Registry / testing / mock-apollo-client

mock-apollo-client

JSON →
library2.0.0jsnpmunverified

Mock Apollo Client is a utility library designed to simplify unit testing of React components that interact with GraphQL APIs via `@apollo/client`. The current stable version is 2.x, which is compatible with `@apollo/client` v4.x. Previous major versions (1.x for Apollo Client v3, and 0.x for Apollo Client v2) exist for backward compatibility. The library helps address limitations found in Apollo Client's built-in `MockedProvider`, such as the inability to assert query/mutation variables, track call counts, dynamically change results after initialization, or easily control loading states. It offers a standalone, framework-agnostic mocking solution that provides granular control over GraphQL operations within tests, making it a powerful alternative for scenarios requiring more advanced testing capabilities than `MockedProvider` offers. Release cadence is tied to major `@apollo/client` updates.

npm install mock-apollo-client
INSTALL
IMPORT
SIG · MOCK-APOLLO-CLIENT
M
mock-apollo-client
testingjavascriptv2.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createMockClient
import { createMockClient } from 'mock-apollo-client';
const { createMockClient } = require('mock-apollo-client');
Primarily designed for ESM usage. While CJS might work via transpilation, direct require is not the recommended or native import style. The library ships with TypeScript types.
createMockClient (type)
import type { ApolloClient } from '@apollo/client'; import { createMockClient } from 'mock-apollo-client';
When mocking, you'll often need to import types from @apollo/client itself for proper type inference and safety.
setRequestHandler
mockClient.setRequestHandler(GET_DOG_QUERY, () => { /* ... */ });
This is a method on the `createMockClient` instance, not a direct export. It's the primary way to define mock responses for specific GraphQL operations.

This quickstart demonstrates how to create a mock Apollo client, define a mock response for a specific GraphQL query using `setRequestHandler`, and render a component wrapped in `ApolloProvider` with the mocked client. It also shows basic assertion of query variables and the rendered output.

import '@testing-library/jest-dom'; import { ApolloProvider, gql } from '@apollo/client/react'; import { render, screen } from '@testing-library/react'; import { createMockClient } from 'mock-apollo-client'; // Imagine this is in dog.jsx export const GET_DOG_QUERY = gql` query getDog($name: String) { dog(name: $name) { id name breed } } `; // Imagine this is in dog.jsx import { useQuery } from '@apollo/client/react'; export const Dog = ({ name }) => { const { loading, error, data } = useQuery(GET_DOG_QUERY, { variables: { name }, }); if (loading) return <p>Loading...</p>; if (error) return <p>{error.message}</p>; return ( <p> {data.dog.name} is a {data.dog.breed} </p> ); }; describe('Dog component', () => { it('renders the dog name and breed', async () => { const mockClient = createMockClient(); mockClient.setRequestHandler(GET_DOG_QUERY, (variables) => { // Assert variables if needed expect(variables.name).toBe('Rufus'); return Promise.resolve({ data: { dog: { id: 1, name: 'Rufus', breed: 'Poodle' } }, }); }); render( <ApolloProvider client={mockClient}> <Dog name="Rufus" /> </ApolloProvider>, ); expect(await screen.findByText('Rufus is a Poodle')).toBeInTheDocument(); }); });
Debug
Known issues
breakingMajor versions of `mock-apollo-client` are tightly coupled to major versions of `@apollo/client`. Using an incompatible version combination will lead to runtime errors or unexpected behavior.
fix
Consult the `mock-apollo-client` README or changelog for compatibility tables. Ensure your `mock-apollo-client` version matches your `@apollo/client` version (e.g., `mock-apollo-client@2.x` for `@apollo/client@4.x`).
affects: >=0.x
gotchaWhen using `setRequestHandler`, remember that the handler function is called with the variables provided to the GraphQL operation. This is your opportunity to assert variable values or dynamically change mock data based on inputs.
fix
Pass a function to `setRequestHandler` that accepts the `variables` argument and perform your assertions or data manipulation within it, e.g., `(variables) => { expect(variables).toEqual({ name: 'test' }); return Promise.resolve(...) }`.
affects: >=0.x
gotcha`mock-apollo-client` is designed to complement, not entirely replace, `@apollo/client/testing`'s `MockedProvider`. For very simple, static mock scenarios, `MockedProvider` might be sufficient. `mock-apollo-client` shines in tests requiring dynamic responses, assertion of call variables/counts, or controlling loading states.
fix
Evaluate your testing needs. If you require more control, such as asserting specific variables, dynamic responses, or error conditions not easily handled by `MockedProvider`, then `mock-apollo-client` is the appropriate choice.
affects: >=0.x
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'query')
Often occurs when an older version of `mock-apollo-client` is used with a newer `@apollo/client` or vice-versa, leading to incompatible client interfaces.
fix
Verify that your `mock-apollo-client` and `@apollo/client` versions are compatible. For `@apollo/client@4.x`, use `mock-apollo-client@2.x`. For `@apollo/client@3.x`, use `mock-apollo-client@1.x`.
ReferenceError: require is not defined in ES module scope
Attempting to use CommonJS `require()` syntax in an ESM project, or when the library is specifically published as ESM-only.
fix
Use ES module `import` syntax: `import { createMockClient } from 'mock-apollo-client';`.
Error: GraphQL query was not found in the mock client's request handlers.
A GraphQL query was executed by the component under test, but no `setRequestHandler` was defined for that specific query in the `mock-apollo-client` instance.
fix
Ensure that `mockClient.setRequestHandler()` is called for every `gql` document (query or mutation) that your component is expected to execute during the test, before rendering the component.
Upgrade
Version history
2.0.0latest on npm
Audit
Dependencies
@apollo/clientrequiredPeer dependency, required at runtime for the components being tested.
Agent activity
10 hits · last 30 days
node
6
Resources
mock-apollo-client — npm install mock-apollo-client · libregistry