Thomas Perrin
Thomas Perrin

Reputation: 784

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:

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?

Upvotes: 3

Views: 13349

Answers (1)

pavelsaman
pavelsaman

Reputation: 8362

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:

Upvotes: 7

Related Questions