apollo-client icon indicating copy to clipboard operation
apollo-client copied to clipboard

MockedProvider not working if useQuery/useMutation has a customized apollo client

Open RachelSang opened this issue 3 years ago • 2 comments

Due to some reason, our project need to have an another apollo client (different to the one we put in the ApolloProvider)when we call the useMutation/useQuery, we wrap the default method like this:

return useMutation(mutation, { ...options, client: apolloClient2 });,

Intended outcome: We hope we still can use MockedProvider to do the unit test.

Actual outcome: But it is not working if we don't use the default one.It is only working if we use the default hook. Does MockedProvider support if the useQuery/useMutation has a customized apollo client in it ?

Versions we are using apollo cleint 3.3.9

RachelSang avatar Mar 17 '22 23:03 RachelSang

Are there any updates on this one? We have the exact same issue. We are using @apollo/[email protected].

seckinozden avatar Aug 10 '22 09:08 seckinozden

We have to mock the custom hook in jest, so that they just return useQuery & useMutation directly, with no custom client.

ghost avatar Aug 10 '22 23:08 ghost

Our workaround is, we have wrapped our component with ApolloProvider in the parent component, set the client there and did not define any client in our useQuery and useMutation. That way we were able to use MockedProvider.

export const ParentComponent = () => {
  ...  
  return (
    <ApolloProvider client={myClient}>
      <Component
        prop1=bla
        prop2=bla
        ...
      />
    </ApolloProvider>
  );
}

seckinozden avatar Aug 12 '22 14:08 seckinozden

Our project has multiple bffs need to connect, so we have to config the different clients in default userQuery/userMutation.

ghost avatar Aug 14 '22 23:08 ghost

Experiencing the same issue with @apollo/[email protected].

I just rewrote a small component tree using @seckinozden's suggestion and it worked to get tests to pass.

We have multiple microservices, so it made sense to specify the url/client with each query. Using this workaround we'll end up with dozens of apollo providers all over our app - I'm not sure if this will cause any issues but it feels less than ideal.

25747 avatar Aug 16 '22 13:08 25747

The way that I overcame this issue was to structure my code so that I am able to mock the export for my Apollo client as undefined while testing. A bit hacky, but it works --

// Component implementation code:
const MyComponent = () => {
  const { data: queryOneResult } = useQuery(MY_QUERY, {
    client: customApolloClientOne
  })

  const { data: queryTwoResult } = useQuery(MY_QUERY_TWO, {
    client: customApolloClientTwo
  })

  // ...
}

// top of test file:
jest.mock('./apollo-clients', () => {
  return {
    customApolloClientOne: undefined,
    customApolloClientTwo: undefined
  }
})

elliottgrieco-toast avatar Jul 16 '23 14:07 elliottgrieco-toast