Mocking GraphQL for unit tests with Cypress

Unit testing GraphQL with Cypress

Cypress is great for front end mocking. Its purpose built for this with Promises in mind.Most commonly, cy.intercept is used for this.Eg.:cy.intercept(‘POST’, ‘/your-backend-api’, {}).as(‘backendAPI’);

cy.wait('@backendAPI').then(xhr => {

  expect(xhr.response.statusCode).to.equal(404);
});

Cypress Documentation

Network Requests | Cypress Documentation

What you’ll learn How Cypress enables you to stub out the back end with cy.intercept() What tradeoffs we make when we stub our network requests.

https://docs.cypress.io/guides/guides/network-requests

Examples for GraphQL

Cypress Documentation

Working with GraphQL | Cypress Documentation

What you’ll learn Best practices to alias multiple GraphQL queries or mutations for a group of tests. Overriding an existing intercept to modify…

https://docs.cypress.io/guides/testing-strategies/working-with-graphql

Unit Testing

For an example in .net, we can rely on something like Nunit combined wth Rest Sharp to get our GraphQL service tested.

Rest sharp is really just an option for us to make that REST call

you can use any other

Nunit, its just our assertion library, you can use any other here as well

Java based?

Well using RestTemplates and Junit would do great as basic tools.

Using Native GraphQL

Its best to try and work directly with these components.

https://www.graphql-tools.com/docs/mocking
https://graphql.org/blog/mocking-with-graphql/