cypress-graphql-mock
Adds commands for executing a mocked GraphQL server using only the client
Installation
npm install cypress-graphql-mock
in Cypress' commands.js
add:
; // Set all of your base mocks, as described in// https://www.apollographql.com/docs/graphql-tools/mocking/#default-mock-example;
See the "code generation" section below for more info on how to generate types for this.
Instructions
Adds .mockGraphql()
and .mockGraphqlOps()
methods to the cypress chain.
The .mockGraphql
should be called in the Cypress before
or beforeEach
block
config to setup the server. This method takes a schema, either in the form of one or more SDL files, or as the JSON result of an introspection query.
;// alternatively, using a dumped introspection query:// const schema = require('../../dumped-schema.json') beforeEach;
Actually it is not possible to use fs.readFileSync
right in the cypress tests. So here you can create custom command. Add this to your cypress/plugins/index.js
.
module.exports =
And then in the code you will be able to
beforeEach;
By default, it will use the /graphql
endpoint, but this can be changed
depending on the expected server implementation.
beforeEach;
It takes an "operations" object, representing the named operations of the GraphQL server. This is combined with the "mocks" option, to modify the output behavior per test.
The .mockGraphqlOps()
allows you to configure the mock responses at a
more granular level
For example, if we has a query called "UserQuery" and wanted to explicitly force a state where a viewer is null (logged out), it would look something like:
.mockGraphqlOps
Examples
Real application example
Simple mutation
Just return mutation result. Make sure that mostly always you will need to duplicate mutation name 1st time as operation key, and 2nd as return data object key.
cy.server;cy.mockGraphql;cy.mockGraphqlOps;
It is also possible to pass a function to simulate dynamic resolver.
cy.server;cy.mockGraphql;cy.mockGraphqlOps;
Delay
In order to test asynchronous behavior sometimes you will need to delay your graphql request. This can be done with a help of delay
option.
cy.mockGraphqlOps;
Code Generation
This plugin ships with a graphql-code-generator plugin to generate typings for the "RootTypes" and the mock operations.
See the graphql-code-generator docs around plugins, and the example app / codegen.yml
in the root for an example use:
test/cypress/generated/generated-mock-types.d.ts: documents: "test/test-graphql-app/**/*.jsx" plugins: - typescript - typescript-operations - cypress-graphql-mock/codegen config: enumsAsTypes: true
Error handling
; cy.mockGraphqlOps;
It is also possible to throw error from the function. Just return
or throw
a GraphQLError.
cy.mockGraphqlOps;
License
MIT