Apollo (v3)
Last updated
Was this helpful?
Last updated
Was this helpful?
This plugin sets up an apollo client with a mock graphql backend to test components that fetch data via graphql.
Setup required peer dependencies: , , , and .
Install via yarn or npm
Add to plugins:
After adding the plugin to your mount
/shallow
, it can be used in your tests like so:
apolloContext(options) => EnzymePlugin
options
(Object
):
options.possibleTypes
(PossibleTypesMap
[optional]): Useful if your app is using fragments on unions and interfaces. Example:
EnzymePlugin
: The plugin which can be passed to createMount
/createShallow
.
This plugin also allows some configuration to be passed at mount-time:
Example:
Help! My mocks don't seem to be working.
We've found there are a few typical reasons that mocks fail. Let's assume we're working with a very simple GraphQL schema like this:
What are the main causes of mocks not working?
Mock names don't align with schema names
You need to make sure that the type name and field name you're trying to mock exactly match your schema. Here's an example of how this problem might arise:
Wrong data types
If you call a mutation or pass arguments to a query, you need to make sure that the data passed in matches the schema data types, otherwise your mock function won't get called. For example, if you pass in a null argument where your schema is expecting a defined value, the call will fail and your mock won't get run.
Not waiting for results
The apollo client / mock GraphQL backend operate asynchronously, so when a new query or mutation is made, you can't expect it to be sychronously completed and must instead wait for it to finish.
Ideally, your component has a prop that returns a promise that is completed when your mutation completes. In that case, you can simply await
that promise:
However, sometimes you might not be able to get a handle to a promise. In that case you can typically just wait a tick and the async operations will be resolved:
options.schema
(IExecutableSchemaDefinition
): the same object passed to .
options.defaultMocks
(IMocks
[optional]): default resolvers for the mock graphql backend. These objects are the same as the ones outlined in the .
apolloMocks
(IMocks
[optional]): resolvers for the mock graphql backend. These objects are the same as the ones outlined in the . The mocks defined here will be deeply merged with the ones defined at plugin configuration time.