{"id":15314,"library":"easygraphql-tester","title":"GraphQL Schema Testing and Mocking","description":"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.","status":"active","version":"6.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/EasyGraphQL/easygraphql-tester","tags":["javascript"],"install":[{"cmd":"npm install easygraphql-tester","lang":"bash","label":"npm"},{"cmd":"yarn add easygraphql-tester","lang":"bash","label":"yarn"},{"cmd":"pnpm add easygraphql-tester","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency required for GraphQL schema parsing and validation. Supports multiple major versions of GraphQL.js.","package":"graphql","optional":false}],"imports":[{"note":"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.","wrong":"import { EasyGraphQLTester } from 'easygraphql-tester';","symbol":"EasyGraphQLTester","correct":"const EasyGraphQLTester = require('easygraphql-tester');"},{"note":"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.","symbol":"EasyGraphQLTester (instance)","correct":"const tester = new EasyGraphQLTester(schema);"},{"note":"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.","wrong":"tester.graphql(query); // Forgetting await for resolvers, or required arguments.","symbol":"tester.graphql","correct":"await tester.graphql(query, rootValue, contextValue, variableValues);"}],"quickstart":{"code":"const EasyGraphQLTester = require('easygraphql-tester');\nconst fs = require('fs');\nconst path = require('path');\n\n// Create a dummy schema file for demonstration\nconst schemaPath = path.join(__dirname, 'schema.gql');\nif (!fs.existsSync(path.dirname(schemaPath))) {\n  fs.mkdirSync(path.dirname(schemaPath));\n}\nfs.writeFileSync(schemaPath, `\n  type User {\n    id: ID!\n    name: String!\n    email: String\n  }\n\n  type Query {\n    getUser(id: ID!): User\n    listUsers: [User]\n  }\n\n  type Mutation {\n    createUser(name: String!, email: String): User\n  }\n`);\n\nconst userSchema = fs.readFileSync(schemaPath, 'utf8');\n\nconst resolvers = {\n  Query: {\n    getUser: (_, { id }) => ({\n      id,\n      name: `User ${id}`,\n      email: `user${id}@example.com`,\n    }),\n    listUsers: () => [\n      { id: '1', name: 'Alice', email: 'alice@example.com' },\n      { id: '2', name: 'Bob', email: 'bob@example.com' },\n    ],\n  },\n  Mutation: {\n    createUser: (_, { name, email }) => ({\n      id: Math.random().toString(36).substring(7),\n      name,\n      email,\n    }),\n  },\n};\n\nconst tester = new EasyGraphQLTester(userSchema, resolvers);\n\nasync function runTests() {\n  try {\n    // Test a valid query\n    const query = `\n      query GetUser($id: ID!) {\n        getUser(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n    const variables = { id: '1' };\n    const result = await tester.graphql(query, undefined, undefined, variables);\n    console.log('Valid Query Result:', JSON.stringify(result, null, 2));\n    // Expected: { \"data\": { \"getUser\": { \"id\": \"1\", \"name\": \"User 1\" } } }\n\n    // Test a valid mutation\n    const mutation = `\n      mutation CreateNewUser($name: String!, $email: String) {\n        createUser(name: $name, email: $email) {\n          id\n          name\n          email\n        }\n      }\n    `;\n    const mutationVariables = { name: 'Charlie', email: 'charlie@example.com' };\n    const mutationResult = await tester.graphql(mutation, undefined, undefined, mutationVariables);\n    console.log('Valid Mutation Result:', JSON.stringify(mutationResult, null, 2));\n    // Expected: { \"data\": { \"createUser\": { \"id\": \"...\", \"name\": \"Charlie\", \"email\": \"charlie@example.com\" } } }\n\n  } catch (error) {\n    console.error('Test Failed:', error.message);\n  }\n}\n\nrunTests();\n","lang":"javascript","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":">=6.0.0"},{"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.","message":"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.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Initialize the tester with your schema and resolvers: `new EasyGraphQLTester(schema, resolvers);`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"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).","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.","error":"TypeError: easygraphql_tester_1.EasyGraphQLTester is not a constructor"},{"fix":"Double-check the GraphQL schema definition for the existence and correct spelling of the queried operation. Verify the query string for typos.","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.","error":"Error: The query/mutation '...' is not defined on the schema."},{"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.","cause":"The GraphQL schema provided to `EasyGraphQLTester` contains references to types that are not defined within the schema itself or linked schemas.","error":"GraphQL schema validation error: Unknown type \"...\""},{"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.","cause":"There is a syntax error within the GraphQL query, mutation, or schema definition string.","error":"Syntax Error: Unexpected Name \"...\""}],"ecosystem":"npm"}