GraphQL Schema Testing and Mocking
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
-
TypeError: easygraphql_tester_1.EasyGraphQLTester is not a constructor
cause This typically occurs when using TypeScript or ESM imports with a package primarily designed for CommonJS default exports, or when the import statement is incorrect.fixFor CommonJS, use `const EasyGraphQLTester = require('easygraphql-tester');`. For TypeScript/ESM, ensure you're importing the default export: `import EasyGraphQLTester from 'easygraphql-tester';` or `import * as EasyGraphQLTester from 'easygraphql-tester';` (though the former is usually sufficient). -
Error: The query/mutation '...' is not defined on the schema.
cause The GraphQL query or mutation string passed to the tester refers to an operation (e.g., a field, query name, or mutation name) that does not exist in the provided schema.fixDouble-check the GraphQL schema definition for the existence and correct spelling of the queried operation. Verify the query string for typos. -
GraphQL schema validation error: Unknown type "..."
cause The GraphQL schema provided to `EasyGraphQLTester` contains references to types that are not defined within the schema itself or linked schemas.fixReview your `.gql` or `.graphql` files for type definitions. Ensure all custom types, inputs, enums, and scalars are defined. If using multiple schema files, confirm they are all passed to the `EasyGraphQLTester` constructor in an array and correctly extend types if necessary. -
Syntax Error: Unexpected Name "..."
cause There is a syntax error within the GraphQL query, mutation, or schema definition string.fixCarefully inspect the GraphQL string for syntax issues such as missing commas, incorrect field names, invalid directives, or malformed arguments. A GraphQL linter can help identify these issues.
Warnings
- breaking Version 6.x introduced changes for better compatibility with `graphql@15` and standardized error handling. Ensure your `graphql` peer dependency aligns with `easygraphql-tester`'s requirements.
- breaking Version 4.x dropped support for Node.js versions older than 8 and introduced `async/await` support for resolvers. If you are on an older Node.js runtime or using synchronous resolvers, this could be a breaking change.
- gotcha When testing resolvers, you must explicitly pass the `resolvers` object as the second argument to the `EasyGraphQLTester` constructor. Forgetting this will result in the tester being unable to execute resolver logic.
- gotcha The `.tester` and `.mock` methods require specific boolean arguments (for assertion) or objects (for mocking/fixtures). Incorrect usage can lead to unexpected test failures or incorrect mock data.
- gotcha Testing GraphQL unions with `easygraphql-tester` can sometimes lead to `TypeError: Cannot read property 'type' of undefined` if the schema or mock data for the union is not correctly structured.
Install
-
npm install easygraphql-tester -
yarn add easygraphql-tester -
pnpm add easygraphql-tester
Imports
- EasyGraphQLTester
import { EasyGraphQLTester } from 'easygraphql-tester';const EasyGraphQLTester = require('easygraphql-tester'); - EasyGraphQLTester (instance)
const tester = new EasyGraphQLTester(schema);
- tester.graphql
tester.graphql(query); // Forgetting await for resolvers, or required arguments.
await tester.graphql(query, rootValue, contextValue, variableValues);
Quickstart
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();