Testing GraphQL in 3 minutesby@colecodes
27,849 reads
27,849 reads

Testing GraphQL in 3 minutes

by Cole TurnerApril 21st, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

You look outside the window and see the clouds crawling on by while you take a sip of your morning coffee and ask yourself:

Company Mentioned

Mention Thumbnail
featured image - Testing GraphQL in 3 minutes
Cole Turner HackerNoon profile picture

You look outside the window and see the clouds crawling on by while you take a sip of your morning coffee and ask yourself:

“How exactly do I test my GraphQL resolvers?”

I never said I was a mind reader. But for the folks out there that are wondering that very same question, here goes.


The first thing you want to cover is schema composition. Mocking your schema lets you write tests with real queries that test your type definitions. These tests will save you from a magnitude of potential glitches including typos and type conflicts.

Mock the schema and write test cases for every query you can imagine. Add cases for happy paths, errors, and test different contexts as well. Declaring these concerns gives us the full integration testing our Schema needs and peace of mind. Here’s how I like to do it:

In the example above we iterate through the test cases using the declared fixtures. These fixtures contain the query that will execute against our mock schema. We can specify variables, context, and the expected output from the query. This gives developers peace of mind that GraphQL can make an executable schema out of type definitions. But what about resolvers? What about integration testing beyond GraphQL?


The really neat thing about resolvers is that they’re pure functions — which makes writing tests super easy and satisfying. For a refresh, here’s what a resolver function looks like:

Pure functions are great for testing because there’s no internal state and no mutable payloads to worry about. Mocking the shape of these arguments we can test resolvers and add integration coverage to our test suites. This way we know our schema is valid and integrates with underlying services.

Here’s something simple to get started:

I like this pattern because I’ve found co-locating tests with your Schema to be just as advantageous to putting tests next to React components. It makes it easier to remember to write tests and helps the next developer gather the big picture. Friction when writing tests is the worst productivity killer at the cost of the testing coverage. Making tests easier to write is a no-brainer.

Thanks for reading! GraphQL and Apollo are awesome frameworks that make building a schema in JavaScript a pleasure. If you find some other pattern that does the same for you — please feel free to share.

Discover more