How to use mock Service Worker to test vue apollo?
P粉696891871
P粉696891871 2024-03-27 11:37:32
0
1
411

I have set up a mock service worker to test my composition functionality but am getting the error: Default Apollo client with id not found. If you are outside the component setup., use ProvideApolloClient().

I thought I should use provideApolloClient, but pasting it into search brings up nothing.

The documentation shows injecting data in component and simulation mode (that part is not fetched). But instead of testing the component, I'm trying to test a custom composed function (hook) and make sure it interacts correctly with useQuery.

P粉696891871
P粉696891871

reply all(1)
P粉821274260

I think the error message you are getting indicates that Apollo cannot render completely because it cannot find any Apollo clients from the context. This can happen if you call code without an ApolloProvider and with a client as its parent. Even if you are testing the hook, you still have to render the hook wrapped in Apollo's Provider and provide a client instance according to Apollo's documentation. See how your React hook testing library suggests doing this.

Here is an example of what I recommend using @testing-library/react-hooks:

import { ApolloProvider } from '@apollo/client'
import { renderHook } from '@testing-library/react-hooks'
import { client } from './apollo-client'
import { myHook } from './myHook'

it('runs the hook as expected', () => {
  renderHook(() => myHook(), {
    wrapper({ children }) {
      return {children}
    }
  })
  // actions and assertions here
})

I know this won't translate directly to Vue, but I'm sure there is an alternative way to test hooks in Vue. Hope this inspires you in the right direction.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template