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-clientVerified import paths — ran on the pinned version, not inferred.
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.
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`).
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(...) }`.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.
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`.
Use ES module `import` syntax: `import { createMockClient } from 'mock-apollo-client';`.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.