Testing React Apollo
Everybody loves testing.
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 .
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.
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.
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.