Registry / testing / easygraphql-tester

easygraphql-tester

JSON →
library6.0.1jsnpmunverified

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.

npm install easygraphql-tester
INSTALL
IMPORT
SIG · EASYGRAPHQL-TESTER
E
easygraphql-tester
testingjavascriptv6.0.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

EasyGraphQLTester
✓ const EasyGraphQLTester = require('easygraphql-tester');
✗ import { EasyGraphQLTester } from 'easygraphql-tester';
The library primarily uses CommonJS `require` syntax. While Node.js may allow `import EasyGraphQLTester from 'easygraphql-tester';` due to interoperability, it is not explicitly designed for named ESM imports.
EasyGraphQLTester (instance)
✓ const tester = new EasyGraphQLTester(schema);
The `EasyGraphQLTester` class is instantiated with the GraphQL schema string(s) or a GraphQL.js `GraphQLSchema` object. Resolvers can be passed as a second argument for testing resolver logic.
tester.graphql
✓ await tester.graphql(query, rootValue, contextValue, variableValues);
✗ tester.graphql(query); // Forgetting await for resolvers, or required arguments.
Used for executing a query or mutation against the schema, especially when testing resolvers. It returns a Promise and the `query` argument is mandatory; the others are optional depending on the resolver's needs.

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();
Debug
Known issues
breakingVersion 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.
fix
Review the `graphql` peer dependency specified in `package.json` for `easygraphql-tester` and update your `graphql` package accordingly. You may also need to adjust error handling logic.
affects: >=6.0.0
breakingVersion 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.
fix
Upgrade your Node.js environment to version 8 or higher. Ensure all resolver functions are either `async` or return Promises if they perform asynchronous operations.
affects: >=4.0.0
gotchaWhen 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.
fix
Initialize the tester with your schema and resolvers: `new EasyGraphQLTester(schema, resolvers);`.
affects: >=1.0.0
gotchaThe `.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.
fix
Consult the official documentation for the precise usage of `.tester(isValid: boolean, query: string, variables?: object)` for assertions and `.mock({ query: string, variables?: object, fixture?: object, saveFixture?: boolean })` for mocking.
affects: >=1.0.0
gotchaTesting 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.
fix
Ensure that your union types are correctly defined in the schema and that any mock data or fixtures provided for union fields specify the `__typename` and conform to one of the union's member types.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: easygraphql_tester_1.EasyGraphQLTester is not a constructor
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.
fix
For 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.
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.
fix
Double-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 "..."
The GraphQL schema provided to `EasyGraphQLTester` contains references to types that are not defined within the schema itself or linked schemas.
fix
Review 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 "..."
There is a syntax error within the GraphQL query, mutation, or schema definition string.
fix
Carefully 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.
Upgrade
Version history
6.0.1latest on npm
Audit
Dependencies
graphqlrequiredPeer dependency required for GraphQL schema parsing and validation. Supports multiple major versions of GraphQL.js.
Agent activity
4 hits · last 30 days
node
4
Resources