cypress cy.route not behaving consistently

Viewed 259

I am trying to stub out a route using cypress 5.2. I have a simple function to do that:

function mockAlertsResponses(){
  cy.route({
    method: "GET",
    url: "/api/polling/alerts/statistics*",
    response: {
      total: 2,
      ...
    }
  });
}

In one set of tests, this works just fine:

describe("admin and read only permissions", () => {
  it ("all action bar items are enabled with admin permissions", () => {
    cy.login("user", "password");
    mockAlertsResponses();

    // Click alert to enable all buttons
    cy.get("#1-checkbox").click()

    cy.get("#mark-alert-button").should("be.enabled");
    cy.get("#delete-alert-button").should("be.enabled");
  });

  // ... a few more similar tests
});

However, in another set of tests, I use the same function:

  it("Logs in and out", () => {
    cy.login("username", "password");
    mockAlertsResponses()
    cy.get("#vine-appbar").should("be.visible");
    cy.get("#info-button").click();
    cy.get("#info-menu-logout").click();
    cy.get("#login-button");
    cy.get("#vine-appbar").should("not.be.visible");
  });

In this second set of tests, the routes are not stubbing properly, leading to errors and test failures. Here, you can see the route is not stubbed, but rather throws a 500 error:

enter image description here

I'm not sure what could be interfering here. I'm a bit new to cypress and I'm not even sure where to begin debugging this. Might the cy.server calls be interfering? Please let me know what more information we'd need to figure out why one set of stubs works and another doesn't.

If you're wondering, the login function has a call to cy.server and has its own cy.route as well:

Cypress.Commands.add("login", (username, password, admin = true) => {
  const response = admin ? <jwt1> : <jwt2>
 
  cy.server();
  cy.route({
    method: "POST",
    url: "/api/login",
    response
  });
  cy.visit("/logout");

  cy.visit("/");
  cy.wait(100);
  cy.get("#login-error").should("not.be.visible");
  cy.get("#login-username").type(username);
  cy.get("#login-password").type(password);
  cy.get("#login-button").click();
});
0 Answers
Related