How to stub an external GraphQL API
At Grinta, we block all http calls in our specs, to allow offline spec run and avoid any issues with a 3rd party sites. We recently started to use an external GraphQL Api and needed to spec it properly.
This approach is based on stub on HTTP calls, using Sinatra and JSON fixtures. There are several articles about it, I would advise you to give a look to this one from thoughbot.
The API we are using has two different endpoints: auth and GraphQL querying. The auth part is obvious: stub the endpoint with the expected response 🤷♂️
Now that we got our (fake) token, we can handle the GraphQL endpoint.
It’s a bit trickier, because all our queries will point to the same url, so we will adapt our code to it. Here is a piece of pseudo-code that will do it.
Let’s dig a bit what is done here. foo_mutation? and bar_query? are in fact reading params and looking for a match in the query name. With graphql-client, it is pretty forward, as we can access the operation_name object:
Once we established which query is being called, we can return the appropriate response: JSON in the file or in separate fixtures files, do as you fill most comfortable with.
Remember to force the stub before each specs, and you get your final FakeGraphQL class.
Resources:
- The graphql-client library
- thoughbot article about stubbing external services