Testing GraphQL React Components

Apollo, GraphQL, React, Jest

There doesn’t seem to be a lot of information around this topic. So I decided to create this page with the intention of keeping it updated with new findings and hopefully people can also contribute with opinions and best practices, and we can all benefit from it.

I recently got myself started into this new cocktail of frameworks: React, Apollo, GraphQL and Jest; And as every developer, I like to test my code. However I found myself struggling with writing tests for React components wrapped around ApolloProviders with GraphQL queries.

Me trying to test React Components

The following describes an example of a component and the 3 approaches I tried for testing it.

First attempt — didn’t work

Take this component as an example. Very simple, it issues a GraphQL query to get a list of bananas and displays a message showing how many items are in the response array.

So my first attempt of testing the component produced the following error.

Invariant Violation: Could not find "client" in the context of "Apollo(BananaComponent)". Wrap the root component in an <ApolloProvider>

Second attempt — not quite good

Looks like I needed to include the ApolloProvider as part of the test. And based on examples like this one, I wrote a test that looked something like this:

It sort of worked. But it felt ugly.

Also, I couldn’t find any good documentation around mocking the ApolloClient, or using the MockedProvider and mockNetworkInterface(). So I found myself doing trial and error while writing the test.

Third attempt —my favorite, so far

I decided to try a different approach in which the Component is separated from the Apollo/GraphQL wrapper. And you can test them both in isolation.

My new component looks like this (Note that the query has been extracted to another file):

The test looks like this (No Apollo or GraphQL related stuff):

The GraphQL query is in a separate file:

And then I can also leverage snapshot-testing for the query itself, which is pretty cool.

This is how I’m testing my components so far. I feel comfortable with this approach — looks clean, readable and it uses Jest snapshots. However I will continue to explore new options and will try to document them as much as possible.

Feel free to comment down below if you think I’m saying bullshit. Or any new ideas will be greatly appreciated as well!