StackPractices
advanced By Mathias Paulenko

Complete Guide to GraphQL Testing

Test GraphQL APIs at every layer: resolver unit tests, schema integration tests, contract and security tests, and E2E for critical operations.

Introduction

Testing a GraphQL API isn’t testing a REST API with a different wire format. There’s one endpoint, clients send arbitrary queries, and the bugs that hurt in production — wiring mistakes, N+1s, auth gaps on nested fields, schema drift — each live at a different layer. A resolver unit test will never catch that posts resolves to the wrong loader; an E2E test takes thirty seconds to tell you what a unit test catches in milliseconds.

This guide covers the layers that earn their keep: resolver unit tests, schema integration tests, contract and security checks, and E2E for the flows that can’t afford to break. The schema side of the contract is covered in Complete Guide to GraphQL Schema Design.

Testing Pyramid for GraphQL

flowchart diagram: E2E<br/>few, slow, full stack
  • Unit tests hit individual resolver functions in isolation — fast, cheap, and where logic bugs should die.
  • Integration tests execute real operations against the schema with mocked or test data sources, catching wiring bugs unit tests structurally can’t see.
  • E2E tests run the full stack from HTTP to database — slow and expensive, reserved for flows that justify the cost.
  • Contract and security checks sit beside the pyramid rather than inside it: they’re cheap CI gates that guard the schema itself.

Unit Testing Resolvers

Resolvers are close to pure functions — (parent, args, context, info) => result — which makes them the cheapest test target in the system. You provide inputs, assert outputs, and inject everything else through context.

Basic Resolver Test

import { describe, it, expect, vi } from "vitest";

const resolvers = {
  Query: {
    user: async (_parent, { id }, ctx) => {
      return ctx.db.users.findById(id);
    },
  },
  User: {
    fullName: (user) => `${user.firstName} ${user.lastName}`,
    age: (user) => {
      const born = new Date(user.birthDate);
      const now = new Date();
      return Math.floor((now - born) / (365.25 * 24 * 60 * 60 * 1000));
    },
  },
};

describe("User resolvers", () => {
  describe("Query.user", () => {
    it("returns user by id", async () => {
      const mockDb = {
        users: { findById: vi.fn().mockResolvedValue({ id: "1", firstName: "Alice", lastName: "Smith" }) },
      };
      const result = await resolvers.Query.user(null, { id: "1" }, { db: mockDb });
      expect(result).toEqual({ id: "1", firstName: "Alice", lastName: "Smith" });
      expect(mockDb.users.findById).toHaveBeenCalledWith("1");
    });

    it("returns null when user not found", async () => {
      const mockDb = {
        users: { findById: vi.fn().mockResolvedValue(null) },
      };
      const result = await resolvers.Query.user(null, { id: "999" }, { db: mockDb });
      expect(result).toBeNull();
    });
  });

  describe("User.fullName", () => {
    it("concatenates first and last name", () => {
      const result = resolvers.User.fullName({ firstName: "Alice", lastName: "Smith" });
      expect(result).toBe("Alice Smith");
    });
  });

  describe("User.age", () => {
    it("calculates age from birth date", () => {
      const user = { birthDate: "1990-01-01" };
      const result = resolvers.User.age(user);
      expect(result).toBeGreaterThan(30);
      expect(result).toBeLessThan(40);
    });
  });
});

Testing Mutations

Mutation tests cover the two error channels separately — payload errors and thrown errors:

describe("Mutation.createUser", () => {
  it("creates a user and returns it", async () => {
    const mockDb = {
      users: {
        create: vi.fn().mockResolvedValue({ id: "1", name: "Alice", email: "alice@example.com" }),
      },
    };
    const ctx = { db: mockDb, user: { id: "admin", role: "ADMIN" } };
    const result = await resolvers.Mutation.createUser(null, { input: { name: "Alice", email: "alice@example.com" } }, ctx);
    expect(result.user).toEqual({ id: "1", name: "Alice", email: "alice@example.com" });
    expect(result.errors).toEqual([]);
  });

  it("returns error when email already exists", async () => {
    const mockDb = {
      users: {
        findUnique: vi.fn().mockResolvedValue({ id: "2", email: "alice@example.com" }),
      },
    };
    const ctx = { db: mockDb, user: { id: "admin", role: "ADMIN" } };
    const result = await resolvers.Mutation.createUser(null, { input: { name: "Alice", email: "alice@example.com" } }, ctx);
    expect(result.user).toBeNull();
    expect(result.errors[0].field).toBe("email");
    expect(result.errors[0].code).toBe("CONFLICT");
  });

  it("throws when not authenticated", async () => {
    const ctx = { db: {}, user: null };
    await expect(
      resolvers.Mutation.createUser(null, { input: { name: "Alice", email: "alice@example.com" } }, ctx)
    ).rejects.toThrow("Not authenticated");
  });
});

