or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdlist-mocking.mdmock-server.mdmock-store.mdpagination.mdschema-mocking.md
tile.json

mock-server.mddocs/

Mock Server

Quick mock server creation utilities for testing and development. Provides a simple interface for executing GraphQL queries against mocked schemas without complex server setup.

Capabilities

Mock Server Function

Creates a mock GraphQL server that can execute queries against mocked schemas.

/**
 * Create a mock GraphQL server for testing and development
 * @param schema - GraphQL schema or type definitions
 * @param mocks - Mock functions for types and fields
 * @param preserveResolvers - Whether to preserve existing resolvers
 * @returns Mock server instance with query method
 */
function mockServer<TResolvers>(
  schema: TypeSource,
  mocks: IMocks<TResolvers>,
  preserveResolvers?: boolean
): IMockServer;

Usage Examples:

import { mockServer } from "@graphql-tools/mock";

// Create mock server with type definitions
const server = mockServer(
  `
    type User {
      id: ID!
      name: String!
      email: String!
      posts: [Post!]!
    }

    type Post {
      id: ID!
      title: String!
      content: String!
      author: User!
    }

    type Query {
      user(id: ID!): User
      users: [User!]!
      post(id: ID!): Post
      posts: [Post!]!
    }
  `,
  {
    User: () => ({
      id: () => `user_${Math.random().toString(36).substr(2, 9)}`,
      name: () => ['Alice', 'Bob', 'Charlie', 'Diana'][Math.floor(Math.random() * 4)],
      email: (root) => `${root.name?.toLowerCase()}@example.com`,
      posts: () => new MockList([1, 5])
    }),
    Post: () => ({
      id: () => `post_${Math.random().toString(36).substr(2, 9)}`,
      title: () => [
        'Getting Started with GraphQL',
        'Advanced Query Techniques',
        'Schema Design Best Practices'
      ][Math.floor(Math.random() * 3)],
      content: () => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit...'
    })
  }
);

// Execute queries against the mock server
async function runQueries() {
  // Simple user query
  const userResult = await server.query(`
    query GetUser($id: ID!) {
      user(id: $id) {
        id
        name
        email
        posts {
          id
          title
        }
      }
    }
  `, { id: "1" });

  console.log('User result:', userResult.data);

  // List all users
  const usersResult = await server.query(`
    query GetAllUsers {
      users {
        id
        name
        email
      }
    }
  `);

  console.log('Users result:', usersResult.data);
}

runQueries();

Mock Server Interface

Interface defining the contract for mock server implementations.

/**
 * Interface for mock server instances
 */
interface IMockServer {
  /**
   * Execute a GraphQL query against the mocked schema
   * @param query - GraphQL query string
   * @param vars - Optional variables for the query
   * @returns Promise resolving to execution result
   */
  query: (query: string, vars?: Record<string, any>) => Promise<ExecutionResult>;
}

Type Source

Type definition for schema input accepted by mockServer.

/**
 * Input types accepted for schema definition
 */
type TypeSource = string | DocumentNode | GraphQLSchema;

Usage Patterns

Basic Testing Setup

import { mockServer, MockList } from "@graphql-tools/mock";

describe('GraphQL API Tests', () => {
  let server: IMockServer;

  beforeAll(() => {
    server = mockServer(
      typeDefs,
      {
        User: () => ({
          id: () => 'test-user-id',
          name: () => 'Test User',
          email: () => 'test@example.com'
        }),
        Post: () => ({
          id: () => 'test-post-id',
          title: () => 'Test Post'
        })
      }
    );
  });

  test('should return user data', async () => {
    const result = await server.query(`
      query {
        user(id: "1") {
          id
          name
          email
        }
      }
    `);

    expect(result.data?.user).toMatchObject({
      id: 'test-user-id',
      name: 'Test User',
      email: 'test@example.com'
    });
  });
});

Development Server

import { mockServer } from "@graphql-tools/mock";
import { createServer } from 'http';
import { execute, parse, validate } from 'graphql';

// Create mock server for development
const server = mockServer(schema, {
  User: () => ({
    name: () => 'Dev User',
    email: () => 'dev@example.com'
  })
});

// Simple HTTP server wrapper
const httpServer = createServer(async (req, res) => {
  if (req.method === 'POST' && req.url === '/graphql') {
    let body = '';
    req.on('data', chunk => { body += chunk; });
    req.on('end', async () => {
      try {
        const { query, variables } = JSON.parse(body);
        const result = await server.query(query, variables);
        
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(result));
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ errors: [{ message: error.message }] }));
      }
    });
  } else {
    res.writeHead(404);
    res.end('Not Found');
  }
});

httpServer.listen(4000, () => {
  console.log('Mock GraphQL server running on http://localhost:4000/graphql');
});

Integration with Existing Resolvers

import { buildSchema } from "graphql";
import { mockServer } from "@graphql-tools/mock";

const schema = buildSchema(`
  type User {
    id: ID!
    name: String!
    email: String!
    profile: UserProfile
  }

  type UserProfile {
    bio: String
    avatar: String
  }

  type Query {
    currentUser: User
    user(id: ID!): User
  }
`);

// Mock server with preserved resolvers
const server = mockServer(
  schema,
  {
    User: () => ({
      name: () => 'Mock User',
      email: () => 'mock@example.com'
    }),
    UserProfile: () => ({
      bio: () => 'This is a mock bio',
      avatar: () => 'https://example.com/avatar.jpg'
    })
  },
  true // Preserve existing resolvers
);

Error Handling

// Mock server with error scenarios
const server = mockServer(typeDefs, {
  User: () => ({
    name: () => {
      // Simulate occasional errors
      if (Math.random() < 0.1) {
        throw new Error('Mock user service temporarily unavailable');
      }
      return 'Mock User';
    }
  })
});

// Handle errors in queries
const result = await server.query(`
  query {
    users {
      id
      name
    }
  }
`);

if (result.errors) {
  console.error('Query errors:', result.errors);
} else {
  console.log('Query data:', result.data);
}

Variable Handling

// Test parameterized queries
const result = await server.query(`
  query GetUserPosts($userId: ID!, $limit: Int) {
    user(id: $userId) {
      id
      name
      posts(first: $limit) {
        id
        title
      }
    }
  }
`, {
  userId: "123",
  limit: 5
});