0
0
GraphQLquery~5 mins

Resolver unit tests in GraphQL

Choose your learning style9 modes available
Introduction

Resolver unit tests check if small parts of your GraphQL server work correctly. They help find mistakes early and keep your code reliable.

When you add a new resolver to fetch or change data.
When you fix a bug in a resolver and want to make sure it stays fixed.
When you want to make sure your resolver returns the right data for different inputs.
When you update your data source and want to check if resolvers still work.
When you want to prevent future changes from breaking your resolver logic.
Syntax
GraphQL
describe('resolverName', () => {
  it('should do something expected', () => {
    // Arrange: set up data or mocks
    // Act: call the resolver function
    // Assert: check the result matches expected
  });
});

describe groups related tests.

it defines a single test case.

Examples
This test checks if the getUser resolver returns the correct user name when given ID '1'.
GraphQL
describe('getUser', () => {
  it('returns user data for valid ID', () => {
    const result = getUser(null, { id: '1' }, context);
    expect(result.name).toBe('Alice');
  });
});
This test verifies that createPost returns the post with the right title after creation.
GraphQL
describe('createPost', () => {
  it('creates a post and returns it', () => {
    const input = { title: 'Hello', content: 'World' };
    const result = createPost(null, { input }, context);
    expect(result.title).toBe('Hello');
  });
});
Sample Program

This example shows two tests for the getUser resolver: one for a valid user ID and one for an invalid ID.

GraphQL
const { describe, it, expect } = require('@jest/globals');

// Sample resolver function
function getUser(parent, args, context) {
  const users = { '1': { id: '1', name: 'Alice' }, '2': { id: '2', name: 'Bob' } };
  return users[args.id] || null;
}

describe('getUser resolver', () => {
  it('returns user data for valid ID', () => {
    const result = getUser(null, { id: '1' }, null);
    expect(result).toEqual({ id: '1', name: 'Alice' });
  });

  it('returns null for invalid ID', () => {
    const result = getUser(null, { id: '3' }, null);
    expect(result).toBeNull();
  });
});
OutputSuccess
Important Notes

Use mocks to simulate data sources when testing resolvers.

Keep tests small and focused on one behavior.

Run tests often to catch errors early.

Summary

Resolver unit tests check small parts of your GraphQL server.

They help make sure your resolvers return correct data.

Write simple tests using describe and it blocks.