mock-apollo-client.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { provideApolloClient } from '@vue/apollo-composable'
  3. import type { DocumentNode } from 'graphql'
  4. import {
  5. createMockClient as createMockedClient,
  6. type MockApolloClient,
  7. type RequestHandler,
  8. } from 'mock-apollo-client'
  9. import createCache from '#shared/server/apollo/cache.ts'
  10. import type { CacheInitializerModules } from '#shared/types/server/apollo/client.ts'
  11. const cacheInitializerModules: CacheInitializerModules = import.meta.glob(
  12. '../../mobile/server/apollo/cache/initializer/*.ts',
  13. { eager: true },
  14. )
  15. export interface ClientRequestHandler {
  16. operationDocument: DocumentNode
  17. handler: RequestHandler
  18. }
  19. let mockClient: Maybe<MockApolloClient>
  20. afterEach(() => {
  21. mockClient = null
  22. })
  23. export const clearMockClient = () => {
  24. mockClient = null
  25. }
  26. const createMockClient = (handlers: ClientRequestHandler[]) => {
  27. if (!mockClient) {
  28. const cache = createCache(cacheInitializerModules)
  29. mockClient = createMockedClient({ cache })
  30. provideApolloClient(mockClient)
  31. }
  32. handlers.forEach((clientRequestHandler) =>
  33. mockClient?.setRequestHandler(
  34. clientRequestHandler.operationDocument,
  35. clientRequestHandler.handler,
  36. ),
  37. )
  38. return mockClient
  39. }
  40. export default createMockClient