Writing Unit and Integration Tests for GraphQL

Tutorial 2 of 5

Introduction

In this tutorial, we will guide you through the process of writing unit and integration tests for GraphQL APIs. The goal is to ensure the correctness of individual queries and their interactions, thus guaranteeing the reliability of your APIs.

You will learn how to:

  • Write unit tests for GraphQL queries and mutations
  • Write integration tests to test the interaction between different parts of your system
  • Use testing frameworks such as Jest and Apollo Server Testing

Prerequisites:

  • Familiarity with JavaScript and Node.js
  • Basic understanding of GraphQL

Step-by-Step Guide

Unit Testing GraphQL

In unit testing, we test individual parts of the code. For GraphQL, this means testing individual queries, mutations, and resolvers.

To begin with, you need to install Jest, a popular testing framework. You can do this by running npm install --save-dev jest.

  1. Setting up Jest:

Create a new file called jest.config.js and add the following content:

module.exports = {
  testEnvironment: 'node',
};
  1. Writing a unit test:

Here's an example of a unit test for a GraphQL query:

// Import the necessary modules
const { graphql } = require('graphql');
const { schema } = require('../schema'); // The schema you've defined

test('Test a query', async () => {
  const query = `
    {
      user(id: "1") {
        name
      }
    }
  `;

  const result = await graphql(schema, query);
  expect(result).toEqual({ data: { user: { name: 'John Doe' } } });
});

In this test, we're executing a GraphQL query and asserting that the result matches our expectations.

Integration Testing GraphQL

Integration testing involves testing how different parts of the system work together. For GraphQL, this could involve testing how queries interact with your database, for instance.

To write integration tests for GraphQL, we can make use of the apollo-server-testing package:

  1. Setting up apollo-server-testing:

Install the package by running npm install --save-dev apollo-server-testing.

  1. Writing an integration test:

Here's an example of an integration test for a GraphQL query:

// Import the necessary modules
const { createTestClient } = require('apollo-server-testing');
const { ApolloServer, gql } = require('apollo-server');
const { schema } = require('../schema'); // The schema you've defined

const server = new ApolloServer({ schema });
const { query } = createTestClient(server);

test('Test a query', async () => {
  const GET_USER = gql`
    {
      user(id: "1") {
        name
      }
    }
  `;

  const res = await query({ query: GET_USER });
  expect(res).toMatchSnapshot();
});

In this test, we're executing a GraphQL query and asserting that the result matches a snapshot, which is a pre-recorded "picture" of the output.

Code Examples

Here are a few more examples of unit and integration tests.

Unit Test:

Testing a mutation:

test('Test a mutation', async () => {
  const mutation = `
    mutation {
      updateUser(id: "1", name: "New Name") {
        name
      }
    }
  `;

  const result = await graphql(schema, mutation);
  expect(result).toEqual({ data: { updateUser: { name: 'New Name' } } });
});

Integration Test:

Testing a mutation with variables:

test('Test a mutation', async () => {
  const UPDATE_USER = gql`
    mutation UpdateUser($id: ID!, $name: String!) {
      updateUser(id: $id, name: $name) {
        name
      }
    }
  `;

  const res = await mutate({ mutation: UPDATE_USER, variables: { id: '1', name: 'New Name' } });
  expect(res).toMatchSnapshot();
});

Summary

In this tutorial, you've learned how to write unit and integration tests for a GraphQL API using Jest and Apollo Server Testing. You've also seen a few examples of how to test queries and mutations.

To continue learning, you can:

  • Explore more advanced testing techniques, such as mocking
  • Learn how to handle errors in your tests
  • Look into other testing tools and frameworks

Here are a few resources to help you on your journey:

Practice Exercises

  1. Write a unit test for a query that returns multiple users.
  2. Write an integration test for a mutation that deletes a user.
  3. Write an integration test that checks for an error when a query is made with invalid input.

Solutions and explanations for these exercises will deepen your understanding and give you practical experience writing tests for GraphQL.