mock-apollo-client.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { provideApolloClient } from '@vue/apollo-composable'
  3. import {
  4. createMockClient as createMockedClient,
  5. type MockApolloClient,
  6. type RequestHandler,
  7. } from 'mock-apollo-client'
  8. import createCache from '#shared/server/apollo/cache.ts'
  9. import type { CacheInitializerModules } from '#shared/types/server/apollo/client.ts'
  10. import type { DocumentNode } from 'graphql'
  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