Using `createMockClient` for testing non react code?
Asked Answered
E

1

6

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

Emblazonry answered 28/10, 2021 at 15:0 Comment(1)
Hi! Did you manage to find out more about createMockClient and test it? Nothing has been added to the docs yet...Dapper
N
2

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 } }
  )
Nerva answered 27/1, 2022 at 19:24 Comment(2)
This is the correct answer and createMockClient is a supported part of the Apollo Client API.Quincuncial
I don't think createMockClient supports testing error state.Canasta

© 2022 - 2024 — McMap. All rights reserved.