Search code examples
graphqlapollocypress

Mock specific graphql request in cypress when running e2e tests


When running e2e tests with Cypress, my goal is to mock a specific graphql query.

Currently, I can mock all requests like this:

cy.server();
cy.route('POST', '/graphql', {
    data: {
        foo: 'bar'
    },
});

The problem is that this mocks all /graphql queries. It would be awesome if I somehow could say:

cy.route('POST', '/graphql', 'fooQuery', {
    data: {
        foo: 'bar'
    },
});

In our application, we are using Apollo Graphql - and thus all queries are named.


Solution

  • With cypress 6.0 route and route2 are deprecated, suggesting the use of intercept. As written in the docs (https://docs.cypress.io/api/commands/intercept.html#Aliasing-individual-GraphQL-requests) you can mock the GraphQL requests in this way:

    cy.intercept('POST', '/api', (req) => {
      if (req.body.operationName === 'operationName') {
        req.reply({ fixture: 'mockData.json'});
      }
    }