DEV Community

Cover image for How to intercept and mock the response of an HTTP request with Cypress

Posted on • Updated on

How to intercept and mock the response of an HTTP request with Cypress

Today, in “Pinches of Cypress”, learn how to mock the server's response

Sometimes we need to run automated tests in environments where we have no control over the data.

It would be useful in such situations if we could intercept the call to the server and then mock its answer with known data.

I have good news. With Cypress, you can achieve this easily.

I will present a simple example, but the idea is the same when working with more complex examples.

Imagine an application that allows the creation, reading, updating, and deletion of notes.

After logging into the application, the user is directed to their personal list of notes.

What to do if we do not have control over the number of existing notes for the test user in the production environment, for example?

After all, why not run tests in production, right? 😜

The test scenario is as follows. I want to test that only one element with the list-group-item class is displayed when there is no note in the list, and this element renders the button to create a new note.

Note: If there were more notes, each one would also be rendered in an element with the list-group-item class.

The test would be like this.

describe('Empty notes list', () => {
  beforeEach(() => {
    cy.intercept('GET', '**/notes', []).as('getNotes')

  it('renders only the button to add a new note', () => {
      .should('have.length', 1)
      .and('contain', 'Create new note)
Enter fullscreen mode Exit fullscreen mode

Notice that in the first line of the beforeEach function, I invoke cy.intercept passing as arguments the GET method, the '**/notes' route, and as an answer, an empty array ([]).

The return of the server when we make a GET request to the '**/notes' route is an array of notes, however, as we are mocking the response with an empty array ([]), this is what the frontend receives, and therefore, no notes are rendered.

Another advantage of running tests mocking server requests is that they run much faster!

That's it!

Are you enjoying the "Pinches of Cypress" series?

I'm looking forward to hearing your feedback!

This post was originally published in Portuguese on the Talking About Testing blog.

Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.

Top comments (2)

rebaiahmed profile image
Ahmed Rebai

Why you choosed to include the interception inside beforeEach hook and not inside the test defintion?

walmyrlimaesilv profile image

So the alias could be reused across all tests, if there was more than one.