Search code examples
cypressresponse

Fetch the API response that occurs after on click


I want to fetch the API response that I receive on clicking a button. In my use-case, after click the button, the response data is loaded on the page.

I need to get the response data upon clicking the button rather than testing the loaded page.

How can I perform this using Cypress?


Solution

  • As jonrsharpe mentions, you can use cy.intercept() to listen for the request, and then cy.wait() on the alias of the intercept to retrieve the data.

    Assumptions made in the example below are called out via comments

    cy.intercept('/foo') // assumes request is made to something like www.my-url.com/foo
      .as('foo'); // assign the intercept an alias
    cy.get('button') // find the button
      .click() // and click it
    cy.wait('@foo') // wait for the request to finish
      .then((interception) => {
        // Assertions on the request here
        // Convenience variable assignment
        const { body } = interception.response
        expect(body).to.not.be.null;
      });