Using `createMockClient` for testing non react code?

Viewed 329

I have mixed application that uses Apollo for both React and non-react code. However, I can’t find documentation or code examples around testing non-react code with the apollo client,not using MockedProvider. I did, however, notice that apollo exports a mock client from the testing directory.

import { createMockClient } from '@apollo/client/testing';

I haven’t found any documentation about this API and am wondering if it’s intended to be used publicly and, if not, what the supported approach is for this.

The reason I need this is simple: When using Next.js’ SSR and/or SSG features data fetching and actual data rendering are split into separate functions. So the fetching code is not using React, but Node.js to fetch data. Therefore I use apolloClient.query to fetch the data I need.

When trying to wrap a react component around that fetching code in a test an wrap MockedProvider around that the apolloClient’s query method always returns undefined for mocked queries - so it seems this only works for the useQuery hook?

Do you have any idea how to mock the client in non-react code? Thank you for your support in advance. If you need any further information from me feel free to ask.

Regards, Horstcredible

1 Answers

I was in a similar position where I wanted to use a MockedProvider and mock the client class, rather than use useQuery as documented here: https://www.apollographql.com/docs/react/development-testing/testing/

Though it doesn't seem to be documented, createMockClient from '@apollo/client/testing' can be passed the same mocks as MockedProvider to mock without useQuery. These examples assume you have a MockedProvider:

export const mockGetAssetById = async (id: Number): Promise<any> => {
  const client = createMockClient(mocks, GetAsset)
  const data = await client.query({
    query: GetAsset,
    variables: id,
  })
  return data
}

Accomplishes the same as:

const { data } = useQuery(
    GetAsset,
    { variables: { id } }
  )
Related