apollographql / apollo-client

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
https://apollographql.com/client
MIT License
19.35k stars 2.66k forks source link

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

Open ghost opened 2 years ago

ghost commented 2 years ago

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

seckinozden commented 2 years ago

Are there any updates on this one? We have the exact same issue. We are using @apollo/client@3.5.10.

ghost commented 2 years ago

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

seckinozden commented 2 years ago

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>
  );
}
ghost commented 2 years ago

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

25747 commented 2 years ago

Experiencing the same issue with @apollo/client@3.6.5.

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.

elliottgrieco-toast commented 1 year ago

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
  }
})