Testing with DataLoader

Batching is a correctness property — test it, not just the resolved value:

import DataLoader from "dataloader";

describe("Product.category resolver with DataLoader", () => {
  it("batches category loads", async () => {
    const batchFn = vi.fn().mockResolvedValue([{ id: "1", name: "Electronics" }]);
    const categoryLoader = new DataLoader(batchFn);
    const ctx = { loaders: { categoryLoader } };

    const products = [{ categoryId: "1" }, { categoryId: "1" }, { categoryId: "1" }];
    const results = await Promise.all(
      products.map((p) => resolvers.Product.category(p, null, ctx))
    );

    expect(results).toHaveLength(3);
    expect(batchFn).toHaveBeenCalledTimes(1); // Batched into one call
  });
});

The batch function must return results in the same order as the keys — a second test worth writing is one where a user has no posts, because a misaligned batch silently returns the wrong data.

Integration Testing the Schema

Integration tests run real GraphQL operations through the schema — parser, validation, resolvers, context — with a test or mocked data layer. This is the layer where wiring bugs surface: wrong field names, a resolver that never got registered, context shape mismatches.

Using Apollo Server with a Test Database

import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { createTestContext } from "./test-context";

const typeDefs = `
  type User { id: ID! name: String! email: String! }
  type Query { user(id: ID!): User users: [User!]! }
  type Mutation { createUser(input: CreateUserInput!): CreateUserPayload! }
  input CreateUserInput { name: String! email: String! }
  type CreateUserPayload { user: User errors: [String!]! }
`;

const resolvers = { /* ... */ };

let server, url;

beforeAll(async () => {
  server = new ApolloServer({ typeDefs, resolvers });
  const { url: serverUrl } = await startStandaloneServer(server, {
    context: async () => createTestContext(),
  });
  url = serverUrl;
});

afterAll(async () => {
  await server.stop();
});

async function execute(query, variables = {}) {
  const response = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query, variables }),
  });
  return response.json();
}

describe("GraphQL integration", () => {
  it("creates and retrieves a user", async () => {
    const createResult = await execute(`
      mutation {
        createUser(input: { name: "Alice", email: "alice@example.com" }) {
          user { id name email }
          errors
        }
      }
    `);
    expect(createResult.data.createUser.user.name).toBe("Alice");
    expect(createResult.data.createUser.errors).toEqual([]);

    const userId = createResult.data.createUser.user.id;
    const getResult = await execute(`
      query GetUser($id: ID!) {
        user(id: $id) { id name email }
      }
    `, { id: userId });
    expect(getResult.data.user.name).toBe("Alice");
  });

  it("returns errors for invalid input", async () => {
    const result = await execute(`
      mutation {
        createUser(input: { name: "", email: "invalid" }) {
          user { id }
          errors
        }
      }
    `);
    expect(result.data.createUser.user).toBeNull();
    expect(result.data.createUser.errors).toHaveLength(2);
  });
});

Using graphql-tools for Schema Testing

When you don’t need HTTP, graphql() executes operations directly against the executable schema — faster than standing up a server:

import { makeExecutableSchema } from "@graphql-tools/schema";
import { graphql } from "graphql";
import { describe, it, expect } from "vitest";

const schema = makeExecutableSchema({ typeDefs, resolvers });

describe("Schema execution", () => {
  it("resolves user query", async () => {
    const result = await graphql({
      schema,
      source: `query { user(id: "1") { id name email } }`,
      contextValue: createMockContext(),
    });
    expect(result.errors).toBeUndefined();
    expect(result.data.user.id).toBe("1");
  });

  it("returns error for missing field", async () => {
    const result = await graphql({
      schema,
      source: `query { nonexistentField }`,
      contextValue: createMockContext(),
    });
    expect(result.errors).toBeDefined();
    expect(result.errors[0].message).toContain("Cannot query field");
  });
});

