Apollo Server Testing Utilities (Legacy)

raw JSON →
2.25.3 verified Sun Apr 19 auth: no javascript abandoned

This `apollo-server-testing` package provides utilities specifically designed for testing applications built with older versions of Apollo Server (v2 and v3). Its primary export, `createTestClient`, wraps the `ApolloServer.executeOperation` method to allow direct GraphQL operation execution against an `ApolloServer` instance without spinning up a full HTTP server. The package `apollo-server-testing` is currently at version `2.25.3` and was last published over four years ago. It is considered abandoned for new development, as the current major versions of Apollo Server (v4 and v5, under the `@apollo/server` package) integrate testing utilities directly via `server.executeOperation` or provide `@apollo/server/testing` where applicable. This package is solely relevant for maintaining legacy projects still on `apollo-server` v2 or v3, which are both officially end-of-life.

error TypeError: Cannot destructure property 'query' of 'undefined' as it is undefined.
cause This typically occurs if `createTestClient` is called with an `ApolloServer` instance that hasn't been properly initialized or started, or if `apollo-server-testing` is being used with `@apollo/server` (v4+), which doesn't directly expose `createTestClient`.
fix
Ensure your ApolloServer instance (from apollo-server v2/v3) is correctly constructed before passing it to createTestClient. If using @apollo/server v4+, you should directly use server.executeOperation() instead of createTestClient().
error Error: Apollo Server requires 'graphql' to be installed. Please install 'graphql@^14.0.0 || ^15.0.0' or newer.
cause Missing `graphql` peer dependency or an incompatible version is installed. `apollo-server-testing` depends on `apollo-server` which has `graphql` as a peer dependency.
fix
Install the required graphql version: npm install graphql@^14.0.0 || ^15.0.0 or yarn add graphql@^14.0.0 || ^15.0.0. Refer to your apollo-server version's documentation for exact compatible graphql versions.
breaking The `apollo-server-testing` package is designed for Apollo Server v2 and v3. Both v2 (end-of-life Oct 2023) and v3 (end-of-life Oct 2024) are no longer officially supported by Apollo. New projects should use `@apollo/server` (v4+) and its integrated testing approaches.
fix For new projects or migrations, switch to `@apollo/server` (v4+) and utilize `server.executeOperation` directly for testing, or use specific integration testing packages like `apollo-server-integration-testing` if full HTTP layer simulation is needed.
gotcha The `createTestClient` function from `apollo-server-testing` does not fully support the `context` function argument that Apollo Server's `executeOperation` method (and the server itself) provides. Specifically, it might not pass `req` or `res` objects to your context function as expected, leading to `undefined` values if your context relies on them.
fix If your context function depends on `req` or `res`, you'll need to mock these objects within your test context or adjust your context logic for testing. Alternatively, consider using `server.executeOperation` directly and explicitly passing a test-specific context object, or using an integration testing package that properly mocks HTTP requests and responses.
deprecated The `apollo-server-testing` package is explicitly deprecated and will not be published with Apollo Server 3 or later. Its functionality is a thin wrapper around `ApolloServer.executeOperation`, which is the recommended direct approach for testing Apollo Server logic without the HTTP layer.
fix Migrate your tests to directly use the `ApolloServer` instance's `executeOperation` method. This method provides the same core functionality and is the officially supported way to test GraphQL operations in isolation for Apollo Server v2+. For Apollo Server v4+, the new core `@apollo/server` package has `executeOperation` built-in.
npm install apollo-server-testing
yarn add apollo-server-testing
pnpm add apollo-server-testing

This quickstart demonstrates how to use `apollo-server-testing` with `apollo-server` (v2/v3) to create an in-memory test client and execute GraphQL queries and mutations against a defined schema and resolvers, simulating requests without a live HTTP server. This is suitable for integration tests of the GraphQL layer.

import { ApolloServer, gql } from 'apollo-server';
import { createTestClient } from 'apollo-server-testing';

// 1. Define your GraphQL schema
const typeDefs = gql`
  type Query {
    hello(name: String): String!
    getUser(id: ID!): User
  }

  type User {
    id: ID!
    name: String!
    email: String!
  }

  type Mutation {
    addUser(name: String!, email: String!): User!
  }
`;

// 2. Define your resolvers
const users = [
  { id: '1', name: 'Alice', email: 'alice@example.com' },
  { id: '2', name: 'Bob', email: 'bob@example.com' }
];

const resolvers = {
  Query: {
    hello: (_, { name }) => `Hello ${name || 'World'}!`,
    getUser: (_, { id }) => users.find(user => user.id === id)
  },
  Mutation: {
    addUser: (_, { name, email }) => {
      const newUser = { id: String(users.length + 1), name, email };
      users.push(newUser);
      return newUser;
    }
  }
};

// 3. Create an Apollo Server instance
const server = new ApolloServer({
  typeDefs,
  resolvers,
  // Optional: context function
  context: () => ({ /* Add any context relevant for your resolvers */ })
});

// 4. Create a test client
const { query, mutate } = createTestClient(server);

// Example Test (using Jest syntax for illustration)
describe('Apollo Server Integration Tests', () => {
  it('should fetch a greeting', async () => {
    const GET_HELLO = gql`
      query GetHello($name: String) {
        hello(name: $name)
      }
    `;
    const response = await query({ query: GET_HELLO, variables: { name: 'Test' } });
    expect(response.data.hello).toBe('Hello Test!');
  });

  it('should add a new user', async () => {
    const ADD_USER = gql`
      mutation AddUser($name: String!, $email: String!) {
        addUser(name: $name, email: $email) {
          id
          name
          email
        }
      }
    `;
    const response = await mutate({ query: ADD_USER, variables: { name: 'Charlie', email: 'charlie@example.com' } });
    expect(response.data.addUser).toEqual({
      id: expect.any(String),
      name: 'Charlie',
      email: 'charlie@example.com'
    });
    expect(users).toHaveLength(3);
  });

  it('should fetch an existing user', async () => {
    const GET_USER = gql`
      query GetUser($id: ID!) {
        getUser(id: $id) {
          id
          name
          email
        }
      }
    `;
    const response = await query({ query: GET_USER, variables: { id: '1' } });
    expect(response.data.getUser).toEqual(users[0]);
  });
});