Mock GraphQL server creation for integration testing, built on nock and graphql-helix for realistic GraphQL request/response handling.
Creates a mock GraphQL server for testing using nock HTTP mocking and graphql-helix execution engine. Enables realistic GraphQL integration testing without requiring actual servers.
/**
* Creates a mock GraphQL server for testing using nock and graphql-helix
* @param config - Configuration object for the mock server
* @returns nock.Scope interceptor or null
*/
function mockGraphQLServer(config: {
schema: GraphQLSchema;
host: string;
path: string | RegExp | ((path: string) => boolean);
intercept?: (obj: nock.ReplyFnContext) => void;
method?: string;
}): nock.Scope | null;Configuration Parameters:
interface MockGraphQLServerConfig {
/** The GraphQL schema to use for query execution */
schema: GraphQLSchema;
/** The host to mock (e.g., 'https://api.example.com') */
host: string;
/** The path pattern to intercept - can be string, RegExp, or function */
path: string | RegExp | ((path: string) => boolean);
/** Optional interceptor function for custom request handling */
intercept?: (obj: nock.ReplyFnContext) => void;
/** HTTP method to intercept (default: 'POST') */
method?: string;
}Usage Examples:
import { mockGraphQLServer } from "@graphql-codegen/testing";
import { buildSchema } from "graphql";
import fetch from "node-fetch";
// Create a test schema
const testSchema = buildSchema(`
type Query {
user(id: ID!): User
users: [User!]!
}
type User {
id: ID!
name: String!
email: String!
}
`);
// Basic mock server setup
const mockServer = mockGraphQLServer({
schema: testSchema,
host: "https://api.example.com",
path: "/graphql"
});
// Test GraphQL queries
const response = await fetch("https://api.example.com/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `
query GetUsers {
users {
id
name
email
}
}
`
})
});
const result = await response.json();
// Mock server executes query against schema and returns results
// Mock server with custom interceptor
const interceptingMock = mockGraphQLServer({
schema: testSchema,
host: "https://api.example.com",
path: "/graphql",
intercept: (context) => {
// Access request headers, modify context, etc.
console.log("Intercepted request:", context.req.headers);
// Add custom headers to response
context.req.headers["x-custom-header"] = "test-value";
}
});
// Mock server with RegExp path matching
const regexMock = mockGraphQLServer({
schema: testSchema,
host: "https://api.example.com",
path: /^\/graphql/,
method: "POST"
});
// Mock server with function-based path matching
const functionMock = mockGraphQLServer({
schema: testSchema,
host: "https://api.example.com",
path: (path) => path.startsWith("/api/") && path.includes("graphql"),
method: "POST"
});
// GET request mocking (for GraphQL over GET)
const getMock = mockGraphQLServer({
schema: testSchema,
host: "https://api.example.com",
path: "/graphql",
method: "GET"
});Request Processing: The mock server handles GraphQL requests through the following pipeline:
getGraphQLParameters from graphql-helix to parse GraphQL query, variables, and operation nameprocessGraphQLHelixRequest with the provided schemaResponse Types: The mock server handles three types of GraphQL responses:
@stream and @defer directives (returns "Not implemented")Query Parameter Support: Supports GraphQL queries sent via URL query parameters (common with GET requests):
// Example GET request with query parameters
const getResponse = await fetch(
"https://api.example.com/graphql?query=query{users{id,name}}&variables={}"
);Error Handling:
Integration with Testing Frameworks:
import { mockGraphQLServer } from "@graphql-codegen/testing";
describe("GraphQL Integration Tests", () => {
let mockServer: nock.Scope;
beforeEach(() => {
mockServer = mockGraphQLServer({
schema: testSchema,
host: "https://api.example.com",
path: "/graphql"
});
});
afterEach(() => {
nock.cleanAll(); // Clean up nock interceptors
});
it("should handle user queries", async () => {
const response = await client.query({
query: gql\`
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
\`,
variables: { id: "1" }
});
expect(response.data.user).toBeDefined();
});
});