Snapshot Testing

Snapshots record the shape of a response and fail on change. They’re excellent for one job — detecting unintentional schema drift — and terrible at everything else.

import { graphql } from "graphql";
import { describe, it, expect } from "vitest";

describe("Snapshot tests", () => {
  it("user query shape matches snapshot", async () => {
    const result = await graphql({
      schema,
      source: `query { user(id: "1") { id name email posts { id title } } }`,
      contextValue: createMockContext(),
    });
    expect(result.data).toMatchInlineSnapshot(`
      {
        "user": {
          "email": "alice@example.com",
          "id": "1",
          "name": "Alice",
          "posts": [
            {
              "id": "101",
              "title": "First Post"
            }
          ]
        }
      }
    `);
  });
});

Schema Snapshot

The highest-value snapshot is the introspection result — it catches every accidental schema change in CI:

import { introspectionFromSchema } from "graphql";

it("schema matches snapshot", () => {
  const introspection = introspectionFromSchema(schema);
  expect(introspection).toMatchSnapshot();
});

The rule of thumb: snapshot the schema, not the data. A snapshot of a big response is a diff nobody reviews, and rubber-stamped updates become the norm.

Contract Testing

A test suite can be fully green while you ship a breaking schema change — nothing in resolver tests knows that user.email just became nullable or disappeared. Contract tests close that gap.

  • Schema diff in CI: graphql-inspector diff compares the proposed schema against the last published one and fails the build on breaking changes. This is the contract check that buys you the most safety per line of config.
  • Introspection snapshot (above) is the lightweight version — coarser, but zero dependencies.
  • Persisted-operation validation: if clients use persisted queries, run every registered operation through graphql.validate() against the candidate schema. An operation that validates today must validate tomorrow, or the deploy is breaking by definition.
import { validate, parse } from "graphql";

it("all persisted operations still validate", () => {
  const operations = readPersistedManifest(); // your client's registered queries
  for (const op of operations) {
    const errors = validate(candidateSchema, parse(op.document));
    expect(errors).toEqual([]);
  }
});

Security Testing

GraphQL’s attack surface is unusual enough to deserve its own tests — generic API security suites don’t cover it.

  • Auth on nested fields: not just Query.user — check that users { posts { internalNotes } } can’t reach restricted fields through a permissive parent.
  • Depth and cost limits: assert that a nested bomb gets rejected (examples below under Performance Testing; same rules protect you here).
  • Introspection in production config: if introspection is disabled in prod, add a test that runs against the production-mode server and asserts the introspection query fails. It’s a one-line regression that leaks your entire schema.
  • Alias abuse: a query with fifty aliases multiplies cost without depth — worth one test if you use alias limits.

E2E Testing

E2E tests hit the real server with a real (test) database. Keep them few, keep them on the flows that can’t break.

import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { setupDatabase, teardownDatabase } from "./test-db";

const API_URL = "http://localhost:4000/graphql";

describe("GraphQL E2E", () => {
  beforeAll(async () => {
    await setupDatabase();
  });

  afterAll(async () => {
    await teardownDatabase();
  });

  it("full user lifecycle: create, read, update, delete", async () => {
    // Create
    const createRes = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: `mutation($input: CreateUserInput!) {
          createUser(input: $input) { user { id name email } errors }
        }`,
        variables: { input: { name: "Bob", email: "bob@example.com" } },
      }),
    });
    const created = await createRes.json();
    const userId = created.data.createUser.user.id;
    expect(created.data.createUser.errors).toEqual([]);

    // Read
    const readRes = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: `query($id: ID!) { user(id: $id) { id name email } }`,
        variables: { id: userId },
      }),
    });
    const read = await readRes.json();
    expect(read.data.user.name).toBe("Bob");

    // Update
    const updateRes = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: `mutation($input: UpdateUserInput!) {
          updateUser(input: $input) { user { id name } errors }
        }`,
        variables: { input: { id: userId, name: "Robert" } },
      }),
    });
    const updated = await updateRes.json();
    expect(updated.data.updateUser.user.name).toBe("Robert");

    // Delete
    const deleteRes = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: `mutation($input: DeleteUserInput!) {
          deleteUser(input: $input) { user { id } errors }
        }`,
        variables: { input: { id: userId } },
      }),
    });
    const deleted = await deleteRes.json();
    expect(deleted.data.deleteUser.errors).toEqual([]);
  });
});

