Testing Resolvers
A GraphQL API is easy to test because graphql() is just a function: no HTTP server, no browser. You can test at three levels:
| Level | What you call | Catches |
|---|---|---|
| Unit | a resolver function or the business logic directly | logic bugs, edge cases |
| Integration | graphql({ schema, source, contextValue }) with fake data sources |
wiring, types, nullability, authorization |
| End-to-end | real HTTP requests to a running server | middleware, auth headers, serialization |
Most of your tests should be integration tests through graphql(): they exercise the real schema and resolvers but stay fast.
A tiny test harness
In a real project you'd use Vitest, Jest or node:test. To keep the playground self-contained, here is a 10-line test/assert setup, then a few unit tests of a resolver's logic:
const results = [];
async function test(name, fn) {
try {
await fn();
results.push(`✓ ${name}`);
} catch (error) {
results.push(`✗ ${name}: ${error.message}`);
}
}
const assertEqual = (actual, expected) => {
const a = JSON.stringify(actual), e = JSON.stringify(expected);
if (a !== e) throw new Error(`expected ${e}, got ${a}`);
};
// Code under test: the logic behind a `cartTotal` field.
function cartTotal(items, { couponPercent = 0 } = {}) {
const subtotal = items.reduce((sum, i) => sum + i.unitCents * i.qty, 0);
return Math.round(subtotal * (1 - couponPercent / 100));
}
await test('sums quantity x price', () => {
assertEqual(cartTotal([{ unitCents: 250, qty: 2 }, { unitCents: 100, qty: 1 }]), 600);
});
await test('empty cart is zero', () => assertEqual(cartTotal([]), 0));
await test('applies a coupon', () => assertEqual(cartTotal([{ unitCents: 1000, qty: 1 }], { couponPercent: 15 }), 850));
await test('deliberately failing test', () => assertEqual(cartTotal([{ unitCents: 999, qty: 3 }]), 3000));
console.log(results.join('\n'));✓ sums quantity x price
✓ empty cart is zero
✓ applies a coupon
✗ deliberately failing test: expected 3000, got 2997
The last test fails on purpose so you can see what a failure looks like: the message shows both values.
Integration tests through graphql()
Build the schema with injected dependencies (a fake repository in the context), run real queries, and assert on the JSON. This tests parsing, validation, resolvers and nullability together:
import { graphql, buildSchema } from 'graphql';
// --- the app ---
const schema = buildSchema(`
type Task { id: ID!, title: String!, done: Boolean! }
type Query { tasks(done: Boolean): [Task!]! }
type Mutation { completeTask(id: ID!): Task }
`);
const rootValue = {
tasks: ({ done }, { repo }) => repo.list().filter((t) => done === undefined || t.done === done),
completeTask: ({ id }, { repo, user }) => {
if (!user) throw new Error('Not logged in');
return repo.update(id, { done: true });
},
};
// --- test helpers ---
function fakeRepo(rows) {
const data = rows.map((r) => ({ ...r }));
return {
list: () => data,
update: (id, patch) => {
const row = data.find((r) => r.id === id);
return row ? Object.assign(row, patch) : null;
},
};
}
const execute = (source, context, variableValues) =>
graphql({ schema, rootValue, source, contextValue: context, variableValues })
.then((r) => JSON.parse(JSON.stringify(r))); // plain objects, easy to compare
const results = [];
const test = async (name, fn) => {
try { await fn(); results.push(`✓ ${name}`); } catch (e) { results.push(`✗ ${name}: ${e.message}`); }
};
const assertEqual = (a, e) => {
if (JSON.stringify(a) !== JSON.stringify(e)) throw new Error(`expected ${JSON.stringify(e)}, got ${JSON.stringify(a)}`);
};
const seed = [
{ id: '1', title: 'Write tests', done: false },
{ id: '2', title: 'Ship it', done: true },
];
// --- the tests ---
await test('filters tasks by done', async () => {
const res = await execute('{ tasks(done: false) { id } }', { repo: fakeRepo(seed) });
assertEqual(res, { data: { tasks: [{ id: '1' }] } });
});
await test('completeTask marks the task done', async () => {
const repo = fakeRepo(seed);
const res = await execute('mutation($id: ID!) { completeTask(id: $id) { id done } }', { repo, user: { id: 'u1' } }, { id: '1' });
assertEqual(res.data.completeTask, { id: '1', done: true });
assertEqual(repo.list()[0].done, true);
});
await test('completeTask requires a user', async () => {
const res = await execute('mutation { completeTask(id: "1") { id } }', { repo: fakeRepo(seed) });
assertEqual(res.errors.map((e) => e.message), ['Not logged in']);
assertEqual(res.data, { completeTask: null });
});
await test('unknown task returns null without errors', async () => {
const res = await execute('mutation { completeTask(id: "99") { id } }', { repo: fakeRepo(seed), user: {} });
assertEqual(res, { data: { completeTask: null } });
});
console.log(results.join('\n'));✓ filters tasks by done
✓ completeTask marks the task done
✓ completeTask requires a user
✓ unknown task returns null without errors
Every test builds a fresh fake repository, so tests can't influence each other. The JSON.parse(JSON.stringify(...)) round-trip turns graphql-js's prototype-less objects into plain ones and drops undefined, which keeps comparisons simple.
Testing the schema itself
Schema-level tests are cheap and catch accidental contract changes:
import { buildSchema, printSchema, findBreakingChanges, validateSchema } from 'graphql';
const published = `type Task { id: ID!, title: String!, done: Boolean! }
type Query { tasks(done: Boolean): [Task!]! }`;
const current = buildSchema(`
type Task { id: ID!, title: String!, done: Boolean!, dueDate: String }
type Query { tasks(done: Boolean): [Task!]! }
`);
console.log('schema valid:', validateSchema(current).length === 0);
console.log('breaking changes:', findBreakingChanges(buildSchema(published), current).length);
console.log('snapshot lines:', printSchema(current).split('\n').length);schema valid: true
breaking changes: 0
snapshot lines: 10
A snapshot test stores printSchema(schema) in a file and fails when it changes, so every schema change is reviewed explicitly in a pull request.
What to test
- Resolvers with logic: computed fields, filters, permission checks, error paths.
- Authorization: one test per rule, for allowed and denied users.
- Nullability surprises: what a client sees when a data source fails.
- N+1: count calls to the fake data source for a list query, and assert it stays constant as the list grows.
Tip: Keep the query strings of tests in the same form clients will send (named operations with variables). Tests then double as usage examples.
Test yourself
What is the most practical level for most GraphQL tests?
- Unit tests of graphql-js internals
- Integration tests calling
graphql()with fake data sources - Manual testing in GraphiQL
- Only end-to-end browser tests
Why pass the repository through the context instead of importing it in resolvers?
- It is faster at runtime
- Tests can inject a fake implementation
- graphql-js requires it
- Imports don't work in resolvers
What does a schema snapshot test catch?
- Slow resolvers
- Any unreviewed change to the schema contract
- Network errors
- Missing indexes