Mock Apollo Client for Unit Testing

2.0.0 · active · verified Tue Apr 21

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.

Common errors

Warnings

Install

Imports

Quickstart

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

view raw JSON →