Two constraints keep E2E honest: a dedicated test database (never a copy of production data), and lifecycle tests that clean up after themselves — E2E suites rot when tests leak state into each other.

Mocking Strategies

Mocking Data Sources

function createMockContext() {
  return {
    db: {
      users: {
        findById: vi.fn().mockResolvedValue({ id: "1", name: "Alice", email: "alice@example.com" }),
        findMany: vi.fn().mockResolvedValue([
          { id: "1", name: "Alice", email: "alice@example.com" },
          { id: "2", name: "Bob", email: "bob@example.com" },
        ]),
        create: vi.fn().mockResolvedValue({ id: "3", name: "Charlie", email: "charlie@example.com" }),
      },
      posts: {
        findMany: vi.fn().mockResolvedValue([
          { id: "101", title: "First Post", authorId: "1" },
        ]),
      },
    },
    user: { id: "1", role: "ADMIN" },
    loaders: {
      postsLoader: new DataLoader(async (userIds) => {
        return userIds.map(() => [{ id: "101", title: "First Post", authorId: "1" }]);
      }),
    },
  };
}

Mocking External APIs

import { vi } from "vitest";

function createContextWithMockedApi() {
  return {
    api: {
      getWeather: vi.fn().mockResolvedValue({ temp: 22, condition: "sunny" }),
      getStockPrice: vi.fn().mockResolvedValue({ symbol: "AAPL", price: 150.50 }),
    },
  };
}

describe("Weather resolver", () => {
  it("fetches weather from external API", async () => {
    const ctx = createContextWithMockedApi();
    const result = await resolvers.Query.weather(null, { city: "Madrid" }, ctx);
    expect(result.temp).toBe(22);
    expect(ctx.api.getWeather).toHaveBeenCalledWith("Madrid");
  });
});

The mock should match your context’s real shape — tests that pass against a context structure production doesn’t build are worse than no test. For heavier mocking needs (entire mocked servers for frontend development), see Mock GraphQL Resolvers for Frontend Development.

Performance Testing

Query Complexity Testing

Verify that expensive queries get rejected by cost analysis:

import costAnalysis from "graphql-cost-analysis";

describe("Cost analysis", () => {
  it("rejects expensive queries", async () => {
    const expensiveQuery = `
      query {
        users(first: 1000) {
          posts(first: 100) {
            comments(first: 100) {
              author { posts(first: 100) { title } }
            }
          }
        }
      }
    `;
    const result = await graphql({
      schema,
      source: expensiveQuery,
      contextValue: createMockContext(),
      validationRules: [costAnalysis({ maximumCost: 1000, variables: {} })],
    });
    expect(result.errors).toBeDefined();
    expect(result.errors[0].message).toContain("exceeds maximum");
  });

  it("allows reasonable queries", async () => {
    const reasonableQuery = `
      query {
        users(first: 10) { id name }
      }
    `;
    const result = await graphql({
      schema,
      source: reasonableQuery,
      contextValue: createMockContext(),
      validationRules: [costAnalysis({ maximumCost: 1000, variables: {} })],
    });
    expect(result.errors).toBeUndefined();
  });
});

Depth Limit Testing

import depthLimit from "graphql-depth-limit";

describe("Depth limiting", () => {
  it("rejects deeply nested queries", async () => {
    const deepQuery = `
      query {
        user(id: "1") {
          posts { author { posts { author { posts { author { name } } } } } }
        }
      }
    `;
    const result = await graphql({
      schema,
      source: deepQuery,
      contextValue: createMockContext(),
      validationRules: [depthLimit(5)],
    });
    expect(result.errors).toBeDefined();
    expect(result.errors[0].message).toContain("depth");
  });
});

Test Organization

File Structure

tests/
├── unit/
│   ├── resolvers/
│   │   ├── user.resolver.test.ts
│   │   ├── post.resolver.test.ts
│   │   └── mutation.resolver.test.ts
│   └── loaders/
│       └── posts.loader.test.ts
├── integration/
│   ├── schema.test.ts
│   └── queries.test.ts
├── e2e/
│   └── lifecycle.test.ts
└── helpers/
    ├── mock-context.ts
    └── test-db.ts

