Back to Apollo Client

MockProvider

docs/source/api/react/testing.mdx

3.14.12.8 KB
Original Source

For more guidance on running tests with MockedProvider, see Testing React components.

MockedProvider

js
import { MockedProvider } from "@apollo/client/testing/react";

The MockedProvider component is a mocked version of ApolloProvider that doesn't send network requests to your API. Instead, it allows you to specify the exact response payload for a given GraphQL operation. This enables you to test your application's operations without communicating with a server.

Props

<table class="field-table"> <thead> <tr> <th>Name / Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>
mocks

ReadonlyArray<MockedResponse>

</td> <td>

An array containing GraphQL operation definitions and their corresponding mocked responses. See Defining mocked responses.

</td> </tr> <tr> <td>
defaultOptions

DefaultOptions

</td> <td>

An object containing options to pass directly to the MockedProvider's ApolloClient instance. See Example defaultOptions object.

</td> </tr> <tr> <td>
cache

ApolloCache<TSerializedCache>

</td> <td>

A custom cache for the MockedProvider's ApolloClient instance to use. Useful when you need to define a custom dataIdFromObject function for automatic cache updates.

By default, MockedProvider creates an InMemoryCache with default configuration.

</td> </tr> <tr> <td>
resolvers

Resolvers

</td> <td>

Deprecated. A collection of local resolvers for the MockedProvider's ApolloClient instance to use.

</td> </tr> <tr> <td>
childProps

object

</td> <td>

Props to pass down to the MockedProvider's child.

</td> </tr> <tr> <td>
showWarnings

boolean

</td> <td>

When a request fails to match a mock, a warning is logged to the console to indicate the mismatch. Set this to false to silence these warnings.

The default value is true.

</td> </tr> </tbody> </table>

Example mocks array

js
const mocks = [
  {
    request: {
      query: GET_DOG,
      variables: { index: 4 },
    },
    result: {
      data: {
        dog: {
          name: "Douglas",
        },
      },
    },
  },
  {
    request: {
      query: GET_DOG,
      variables: { index: 8 },
    },
    error: new Error("Something went wrong"),
  },
];

With the mocks array above:

  • If the GET_DOG operation is executed with variables { index: 4 }, it returns a dog named Douglas.
  • If GET_DOG is executed with variables { index: 8 }, it returns an error.

Usage

See Testing React components.