Testing GraphQL APIs in GraphQL
From the GraphQL cheat sheet · Testing · verified Jul 2026
Testing GraphQL APIs
javascript
// Unit testing resolvers
const { expect } = require('chai');
const sinon = require('sinon');
describe('User Resolvers', () => {
let db;
beforeEach(() => {
// Mock database
db = {
user: {
findUnique: sinon.stub(),
findMany: sinon.stub(),
create: sinon.stub(),
update: sinon.stub()
}
};
});
describe('Query.user', () => {
it('should return user by id', async () => {
const mockUser = { id: '1', name: 'John' };
db.user.findUnique.resolves(mockUser);
const result = await resolvers.Query.user(
null,
{ id: '1' },
{ db }
);
expect(result).to.deep.equal(mockUser);
expect(db.user.findUnique.calledWith({
where: { id: '1' }
})).to.be.true;
});
it('should throw error if user not found', async () => {
db.user.findUnique.resolves(null);
try {
await resolvers.Query.user(null, { id: '999' }, { db });
expect.fail('Should have thrown');
} catch (error) {
expect(error.message).to.include('not found');
}
});
});
});
// Integration testing with test server
const { ApolloServer } = require('@apollo/server');
const { gql } = require('graphql-tag');
describe('GraphQL Integration Tests', () => {
let server;
beforeEach(() => {
server = new ApolloServer({ typeDefs, resolvers });
});
it('should fetch users', async () => {
const GET_USERS = gql`
query {
users {
id
name
email
}
}
`;
const res = await server.executeOperation(
{ query: GET_USERS },
{ contextValue: { db: mockDb, user: { id: '1', role: 'USER' } } }
);
// Results live under res.body.singleResult
expect(res.body.singleResult.errors).to.be.undefined;
expect(res.body.singleResult.data.users).to.be.an('array');
});
it('should create post', async () => {
const CREATE_POST = gql`
mutation CreatePost($title: String!, $content: String!) {
createPost(title: $title, content: $content) {
id
title
content
}
}
`;
const res = await server.executeOperation(
{
query: CREATE_POST,
variables: {
title: 'Test Post',
content: 'Test content'
}
},
{ contextValue: { db: mockDb, user: { id: '1', role: 'USER' } } }
);
expect(res.body.singleResult.errors).to.be.undefined;
expect(res.body.singleResult.data.createPost).to.include({
title: 'Test Post',
content: 'Test content'
});
});
});💡 Test resolvers in isolation
⚡ Use test server for integration tests
📌 Mock data sources and context
🟢 Test both success and error cases