{"id":15705,"library":"mock-apollo-client","title":"Mock Apollo Client for Unit Testing","description":"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.","status":"active","version":"2.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/mike-gibson/mock-apollo-client","tags":["javascript","apollo-client","graphql","mock","test","testing","typescript"],"install":[{"cmd":"npm install mock-apollo-client","lang":"bash","label":"npm"},{"cmd":"yarn add mock-apollo-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add mock-apollo-client","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency, required at runtime for the components being tested.","package":"@apollo/client","optional":false}],"imports":[{"note":"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.","wrong":"const { createMockClient } = require('mock-apollo-client');","symbol":"createMockClient","correct":"import { createMockClient } from 'mock-apollo-client';"},{"note":"When mocking, you'll often need to import types from @apollo/client itself for proper type inference and safety.","symbol":"createMockClient (type)","correct":"import type { ApolloClient } from '@apollo/client';\nimport { createMockClient } from 'mock-apollo-client';"},{"note":"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.","symbol":"setRequestHandler","correct":"mockClient.setRequestHandler(GET_DOG_QUERY, () => { /* ... */ });"}],"quickstart":{"code":"import '@testing-library/jest-dom';\nimport { ApolloProvider, gql } from '@apollo/client/react';\nimport { render, screen } from '@testing-library/react';\nimport { createMockClient } from 'mock-apollo-client';\n\n// Imagine this is in dog.jsx\nexport const GET_DOG_QUERY = gql`\n  query getDog($name: String) {\n    dog(name: $name) {\n      id\n      name\n      breed\n    }\n  }\n`;\n\n// Imagine this is in dog.jsx\nimport { useQuery } from '@apollo/client/react';\nexport const Dog = ({ name }) => {\n  const { loading, error, data } = useQuery(GET_DOG_QUERY, {\n    variables: { name },\n  });\n  if (loading) return <p>Loading...</p>;\n  if (error) return <p>{error.message}</p>;\n\n  return (\n    <p>\n      {data.dog.name} is a {data.dog.breed}\n    </p>\n  );\n};\n\ndescribe('Dog component', () => {\n  it('renders the dog name and breed', async () => {\n    const mockClient = createMockClient();\n\n    mockClient.setRequestHandler(GET_DOG_QUERY, (variables) => {\n      // Assert variables if needed\n      expect(variables.name).toBe('Rufus');\n      return Promise.resolve({\n        data: { dog: { id: 1, name: 'Rufus', breed: 'Poodle' } },\n      });\n    });\n\n    render(\n      <ApolloProvider client={mockClient}>\n        <Dog name=\"Rufus\" />\n      </ApolloProvider>,\n    );\n\n    expect(await screen.findByText('Rufus is a Poodle')).toBeInTheDocument();\n  });\n});","lang":"typescript","description":"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."},"warnings":[{"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`).","message":"Major 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.","severity":"breaking","affected_versions":">=0.x"},{"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(...) }`.","message":"When 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.","severity":"gotcha","affected_versions":">=0.x"},{"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.","message":"`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.","severity":"gotcha","affected_versions":">=0.x"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"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`.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'query')"},{"fix":"Use ES module `import` syntax: `import { createMockClient } from 'mock-apollo-client';`.","cause":"Attempting to use CommonJS `require()` syntax in an ESM project, or when the library is specifically published as ESM-only.","error":"ReferenceError: require is not defined in ES module scope"},{"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.","cause":"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.","error":"Error: GraphQL query was not found in the mock client's request handlers."}],"ecosystem":"npm"}