DEV Community

Diego Daniel
Diego Daniel

Posted on

How to wait for requests on Cypress tests

With cy.route() you can create an alias for a particular request, and then later wait with cy.wait() for that request to be made and return a response, like this:

describe('Some page', () => {
  beforeEach(() => {
    // Needs to be called before cy.route
    cy.server();

    // Alias request
    cy.route('POST', '**/items/show_all').as('showAll');
    cy.visit('/page');
  });

  it('should test something', () => {
    cy.get('[data-testid=GetItemsButton]').click();

    // Waits for request to finish and fails if it's not made
    cy.wait('@showAll');
    cy.get('[data-testid=ItemsList]')
      .should('be.visible')
      .and('contain', 'Item 1')
      .and('contain', 'Item 2');
  });
});

If you need to make assertions on the response

You can with a callback!

cy.wait('@showAll').then((response) => {
  expect(response.body.length).to.be(5);
});

Documentation

You can get more details on the function calls here:

Happy testing!

Top comments (0)