GraphQL Schema Testing and Mocking

6.0.1 · active · verified Tue Apr 21

easygraphql-tester is a Node.js library designed to facilitate testing of GraphQL schemas, queries, and mutations. Currently at stable version 6.0.1, its release cadence is active but irregular, typically aligning with updates to the GraphQL specification or bug fixes. It distinguishes itself by offering both assertion-based testing (validating schema adherence, field existence, argument types, and input validity) and mocking capabilities, allowing developers to generate fake data for operations without a live GraphQL server. This enables comprehensive unit testing of GraphQL logic and schema definitions. It supports single or multiple schema files, direct `graphql-js` schema objects, and integrates resolvers for more complete backend testing. The library is part of the broader EasyGraphQL suite, which includes tools for load testing, schema mocking, and server creation.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates initializing `easygraphql-tester` with a GraphQL schema and resolvers, then executing a valid query and a mutation using the `graphql` method to test resolver logic and schema adherence.

const EasyGraphQLTester = require('easygraphql-tester');
const fs = require('fs');
const path = require('path');

// Create a dummy schema file for demonstration
const schemaPath = path.join(__dirname, 'schema.gql');
if (!fs.existsSync(path.dirname(schemaPath))) {
  fs.mkdirSync(path.dirname(schemaPath));
}
fs.writeFileSync(schemaPath, `
  type User {
    id: ID!
    name: String!
    email: String
  }

  type Query {
    getUser(id: ID!): User
    listUsers: [User]
  }

  type Mutation {
    createUser(name: String!, email: String): User
  }
`);

const userSchema = fs.readFileSync(schemaPath, 'utf8');

const resolvers = {
  Query: {
    getUser: (_, { id }) => ({
      id,
      name: `User ${id}`,
      email: `user${id}@example.com`,
    }),
    listUsers: () => [
      { id: '1', name: 'Alice', email: 'alice@example.com' },
      { id: '2', name: 'Bob', email: 'bob@example.com' },
    ],
  },
  Mutation: {
    createUser: (_, { name, email }) => ({
      id: Math.random().toString(36).substring(7),
      name,
      email,
    }),
  },
};

const tester = new EasyGraphQLTester(userSchema, resolvers);

async function runTests() {
  try {
    // Test a valid query
    const query = `
      query GetUser($id: ID!) {
        getUser(id: $id) {
          id
          name
        }
      }
    `;
    const variables = { id: '1' };
    const result = await tester.graphql(query, undefined, undefined, variables);
    console.log('Valid Query Result:', JSON.stringify(result, null, 2));
    // Expected: { "data": { "getUser": { "id": "1", "name": "User 1" } } }

    // Test a valid mutation
    const mutation = `
      mutation CreateNewUser($name: String!, $email: String) {
        createUser(name: $name, email: $email) {
          id
          name
          email
        }
      }
    `;
    const mutationVariables = { name: 'Charlie', email: 'charlie@example.com' };
    const mutationResult = await tester.graphql(mutation, undefined, undefined, mutationVariables);
    console.log('Valid Mutation Result:', JSON.stringify(mutationResult, null, 2));
    // Expected: { "data": { "createUser": { "id": "...", "name": "Charlie", "email": "charlie@example.com" } } }

  } catch (error) {
    console.error('Test Failed:', error.message);
  }
}

runTests();

view raw JSON →