Testing a GraphQL API

Intermediate · 12 min

Test a schema by executing real queries against it, directly with graphql() and through yoga.fetch, including errors, auth and schema snapshots.

Before thisA server with GraphQL YogaContext and resolver argumentsErrors and partial responses

Lester Fernandez · 12 min

Testing a GraphQL API

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Lester FernandezReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The cheapest strong test of a GraphQL API is to execute a real query against the real schema and assert on data and errors.
  • Calling graphql() directly skips HTTP and lets you pass any context, which makes auth and per-user cases easy to test.
  • A server's fetch handler, like yoga.fetch, tests the HTTP layer and plugins in process without opening a port.
  • Test the failure paths too: validation errors, missing variables, unauthenticated and forbidden calls.
  • Unit-testing a resolver on its own misses the schema wiring, so prefer operation-level tests and keep resolver unit tests for pure logic.

What is worth testing

A GraphQL API has more surface than it looks. The schema is a contract, resolvers produce data, context decides who is calling, validation rejects bad requests before any code runs, and plugins add behaviour such as limits. A test strategy has to touch the layers that break in practice, which are mostly the joints between them: a field renamed in the schema but not the resolver, a nullable field that should not be, a resolver that forgets to check the user.

The most useful test of all is also the simplest. Send a real operation to the real schema and check what comes back.

Execute against the schema

GraphQL’s reference library, graphql, has a graphql() function that parses, validates and executes a query string. No server, no port, no HTTP. I ran these tests with Node’s built-in node:test runner (Node 26) against a small Yoga schema with graphql 16.15.0:

import { test } from "node:test";
import assert from "node:assert/strict";
import { graphql } from "graphql";
import { schema } from "./schema.js";

const run = (source, variableValues, contextValue = {}) =>
  graphql({ schema, source, variableValues, contextValue });

test("query returns books with authors", async () => {
  const { data, errors } = await run("{ books { title author { name } } }");
  assert.equal(errors, undefined);
  assert.equal(data.books[0].author.name, "Ursula");
});

test("mutation with variables", async () => {
  const { data } = await run(
    "mutation($t: String!, $a: ID!) { addBook(title: $t, authorId: $a) { id title } }",
    { t: "Test", a: "1" },
  );
  assert.equal(data.addBook.title, "Test");
});

Both passed. A real query exercised the type definitions, resolver wiring and the nested author resolver together, which a resolver-only unit test would not. You choose the contextValue, so you can run the same query as an anonymous caller and as an admin with no token handling at all.

Test the failure paths

Errors are part of the contract. These also passed:

test("missing required variable", async () => {
  const { data, errors } = await run(
    "mutation($t: String!, $a: ID!) { addBook(title: $t, authorId: $a) { id } }",
    { a: "1" },
  );
  assert.equal(data, undefined);
  assert.match(errors[0].message, /\$t/);
});

test("unknown field fails validation", async () => {
  const { errors } = await run("{ books { nope } }");
  assert.match(errors[0].message, /Cannot query field "nope"/);
});

For validation failures data is absent altogether; for a resolver error on a nullable field it is present with a null at that path; for a non-null field the null spreads upward, as described in errors and partial responses. Each is a different assertion, so write one per case you care about. For authorization, the earlier lesson’s tests check errors[0].extensions.code for UNAUTHENTICATED and FORBIDDEN; see authentication and authorization for the cases.

Through the HTTP layer, in process

Direct execution skips things that live around the schema: context functions that read headers, plugins such as limits and persisted queries, error masking, status codes. To cover them without starting a server, use the handler. GraphQL Yoga’s yoga.fetch takes a standard Request-shaped input and returns a Response:

const yoga = createYoga({ schema, logging: false });
const res = await yoga.fetch("http://localhost/graphql", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ query: "{ books { id } }" }),
});
assert.equal(res.status, 200);

That passed too. This is the right level for tests of limits, persisted queries and header-based auth, because those are plugins. I used this exact pattern for the depth, cost and introspection results in earlier lessons. It is quick enough to run thousands of times.

Reserve a real network test, with the server listening on a port and a client library calling it, for a handful of end-to-end checks. Contract testing for APIs covers the broader approach.

Snapshot the schema

The public contract is the schema. A schema test prints it and compares it to a committed file:

import { printSchema } from "graphql";
test("schema matches the committed contract", () => {
  assert.equal(printSchema(schema), readFileSync("schema.graphql", "utf8"));
});

My run asserted only that Book and the addBook signature appeared, since I had no committed file, but the full comparison is the point: any change to a field, an argument or nullability shows up as a failing test and a diff. It is the local version of the checks in schema registry and CI checks, and it prompts the question evolving a schema without versions answers: is this change safe for existing clients.

Resolver units and mocks

Plain unit tests still have a place for logic that has no GraphQL in it: a pricing function, a permission check, a data mapper. Keep those as ordinary functions and test them directly. For the data layer, use a real test database where you can; mocking everything leaves a test that proves your mocks work. The video below mocks the database and tests resolvers with context, which is a legitimate, faster option when a database is awkward.

Federation adds one more layer: test each subgraph alone, including _entities calls, as shown in Apollo Federation basics, and run composition in CI.

What the video covers

Lester Fernandez’s “Testing a GraphQL Schema with Jest and TypeScript” runs about 12 minutes. Its chapters are: install dependencies, configure Jest, a Jest configuration, create an npm script, server-side validation, run the login mutation, and run a bad test. I could not confirm its publication date, and the setup is Jest with TypeScript, so the tooling differs from the node:test code above. The idea is the same: run a mutation, including a failing one, against the schema and check the result. It is chosen for that match with the lesson. The runner-up is Ben Awad’s 2018 video on testing resolvers with a mocked context and database.

Where this fits

Tests tell you the API behaves. The next two lessons tell you how it behaves in production: observability and tracing first.

Check yourself

  1. 01What do you give up by testing resolvers as plain functions?

    You skip the schema, so typos in field names, wrong types, nullability and argument handling are never exercised.

  2. 02How do you test as a particular user without a login flow?

    Pass the context directly to graphql() with a user object, or send a test token through a fetch handler whose context function reads it.

  3. 03What can a schema snapshot test catch?

    An accidental change to the public contract, such as a renamed field or a changed nullability, because the printed schema no longer matches the committed one.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark