Testing React Apollo

Everybody loves testing.

Nutritious tests help you grow up to be big and strong.

If you are like me, you have been trying to figure out how to test react-apollo and redux components, because you care.

Want the code? Skip to Github.

Along the way, you probably found a bunch of blog posts telling you enzyme is cool these days [1].

Because you like isolation, you try and keep your component tests simple snapshot tests:

But testing React + Redux + GraphQL is confusing. Its hard to understand how to test your components once they are inside of containers.

Apollo containers pretty much work like this.

You have 2 objectives:

  • Make sure GraphQL provides the correct data to your component based on props.
  • Make sure that Redux and GraphQL work together correctly when users interact with your components.

Here’s an example of a container which uses Redux and GraphQL to provide the props to our component:

The important thing to note here, is that we are dispatching actions from inside the prop added by GraphQL (onPokemonLoadStarted, onPokemonLoaded, etc…)… And we want to test that stuff… we also are expecting some data to be retrieved by Apollo, but we don’t want to make actual network requests for this data, we want to use mocked data.

What its like to use mocked data.

Use the MockProvider from react-apollo to make your tests easy to understand and performant!

These tests show how to use components in your enzyme tests to ensure that Redux and GraphQL are working correctly. In addition, you can rebuild the data used by the mocks by making real network requests and saving the result to a file. This makes it easy to update your tests if your data changes.

If you want to run this code and see how it all works, checkout the repo here.

…happy testing.
  1. https://paradite.com/2017/11/16/test-react-apollo-components-enzyme-examples/