Mocking XHR requests with Cypress

Marie Drake

Principal Test Automation Engineer @ News UK

mariedrake.com         @mcruzdrake 

https://www.linkedin.com/in/marie-drake/

 

Cypress lunch and learn recap

  • Cypress functional testing ✅
  • Cypress API testing ✅
  • Cypress Visual testing with Applitools ✅
  • Testing iframes with Cypress ✅

What is a Mock API?

  • Imitation of the real API which sends expected responses to a request
  • Requires great understanding of the real API so it can be imitated correctly

Real API

👍🏼 Tests the real behaviour

👍🏼 Catch performance issues

👍🏼 More confidence that critical paths are verified

👍🏼 Straightforward to test

API mocks

👍🏼 Speeds up development

👍🏼 Speeds up testing

👍🏼 Quicker to run

👍🏼 Simulate delays

👍🏼 Avoids flaky tests as results are deterministic

👍🏼 Simulate different scenarios easily and test different status codes

 

Real API

👎🏼 Slower to run

👎🏼 Requires a dedicated environment

👎🏼 Can cause flaky tests if the API is still in development mode

👎🏼 Makes application under test dependent on other services

API mocks

👎🏼 More effort to maintain

👎🏼 Bugs can be missed if mock API is not updated

 

Should I mock or should I not?

Consider a Hybrid Approach

Testing real API endpoints with Cypress

/// <reference types="cypress" />

describe('Todo API', () => {
  it('returns a JSON data', () => {
    cy.request('/todos')
      .its('headers')
      .its('content-type')
      .should('include', 'application/json');
  });
});

Let's mock API requests with Cypress!

Image Search App

What we did

  • Introduced cy.server()
  • Introduced cy.route()
  • Mock a specific request
  • Simulated scenarios where API is returning data or not

Additional Resources

Any questions?