Mocking Queries and Mutations in Tests

Tutorial 3 of 5

1. Introduction

The goal of this tutorial is to provide you with the knowledge and tools to mock GraphQL queries and mutations in your tests. You will learn how to simulate server responses, allowing you to write tests irrespective of the actual data.

By the end of this tutorial, you will have a clear understanding of:

  • The concept and importance of mocking in testing.
  • How to use jest and @apollo/client to mock GraphQL queries and mutations.
  • How to write and run tests against these mocks.

Prerequisites: Familiarity with JavaScript, React and basic understanding of GraphQL is recommended. You should also have Node.js and npm installed on your machine.

2. Step-by-Step Guide

Concepts

Mocking is a testing technique where we replace real dependencies with fake ones. This allows us to isolate the code we want to test and control the behavior of these dependencies.

In the context of GraphQL, mocking is used to simulate server responses. This is achieved through libraries like @apollo/client for creating a mock client and jest for running tests.

Best Practices and Tips

  • Always clean up mocks after each test to avoid tests interfering with each other.
  • Make your mock data as close to your real data as possible.
  • Test edge cases by manipulating your mock data.

3. Code Examples

Example 1: Mocking a Query

First, we need to install the necessary dependencies.

npm install jest @apollo/client graphql

Let's consider the following GraphQL query that fetches a list of users:

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

We can create a mock for this query as follows:

import { MockedProvider } from '@apollo/client/testing';

const mocks = [
  {
    request: {
      query: GET_USERS,
    },
    result: {
      data: {
        users: [
          { id: '1', name: 'John Doe', email: 'john@example.com' },
          { id: '2', name: 'Jane Doe', email: 'jane@example.com' },
        ],
      },
    },
  },
];

The request field corresponds to the query we want to mock and result is the data that should be returned when the query is executed.

Now, we can use MockedProvider to wrap our component in tests:

import { render } from '@testing-library/react';

test('renders user list', async () => {
  const { findByText } = render(
    <MockedProvider mocks={mocks} addTypename={false}>
      <UserList />
    </MockedProvider>,
  );

  await findByText('John Doe');
  await findByText('Jane Doe');
});

Example 2: Mocking a Mutation

Consider a CREATE_USER mutation:

const CREATE_USER = gql`
  mutation CreateUser($name: String!, $email: String!) {
    createUser(name: $name, email: $email) {
      id
      name
      email
    }
  }
`;

The mock for this mutation would look like:

const userMock = {
  request: {
    query: CREATE_USER,
    variables: {
      name: 'John Doe',
      email: 'john@example.com',
    },
  },
  result: {
    data: {
      createUser: { id: '1', name: 'John Doe', email: 'john@example.com' },
    },
  },
};

The variables field in request corresponds to the variables passed to the mutation.

4. Summary

In this tutorial, we have covered how to mock GraphQL queries and mutations using jest and @apollo/client. Mocking is a powerful technique that allows you to write reliable tests that aren't dependent on actual data.

5. Practice Exercises

Exercise 1: Create a mock for a DELETE_USER mutation and write a test that checks if a user is removed from the list after the mutation is executed.

Exercise 2: Write a test for a GET_USER query that returns a single user. The test should check if the correct user data is displayed.

For further practice, consider manipulating your mock data to test edge cases. For example, you could return an error from your mock to test how your app handles it.