A Jest utility for validating GraphQL mocks against your schema and simplifying GraphQL API testing by providing mockable query functionality.
To install the library, use npm or yarn:
npm install jest-gql-mock-validator --save-devor
yarn add jest-gql-mock-validator --devTo enable the library in your Jest environment, you need to extend Jest with the custom matchers and mocks provided by jest-gql-mock-validator.
Update your jest.config.js to include the setup file:
module.exports = {
setupFilesAfterEnv: ["jest-qgl-mock-validator"],
};This library uses graphql-config to manage and load your GraphQL schema. Ensure you have a valid graphql-config configuration file in your project root.
.graphqlrc.graphqlrc.json.graphqlrc.yamlor.graphqlrc.ymlgraphql.config.js
Create a .graphqlrc.yml file in your project root to specify the schema location:
schema: ./schema.graphqlFor more details on how to configure graphql-config, refer to the graphql-config documentation.
The library provides utilities for:
- Validating the JSON response against the provided GraphQL query when mocking a response.
- Independently validating a JSON object against a provided GraphQL query.
Use mockGqlQuery() to construct a mock in lieu of jest.fn() to allow the use of .mockResolvedGqlOnce() to validate the response against the provided GraphQL queries or mutations:
import { mockGqlQuery } from "jest-gql-mock-validator";
import { getUsers } from "./queries";
// construct a mock that enables .mockResolvedGqlOnce below
const mockSendQuery = mockGqlQuery();
// validate that the JSON response being provided to the user is valid for the provided gql query or mutation
mockSendQuery.mockResolvedGqlOnce(getUsers, {
getUsers: [
{ id: "1", username: "Alice" },
{ id: "2", username: "Bob" },
],
});Use the custom matcher expect().toMatchGqlMock() to validate a JSON object against the GraphQL query or mutation:
expect(response).toMatchGqlMock(query);For example:
import { toMatchGqlMock } from "jest-gql-mock-validator";
import { getUsers } from "./queries";
const mockResponse = {
getUsers: [
{ id: "1", username: "Alice" },
{ id: "2", username: "Bob" },
],
};
expect(mockResponse).toMatchGqlMock(getUsers);Contributions are welcome! To contribute:
- Fork the repository.
- Create a new branch (
git checkout -b feature-name). - Commit your changes (
git commit -m "Add feature"). - Push to your branch (
git push origin feature-name). - Open a pull request.
This library is licensed under the MIT License. See LICENSE for details.