{"id":12814,"library":"apollo-server-integration-testing","title":"Apollo Server Integration Testing Utilities","description":"This package provides essential utilities for conducting true integration tests on Apollo Server instances, especially when the server's `context` option depends on mocked HTTP `Request` or `Response` objects. Unlike the now-deprecated `apollo-server-testing` package, which often resulted in `req` being undefined in the context function, `apollo-server-integration-testing` automatically provides robust mock objects, enabling comprehensive testing of server logic, including middleware and resolvers that access `req` or `res`. The package's current stable version is 3.0.0, and while it doesn't have a fixed release cadence, it generally aims to support relevant versions of `graphql` (from 0.12.0 up to 15.0.0 as per its peer dependencies) to remain compatible with various Apollo Server setups. Its key differentiator is its ability to simulate a full HTTP request/response cycle, making it suitable for integration and end-to-end testing where `ApolloServer.executeOperation` (recommended for simpler unit tests) is insufficient.","status":"active","version":"3.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/zapier/apollo-server-integration-testing","tags":["javascript","GraphQL","Apollo","Server","Javascript","Testing","Integration Testing","typescript"],"install":[{"cmd":"npm install apollo-server-integration-testing","lang":"bash","label":"npm"},{"cmd":"yarn add apollo-server-integration-testing","lang":"bash","label":"yarn"},{"cmd":"pnpm add apollo-server-integration-testing","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for GraphQL schema validation and execution. Note that the supported range (`^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0`) is broad and should be compatible with the specific Apollo Server version being tested.","package":"graphql","optional":false}],"imports":[{"note":"The library primarily exports `createTestClient` as a named export. While CommonJS `require` syntax might technically work in some environments, modern TypeScript/JavaScript projects should use ESM `import`.","wrong":"const { createTestClient } = require('apollo-server-integration-testing');","symbol":"createTestClient","correct":"import { createTestClient } from 'apollo-server-integration-testing';"},{"note":"When using TypeScript, import the `TestClient` type for type-safety when destructuring `query` and `mutate`.","symbol":"TestClient","correct":"import type { TestClient } from 'apollo-server-integration-testing';"},{"note":"The `setOptions` function is returned alongside `query` and `mutate` and allows modifying mock request/response options dynamically after client creation, which can be more efficient than re-creating the client for each change.","symbol":"setOptions","correct":"const { query, setOptions } = createTestClient({ apolloServer });"}],"quickstart":{"code":"import { createTestClient } from 'apollo-server-integration-testing';\nimport { ApolloServer } from '@apollo/server';\nimport { buildSubgraphSchema } from '@apollo/subgraph';\nimport gql from 'graphql-tag';\n\nconst typeDefs = gql`\n  type User {\n    id: ID!\n    email: String\n  }\n\n  type Query {\n    currentUser: User\n  }\n\n  type Mutation {\n    updateUser(id: ID!, email: String!): User\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    currentUser: (_, __, { req }) => {\n      // Simulate context logic that depends on req\n      if (req?.headers?.authorization) {\n        return { id: '1', email: 'test@example.com' };\n      }\n      return null;\n    },\n  },\n  Mutation: {\n    updateUser: (_, { id, email }) => ({ id, email }),\n  },\n};\n\nasync function createApolloServer() {\n  const server = new ApolloServer({\n    schema: buildSubgraphSchema({ typeDefs, resolvers }),\n  });\n  await server.start(); // Mandatory for Apollo Server v3+\n  return server;\n}\n\ndescribe('Apollo Server Integration Tests', () => {\n  let apolloServer;\n  let query;\n  let mutate;\n  let setOptions;\n\n  beforeAll(async () => {\n    apolloServer = await createApolloServer();\n    ({ query, mutate, setOptions } = createTestClient({\n      apolloServer,\n      extendMockRequest: {\n        headers: { authorization: 'Bearer token' }\n      }\n    }));\n  });\n\n  afterAll(async () => {\n    await apolloServer.stop();\n  });\n\n  test('should fetch current user with mocked request headers', async () => {\n    const result = await query(`{ currentUser { id email } }`);\n    expect(result).toEqual({\n      data: {\n        currentUser: {\n          id: '1',\n          email: 'test@example.com'\n        }\n      }\n    });\n  });\n\n  test('should update user and allow subsequent request modification', async () => {\n    setOptions({\n      request: { headers: { authorization: 'Bearer another-token' } }\n    });\n\n    const UPDATE_USER_MUTATION = `\n      mutation UpdateUser($id: ID!, $email: String!) {\n        updateUser(id: $id, email: $email) {\n          id\n          email\n        }\n      }\n    `;\n    const mutationResult = await mutate(UPDATE_USER_MUTATION, {\n      variables: { id: '1', email: 'jane.doe@example.com' }\n    });\n\n    expect(mutationResult).toEqual({\n      data: {\n        updateUser: {\n          id: '1',\n          email: 'jane.doe@example.com'\n        }\n      }\n    });\n  });\n});","lang":"typescript","description":"This quickstart demonstrates how to create an Apollo Server, use `createTestClient` to run queries and mutations against it, mock and extend the `Request` object for context testing, and dynamically update mock options using `setOptions`. It includes mandatory `server.start()` and `server.stop()` calls for Apollo Server v3+."},"warnings":[{"fix":"Use `apollo-server-integration-testing` for integration tests where your `ApolloServer` instance's `context` option is a function that processes the incoming `req` or `res` objects. For simpler, isolated GraphQL operation tests, consider `ApolloServer.executeOperation` directly.","message":"When testing Apollo Server `context` functions that rely on `req` or `res` objects, using the official `apollo-server-testing` package (now deprecated in favor of `server.executeOperation`) will result in `req` being `undefined`. This package (`apollo-server-integration-testing`) is specifically designed to address this limitation by providing robust mock HTTP request/response objects.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure you call `await apolloServer.start()` after creating your `ApolloServer` instance and before passing it to `createTestClient`.","message":"Apollo Server v3 and later versions require calling `await server.start()` before the server can be used. Failing to do so will result in runtime errors. This applies when you are passing an `ApolloServer` instance to `createTestClient`.","severity":"breaking","affected_versions":">=3.0.0 of Apollo Server"},{"fix":"Always install a `graphql` version that satisfies both `apollo-server-integration-testing`'s peer dependency and, more importantly, the explicit requirements of your specific `Apollo Server` package.","message":"The `graphql` peer dependency for `apollo-server-integration-testing` has a wide range (`^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0`). However, the specific version of `graphql` required by your `Apollo Server` package (e.g., Apollo Server 3 requires `graphql` v15.3.0+, Apollo Server 4 requires `graphql` v16+) might be more restrictive. A mismatch can lead to unexpected behavior or conflicts.","severity":"gotcha","affected_versions":"All versions, depending on `Apollo Server` version"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Switch to `apollo-server-integration-testing` for tests that require `req` or `res` objects in the `context`, or manually mock the `context` argument when using `ApolloServer.executeOperation` if a full HTTP mock isn't needed. Alternatively, if using `apollo-server-integration-testing`, ensure `extendMockRequest` or `setOptions` provide the necessary `req` properties.","cause":"Attempting to access `req` (or `res`) within the `ApolloServer`'s `context` function when using `apollo-server-testing` or `ApolloServer.executeOperation` for a test where `req` is not explicitly mocked.","error":"Cannot read properties of undefined (reading 'req') / TypeError: Cannot read property 'req' of undefined"},{"fix":"Add `await apolloServer.start();` after creating your `new ApolloServer(...)` instance and before passing `apolloServer` to `createTestClient`.","cause":"When using Apollo Server v3 or later, the `server.start()` method must be called to initialize the server before any operations or integrations can use it. This error indicates it was omitted before `createTestClient` was invoked.","error":"ApolloServer must be started before it can be used. Call `await server.start()` before `applyMiddleware()` or `listen()`."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null}