Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

With Cypress, how to get the response body of an api call triggered by a non-request event

I am testing my login page with cypress. The call to my api /api/auth/login is triggered automatically when the input field of the password reaches 4 characters. So in my cypress spec file, the command cy.get("password-input").type("1234") is enough to trigger the api call. How can I get the response body of that api call? I would like to get the token my api sends back.

In classic api calls with the cy.request command I can easily handle the response body, but I couldn’t find how to access the response body when the api request is triggered by another event like here with the type event.

Currently, I have a workaround because my website stores the response.body.token in the localStorage, so I access the token with window and after a wait:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cypress test run

it("should get token", () => {
  cy.visit("/login")
  cy.get("[data-cy="login-input"]).type("myLogin")
  cy.get("[data-cy="password-input"]).type("0001")
  cy.wait(5000)
  cy.window().then(window => {
    cy.log(window.localStorage.getItem("myToken"))
  })
})

But this feels gross… Could you give me the proper way to access the response body of the api call triggered by the type event?

>Solution :

You can use cy.intercept(), aliasing, and cy.wait():

it("should get token", () => {
  cy
    .intercept('/api/auth/login')
    .as('token');
  cy
    .visit("/login");
  cy
    .get('[data-cy="login-input"]')
    .type("myLogin");
  cy
    .get('[data-cy="password-input"]')
    .type("0001");
  cy
    .wait('@token')
    .then(intercept => {
      // you can now access the request body, response body, status, ...
    });
});

Useful reading:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading