@apollo/react-testing
API reference
Installation
Text
1npm install @apollo/react-testing
MockedProvider
JavaScript
1import { MockedProvider } from "@apollo/react-testing";
The MockedProvider
is a test-utility that allows you to create a mocked version of the ApolloProvider
that doesn't send out network requests to your API, but rather allows you to specify the exact response payload for a given request.
The <MockedProvider />
component takes the following props:
Prop | Type | Description |
---|---|---|
mocks? | ReadonlyArray | An array containing a request object and the corresponding response. |
addTypename? | boolean | A boolean indicating whether or not __typename are injected into the documents sent to graphql. This defaults to true. |
defaultOptions? | DefaultOptions | An object containing options to pass directly to the ApolloClient instance. |
cache? | ApolloCache | A custom cache object to be used in your test. Defaults to InMemoryCache . Useful when you need to define a custom dataIdFromObject function for automatic cache updates. |
resolvers? | Resolvers | Apollo Client local resolvers |
childProps? | object | Props that should be passed down to the child |
Here is an example mocks
prop shape:
JavaScript
1const mocks = [
2 {
3 request: {
4 query: SOME_QUERY,
5 variables: { first: 4 }
6 },
7 result: {
8 data: {
9 dog: {
10 name: "Douglas"
11 }
12 }
13 }
14 },
15 {
16 request: {
17 query: SOME_QUERY,
18 variables: { first: 8}
19 },
20 error: new Error("Something went wrong")
21 }
22]
The above shows that if the request SOME_QUERY
is fired with variables { first: 4 }
that it results in the data in the result
object.
If SOME_QUERY
is fired with variables { first: 8 }
then it results in an error
.
Example
JavaScript
1it("runs the mocked query", () => {
2 render(
3 <MockedProvider mocks={mocks}>
4 <MyQueryComponent />
5 </MockedProvider>
6 )
7
8 // Run assertions on <MyQueryComponent/>
9});