Fauna logo
Product
Solutions
Pricing
Resources
Company
Log InGet a DemoSign Up
Fauna logo
Pricing
Customers
Sign Up
© 2022 Fauna, Inc. All Rights Reserved.
graphql

Best practices for testing GraphQL APIs

Nov 12th, 2021
The GraphQL query language was created to help with common API integration problems. It was built to be scalable and aligned with how data is being created and consumed today. GraphQL's intuitive and flexible syntax allows developers to build more performant and flexible applications.
In this article, we will go through what GraphQL is and cover some strategies and best practices involved in testing GraphQL APIs.

What is GraphQL?

GraphQL is a query language layer that operates over a single endpoint. This differs from REST APIs that assign distinct resources to separate URIs while GraphQL always queries the same endpoint.
A GraphQL resolver is a collection of functions that generate responses for a GraphQL query. These resolvers can be written in any language since the GraphQL schema is designed to be uniform in a language-agnostic way.
GraphQL queries are structured to specify the exact data that the query is requesting. Queries are used to read or fetch values while mutations are used to write or post values. In either case, the operation is a simple string that a GraphQL server can parse and respond to with data in a specific format.
Using GraphQL offers various benefits to developers. Frontend queries can request the exact data they need in the shape they need, cutting down on the number of queries that need to be made while also reducing the amount of transformations that are needed to be made to the data. GraphQL also enables development teams to be more flexible. Frontend teams can release changes without waiting for backend changes to catch up, as would be the case with REST. At the same time, backend developers also benefit by not having to worry about versioning APIs to synchronize with the frontend.

How to test a GraphQL API

The primary goal when testing GraphQL APIs is to verify that the schemas, queries, and mutations developed for an application behave as expected on the frontend. There are a wide variety of tools that can aid developers in testing their GraphQL APIs, with some even offering automation. For example, EasyGraphQL is a Node package that can be used to easily set up test suites to check whether your operations are defined in your schemas and whether the input and parameters provided to these APIs are valid. Parasoft allows users to create scripts that can be used to automate API testing. The benefit of using Parasoft is the tool’s strong support for JSON verification which integrates easily with the kind of responses returned from GraphQL endpoints.
GraphQL API testing involves a variety of test types that range from testing the actual implementation of the schemas and resolvers to load and security testing.
Query testing is used to ensure that a given query and any of its parameters returns the correct response. Using EasyGraphQL, you can create an instance of the EasyGraphQLTester after defining your schemas and resolvers as shown below:
const EasyGraphQLTester = require('easygraphql-tester')
const fs = require('fs')
const path = require('path')
const resolvers = require('./resolvers')
const schema = fs.readFileSync(path.join(__dirname, 'schema', schema.gql'), 'utf8')
const tester = new EasyGraphQLTester(userSchema, resolvers)
Once your tester is initialized you can create a test by defining the query you want to test against your resolver bypassing the query and parameters to the .graphql method. This will return a result that you can then use to assert against the expected value, using the testing framework of your choice.
const query = `
 query TEST($id: Integer!) {
   getNameById(id: $id) {
     id
     name
   }
 }
`
tester.graphql(query, undefined, undefined, { id: 1 })
 .then(result => console.log(result))
 .catch(err => console.log(err))
Mutation tests are used to ensure that a query, when successfully executed, persists changes to the database. EasyGraphQL gives users the option to use fixtures to mock the writing of database operations when executing mutations. First, define the mutation you want to test and also the sample input data.
const mutation = `
 mutation CreateUser($input: CreateUserInput!) {
   createUser(input: $input) {
     id
     name
   }
 }
`
const input = {
   input: {
     name: 'test'   
   }
 }
Then pass the input and the mutation to the .mock method of your tester to simulate the mutation. This will return a response that will be the same as the response returned from executing a mutation against a database.
const { data: { createUser } } = tester.mock({ query: mutation, variables: input })
To ensure that your GraphQL APIs remain performant when operating at scale, load testing can be used as a good indicator to test the performance of your APIs. Load testing your GraphQL APIs can be done in the same ways used to test traditional REST APIs. Popular tools such as Apache JMeter can be used to set up test plans containing tests that send requests to your GraphQL servers at a high rate and volume to test its performance.
Security testing should also be conducted on your GraphQL applications to ensure sensitive data isn’t returned without taking the necessary precautions. Tools such as HawkScan can be used to run introspective queries on your GraphQL servers and request a fully inclusive description of the APIs in a single query. These tests can be used to determine if any of the schemas or resolvers defined return any sensitive information so that they can be updated appropriately.
When running these tests against external web services, it is advisable to simulate responses to rather than testing against production instances. Plugin tools such as serverless offline can provide an alternative when testing to avoid unnecessary usage of the production environment as well as reduce the time taken to deploy changes and rerunning tests.

Conclusion

Testing is critical to ensure your users don’t suffer from unforseen bugs. GraphQL is flexible and provides value in your applications when being used to perform CRUD operations on your database.
Fauna is a flexible, developer-friendly, serverless database delivered as a secure and scalable cloud API with a native GraphQL interface. With the core principle of being developer-friendly, Fauna takes care of time-consuming operational tasks letting you focus on building and testing your applications for your users.
Sign-up for free The data API for modern applications is here. Sign-up for free without a credit card and get started instantly. Sign-up now
GraphQL Quick start guide Try our GraphQL quick start guide to get up and running with your first Fauna database in only 5 minutes! Read more

If you enjoyed our blog, and want to work on systems and challenges related to globally distributed systems, serverless databases, GraphQL, and Jamstack, Fauna is hiring!

Share this post

TWITTERLINKEDIN
‹︁ PreviousNext ›︁

Subscribe to Fauna's newsletter

Get latest blog posts, development tips & tricks, and latest learning material delivered right to your inbox.