Testing GraphQL in 3 minutes

Written by colecodes | Published 2018/04/21
Tech Story Tags: graphql | javascript | node | apollostack | software-development

TLDRvia the TL;DR App

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.

Schema

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?

Resolvers

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


Published by HackerNoon on 2018/04/21