Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Evolving and Testing

Testing GraphQL APIs

Learn how to test GraphQL APIs: unit-test resolvers, run queries against the schema without HTTP, test auth and errors, and check schema contracts in CI.

A GraphQL API has more moving parts than a single REST route: a schema, many small resolvers, a context, and a client that can ask for any combination of fields. The good news is that GraphQL is easy to test, because an operation is just a function call: execute(schema, query, variables, context) returns a plain object. You do not need a network, a browser or even a running server for most tests.

No GraphQL library runs on this site, so real test code is read-only and shown in the common shapes. The runnable examples use a stand-in test harness written in plain Node, with a tiny hand-written executor and assert. The testing ideas carry over to Jest, Vitest, node:test, pytest and similar tools. If you have not seen resolvers yet, read Resolvers first.

A test pyramid for GraphQL

Resolver tests Call one function with fake context.
Operation tests Run a query against the schema.
HTTP tests A few end-to-end checks.
Schema checks Catch breaking changes in CI.

Many small tests, a few big ones.

1 / 2

Unit-testing resolvers

A resolver is a function of (parent, args, context, info). Keep resolvers thin: they check permissions, call a service or data source, and return the result. Then you can test the business logic directly, and test a resolver by passing a fake context:

JavaScript
// read-only: shape of a typical test (Jest/Vitest style)
test("book resolver returns the book from the data source", async () => {
  const context = { db: { books: { byId: async (id) => ({ id, title: "Dune" }) } } };
  const book = await resolvers.Query.book(null, { id: "1" }, context);
  expect(book.title).toBe("Dune");
});

Fast, focused and independent of the schema. It does not prove that the schema and resolvers fit together, which is what the next level is for.

Executing operations without HTTP

Most of your tests should run real GraphQL documents against the real schema in-process. In Node with the reference library, that is one call to graphql() or execute():

JavaScript
// read-only: the graphql-js entry point
import { graphql } from "graphql";

const result = await graphql({
  schema,
  source: "query ($id: ID!) { book(id: $id) { title } }",
  variableValues: { id: "1" },
  contextValue: { db: fakeDb, user: { id: "u1", role: "reader" } },
});

Many server libraries also provide a helper, such as server.executeOperation(...). In Python, libraries such as Strawberry and Ariadne offer a schema.execute(...) method in the same spirit. The result is the usual { data, errors } object, so you assert on plain data.

The advantages are speed (no sockets, thousands of tests per second), and control: you choose the context, so you can test the same query as an anonymous user, a normal user and an admin.

A stand-in harness

The harness below has three parts: a tiny schema-like resolver map, a tiny executor that handles one level of fields (with an error path), and a few tests with a test() helper that prints pass or fail. The executor is a stand-in, but it behaves like the real thing in the ways the tests rely on: it applies resolvers field by field and puts failures in errors.

Node.js A stand-in executor and test harness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last test fails on purpose, so you can see what a failure looks like. Fix the expected number to 2 and run it again. Notice the style of the other tests: they assert on specific values (explicit assertions) and cover the interesting failure modes: a missing record, an unauthorized field and an authorized one.

Snapshots versus explicit assertions

A snapshot test stores the whole result the first time and compares against it later. It is quick to write and good for big, stable outputs such as the introspection result or a printed schema. For ordinary queries, prefer explicit assertions: they say what matters, fail with a clear message, and do not let a reviewer approve a wrong snapshot with one keystroke. A good compromise is to assert the important fields explicitly and snapshot only the shape of a large payload.

Testing auth and errors

Cover the unhappy paths. For every field or mutation that has a rule, write at least:

  • an anonymous test (expect an authentication error or null),
  • a wrong-role test (expect a permission error), and
  • an allowed test.

Test errors as data too: for a mutation that returns a payload with user errors or a result union (see Modeling Errors), assert on the typed result, not on a thrown exception. Check the extensions.code of top-level errors, because clients branch on codes, not on message text. The execution rules behind partial results and null bubbling are in How Execution Works and How Errors Behave.

Also test limits: a query that is too deep or too expensive must be rejected (see Query Depth, Complexity and Other Attacks), and a batch of resolvers should issue the expected number of database calls (see The N+1 Problem and DataLoader). Counting queries in a test catches N+1 regressions before production does.

Testing with a client and over HTTP

Keep a handful of tests that go through the real HTTP layer (with your framework's test client): one that checks authentication middleware, one for CORS, and one for an error status. They are slower, so keep them few. Client-side code can be tested by mocking the transport, so components render fixed data and you check loading and error states.

Contract and schema checks in CI

Your schema is a contract with every client. Add automated checks:

  • Schema printing check: print the SDL to a file that is committed, and fail CI if the generated file differs from the committed one. Every schema change then shows up in code review.
  • Breaking-change detection: compare the new schema with the one in production (or the last release) and fail if a field, type or argument was removed or made stricter. Tools such as GraphQL Inspector and schema registries do this; the idea is built in Schema Evolution, Federation and Tooling.
  • Operation validation: validate every query document in your client code against the schema. Code generation (see Clients, Apollo and Code Generation) often does this as a side effect.

The next stand-in is a tiny schema check: it compares two type maps and reports what was removed.

JS A stand-in schema contract check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The added rating field is not reported, because additions are safe. The removed year field and the changed return type are reported. (Making a nullable output field non-null is technically only risky in some situations, so real tools classify it with care; this stand-in simply flags every change.)

A practical checklist

  1. Keep resolvers thin and test the services behind them.
  2. Run most tests as in-process operations with a controlled context.
  3. For each rule: anonymous, forbidden and allowed cases.
  4. Assert on explicit values; use snapshots sparingly.
  5. Count data-source calls to catch N+1 regressions.
  6. Print the schema, commit it, and check for breaking changes in CI.
  7. Keep a few end-to-end HTTP tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can most GraphQL tests run without HTTP?

    Calling the execute function with a schema, query, variables and context is fast and gives full control over the context.
  2. 2. Which set of tests is best for a field protected by a role check?

    Rules fail in the negative cases, so test who is refused as well as who is allowed.
  3. 3. When is a snapshot test a good fit?

    Snapshots suit big outputs where reviewing a diff is useful. Small queries read better with explicit assertions.
  4. 4. What does a breaking-change check in CI compare?

    It reports removed or stricter fields, types and arguments that could break existing clients.

Summary

  • An operation is a function call, so most tests run in-process against the real schema with a chosen context.
  • Keep resolvers thin; unit-test the services and test resolvers with a fake context.
  • Cover anonymous, forbidden and allowed cases; assert on errors[].extensions.code and typed error payloads.
  • Prefer explicit assertions; use snapshots for large, stable outputs.
  • Count data-source calls and reject over-limit queries in tests.
  • Commit the printed schema and check for breaking changes in CI.
  • The executor and harness here are stand-ins for real libraries.

Next: Schema Evolution, Federation and Tooling.