HMR
HMR

Reputation: 39270

How to use mock service worker to test vue apollo?

I have set up mock service worker to test my composition functions but get the error: Apollo client with id default not found. Use provideApolloClient() if you are outside of a component setup..

Guess I should use provideApolloClient but pasting that in search gives me nothing.

The docs show to inject data in component and mock schema (not getting that part). But I am not testing a component, I am trying to test a custom composition function (hook) and make sure it interfaces with useQuery correctly.

Upvotes: 1

Views: 682

Answers (1)

kettanaito
kettanaito

Reputation: 1564

I think the error message you get suggests that Apollo cannot fully render because it can't find any Apollo Client from the context. This may happen if you're calling a code that doesn't have the ApolloProvider with the client as its parent. Even if you're testing a hook, you would still have to render the hook wrapped in Apollo's Provider and supply the client instance as per Apollo's documentation. Take a look at how your React hook testing library suggests doing that.

Here's an example of what I'm suggesting 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 <ApolloProvider client={client}>{children}</ApolloProvider>
    }
  })
  // actions and assertions here
})

I know this won't directly translate to Vue but I'm certain there's an alternative for testing hooks in Vue. Hope this stirs you in the right direction.

Upvotes: 1

Related Questions