Running Tests in CI

Run fast layers on every commit, slow layers on merge:

{
  "scripts": {
    "test:unit": "vitest run tests/unit",
    "test:integration": "vitest run tests/integration",
    "test:e2e": "vitest run tests/e2e",
    "test": "vitest run",
    "test:watch": "vitest"
  }
}

The order that works: test:unit + schema diff on every PR, test:integration on the same PR, test:e2e on merge to main. Blocking every PR on the E2E suite is how teams learn to merge with failing tests.

Best Practices

The complete test suite layout ships in the companion repository: shared mock context, unit/integration/contract test files, and layered CI scripts.

  • Assert on payload error codes, not messages. errors[0].code === "CONFLICT" survives a copy edit; message === "Email already in use" doesn’t.
  • Keep one mock-context factory. Every test file building its own context is how mocks drift out of shape.
  • Test the unhappy path per layer. Unit tests for logic branches, integration for validation and error shape, E2E only for flows that justify the wait.
  • Gate the schema, not just the code. A breaking SDL change should fail CI before any test suite runs.
  • Track operation coverage, not line coverage. “Do our top-10 client queries still validate and resolve” is the metric that predicts incidents.

Common Mistakes

  • Snapshotting everything. Large response snapshots are diffs nobody reviews — the button that rubber-stamps regressions. Snapshot the schema, assert on data.
  • Mocking what you’re testing. A resolver test whose mock returns exactly what the resolver returns proves nothing; mock the boundary (db, API), not the unit.
  • E2E for every resolver. Full-stack tests are for flows, not coverage — 200 E2E tests means CI that takes an hour and teaches people to ignore red.
  • No test for partial failure. If a subgraph or data source can return null mid-response, someone should have tested what the client sees when it does.
  • Testing GraphQL itself. The library already validates types and parses documents; tests that assert “query returns data” without touching your resolvers are plumbing tests.

Production Checklist

  • Unit tests for all resolvers (queries, mutations, field resolvers)
  • Integration tests for schema execution
  • E2E tests for critical user flows
  • Mock data sources in unit and integration tests
  • Test database for E2E tests (not production database)
  • Schema snapshot or graphql-inspector diff in CI
  • Persisted operations validated against candidate schema
  • Cost analysis tests (expensive queries rejected)
  • Depth limit tests (deeply nested queries rejected)
  • Auth tests (unauthenticated users rejected, nested-field auth checked)
  • Introspection-off tested against production config
  • Error handling tests (expected errors in payload, unexpected in errors array)
  • CI pipeline runs fast layers on PR, E2E on merge
  • Top client operations tracked for coverage

See Also

Frequently Asked Questions

Should I test resolvers or test the full schema?

Both, but for different bugs. Unit tests catch logic errors cheap; integration tests catch wiring mistakes unit tests can't see; E2E catches the real stack failing. Skipping a layer just moves the bug report to production.

How do I test authentication in resolvers?

Inject it through context: { user: { id: "1", role: "ADMIN" } } for authenticated cases, { user: null } for the unauthorized path, and assert the resolver throws or returns the expected error.

Should I use a real database for integration tests?

A real test database — yes, separate from production. ORM quirks and query-plan issues are exactly the bugs mocks hide. Unit tests mock; integration tests use the real thing against test data.

How do I test DataLoader batching?

Call the resolver several times with the same key inside one tick and assert the batch function ran once. DataLoader batches within a single event-loop tick — batching is a correctness property, not an optimization.

What should I snapshot?

The introspection query result, to catch schema drift. Response snapshots only for small, stable payloads — anything large becomes a diff nobody reviews.

How do I test GraphQL subscriptions?

With graphql-ws's client: connect to the subscription endpoint, subscribe, fire the event (usually through a mutation), and assert the message arrives:

import { createClient } from "graphql-ws";
import { WebSocket } from "ws";

it("receives subscription updates", async () => {
  const client = createClient({ url: "ws://localhost:4000/graphql", webSocketImpl: WebSocket });
  const payload = await new Promise((resolve, reject) => {
    client.subscribe({ query: `subscription { onNewPost { id title } }` }, {
      next: resolve, error: reject, complete: () => {},
    });
    triggerNewPostMutation(); // fires the event the subscription listens to
  });
  expect(payload.data.onNewPost.title).toBeDefined();
  client.dispose();
});