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

schema-mocking.mddocs/

Schema Mocking

Core schema mocking functionality that transforms existing GraphQL schemas by adding mock resolvers. This is the primary entry point for adding mock behavior to schemas for development and testing.

Capabilities

Add Mocks to Schema

Transforms a GraphQL schema by adding mock resolvers while optionally preserving existing resolvers.

/**
 * Add mock resolvers to a GraphQL schema
 * @param options - Configuration object for mock behavior
 * @returns New schema with mock resolvers attached
 */
function addMocksToSchema<TResolvers = IResolvers>({
  schema,
  store,
  mocks,
  typePolicies,
  resolvers,
  preserveResolvers
}: IMockOptions<TResolvers>): GraphQLSchema;

interface IMockOptions<TResolvers> {
  /** The GraphQL schema to add mocks to */
  schema: GraphQLSchema;
  /** Optional mock store for stateful data */
  store?: IMockStore;
  /** Mock functions for types and fields */
  mocks?: IMocks<TResolvers>;
  /** Configuration for type behavior */
  typePolicies?: { [typeName: string]: TypePolicy };
  /** Additional resolvers to merge */
  resolvers?: Partial<TResolvers> | ((store: IMockStore) => Partial<TResolvers>);
  /** Whether to preserve existing resolvers */
  preserveResolvers?: boolean;
}

Usage Examples:

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

const schema = buildSchema(`
  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
  }
`);

// Basic mocking with default values
const basicMockedSchema = addMocksToSchema({ schema });

// Custom mock functions
const customMockedSchema = addMocksToSchema({
  schema,
  mocks: {
    User: () => ({
      id: () => `user_${Math.random().toString(36).substr(2, 9)}`,
      name: () => ['Alice', 'Bob', 'Charlie', 'Diana'][Math.floor(Math.random() * 4)],
      email: (root, args, context, info) => `${root.name?.toLowerCase()}@example.com`,
      posts: () => new MockList([2, 6])
    }),
    Post: () => ({
      id: () => `post_${Math.random().toString(36).substr(2, 9)}`,
      title: () => ['GraphQL Basics', 'Advanced Queries', 'Schema Design'][Math.floor(Math.random() * 3)],
      content: () => 'Lorem ipsum dolor sit amet...'
    }),
    String: () => 'Default String',
    Int: () => Math.floor(Math.random() * 100),
    ID: () => Math.random().toString(36).substr(2, 9)
  }
});

// With existing resolvers preserved
const preservedResolverSchema = addMocksToSchema({
  schema,
  mocks: {
    User: () => ({
      name: () => 'Mock Name'
    })
  },
  resolvers: {
    Query: {
      user: () => ({ id: '1', name: 'Real User', email: 'real@example.com' })
    }
  },
  preserveResolvers: true
});

Mock Configuration Types

Type definitions for configuring mock behavior across different GraphQL types.

/**
 * Mock configuration for GraphQL types and scalars
 */
type IMocks<TResolvers = IResolvers> = {
  [TTypeName in keyof TResolvers]?: {
    [TFieldName in keyof TResolvers[TTypeName]]: 
      TResolvers[TTypeName][TFieldName] extends (args: any) => any
        ? () => ReturnType<TResolvers[TTypeName][TFieldName]> | ReturnType<TResolvers[TTypeName][TFieldName]>
        : TResolvers[TTypeName][TFieldName];
  };
} & {
  [typeOrScalarName: string]: IScalarMock | ITypeMock;
};

/**
 * Mock function that returns a value
 */
type IMockFn = () => unknown;

/**
 * Mock for scalar fields - can be a static value or function
 */
type IScalarMock = unknown | IMockFn;

/**
 * Mock for object types - function returning field mocks
 */
type ITypeMock = () => { [fieldName: string]: unknown | IMockFn };

Type Policies

Configuration for controlling how types behave in the mock system.

/**
 * Configuration for type-specific mock behavior
 */
type TypePolicy = {
  /** Field name to use as unique key, or false to disable keying */
  keyFieldName?: string | false;
};

Usage Examples:

// Configure type policies for better data consistency
const schemaWithPolicies = addMocksToSchema({
  schema,
  typePolicies: {
    User: { keyFieldName: 'id' },
    Post: { keyFieldName: 'id' },
    Tag: { keyFieldName: false } // No unique key for tags
  },
  mocks: {
    User: () => ({
      id: () => `user_${Math.random().toString(36).substr(2, 9)}`
    })
  }
});

Default Mock Values

Built-in default mock functions for common GraphQL scalar types.

/**
 * Default mock implementations for scalar types
 */
const defaultMocks = {
  Int: () => Math.round(Math.random() * 200) - 100,
  Float: () => Math.random() * 200 - 100,
  String: () => 'Hello World',
  Boolean: () => Math.random() > 0.5,
  ID: () => uuidv4(),
};

These defaults are automatically applied when no custom mocks are provided for scalar types.

Usage Examples:

import { addMocksToSchema, defaultMocks } from "@graphql-tools/mock";

// Use default mocks directly
const customMocks = {
  ...defaultMocks,
  String: () => 'Custom String Value',
  User: () => ({
    name: defaultMocks.String,
    id: defaultMocks.ID
  })
};

// Default mocks are applied automatically when using addMocksToSchema
const mockedSchema = addMocksToSchema({
  schema,
  mocks: {
    // Only need to override specific types
    User: () => ({
      name: () => 'Custom User Name'
      // id, email etc. will use defaultMocks
    })
  }
});

Integration Patterns

With Existing Resolvers

// Merge mocks with existing resolvers
const schemaWithMixedResolvers = addMocksToSchema({
  schema,
  mocks: {
    User: () => ({
      name: () => 'Mock User',
      email: () => 'mock@example.com'
    })
  },
  resolvers: {
    Query: {
      // Real resolver for specific query
      currentUser: (parent, args, context) => {
        return context.user || null;
      }
    },
    User: {
      // Real resolver for computed field
      fullName: (user) => `${user.firstName} ${user.lastName}`
    }
  },
  preserveResolvers: true
});

With Custom Context

// Mock functions can access GraphQL context
const contextAwareMocks = addMocksToSchema({
  schema,
  mocks: {
    User: (root, args, context, info) => ({
      id: () => context.userId || 'anonymous',
      name: () => context.user?.name || 'Guest User',
      permissions: () => context.user?.permissions || []
    })
  }
});