CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-graphql-codegen--testing

Jest testing utilities for GraphQL Code Generator with custom matchers, TypeScript validation, and GraphQL server mocking

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

server-mocking.mddocs/

GraphQL Server Mocking

Mock GraphQL server creation for integration testing, built on nock and graphql-helix for realistic GraphQL request/response handling.

Capabilities

mockGraphQLServer Function

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"
});

Implementation Details

Request Processing: The mock server handles GraphQL requests through the following pipeline:

  1. Request Interception: Nock intercepts HTTP requests matching the configured host and path
  2. Parameter Extraction: Uses getGraphQLParameters from graphql-helix to parse GraphQL query, variables, and operation name
  3. Request Object Creation: Constructs a generic request object compatible with graphql-helix API
  4. Query Execution: Processes the GraphQL request using processGraphQLHelixRequest with the provided schema
  5. Response Handling: Returns appropriate HTTP status codes and response bodies based on execution results

Response Types: The mock server handles three types of GraphQL responses:

  • RESPONSE: Standard JSON payload for regular queries and mutations
  • MULTIPART RESPONSE: Multipart responses for @stream and @defer directives (returns "Not implemented")
  • PUSH: Server-sent events for subscriptions (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:

  • Returns 500 status for unsupported response types (multipart, push)
  • Propagates GraphQL execution errors through standard GraphQL error response format
  • Maintains compatibility with graphql-helix error handling patterns

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();
  });
});

docs

index.md

jest-extensions.md

monorepo-utilities.md

resolver-testing.md

server-mocking.md

typescript-validation.md

tile.json