In my Cypress code, I want to decide action based upon the response from the backend. Please note, I am not mocking a server, rather wanting to hit & get response from API server & base next commands off the response.
cy.visit("http://localhost:3000/login");
cy.get(".cookieConsent button").click();
cy.get("#email-input").type(userLoginDetail.email);
cy.get("#password-input").type(userLoginDetail.password);
cy.get("form").submit();
cy.wait(3000);
// logic being it user is redirected to homepage, then login was successful. Not happy with this O(
if (cy.url() === "http://localhost:3000/") {
console.log("eeeeeeeeeee");
} else {
console.log(
"aaaaaaaaaaaaaaaaaaa ");
How can I check the response from the form submission & use if
condition based off that.
I think the problem is, that you want to do conditional testing. Using cy.wait()
is bad practice and is even mentioned in the docs itself.
Anti-Pattern
You almost never need to wait for an arbitrary period of time. There are always better ways to express this in Cypress.
You should not execute different actions upon response. In cypress testing it is expected, that you know the result of your action beforehand.
If user enters invalid email, you might expect form submisson to fail and an error to be displayed.
cy.get("#email-input").type('invalid_email.com');
cy.get("#password-input").type(userLoginDetail.password);
cy.get("form").submit();
cy.get(".email-error").should('be.visible');
In this case cypress will check them DOM until it finds the error or hits the defaultCommandTimeout
from cypress config.
On the other hand, if you want to check if user is redirected correclty, you can simply check for a div
on the success/redirected page.
cy.get("#email-input").type('[email protected]');
cy.get("#password-input").type(userLoginDetail.password);
cy.get("form").submit();
cy.get(".success-page").should('be.visible');
However, if you still decide to execute an action depending on the servers response, cypress enables you to declaratively cy.wait()
for requests and their responses.
cy.server()
cy.route({
method: 'POST',
url: '/myApi',
}).as('apiCheck')
cy.visit('/')
cy.wait('@apiCheck').then((xhr) => {
assert.isNotNull(xhr.response.body.data, 'api call successfull')
})