cypresscypress-intercept

Cypress intercept not overriding Cypress alias


I'm doing some testing and I intercept some API calls to the same URL, I do one beforeEach, and then another one on the test, but for some reason I does not understand that I changed the alias. I was doing some reading, and the overriding was fixed, but apparently is not?

My code:

beforeEach(() => {
  cy.visit("/");
  cy.intercept(
    {
      method: "GET",
      url: "/customers*",
      hostname: "local.api",
    },
    {
      fixture: "customers.json",
    }
  ).as("customers");
  cy.get("[class^=ant-menu-item]", { multiple: true }).eq(1).click();
  cy.wait("@customers");
});



[
  ["customerName", "ASC", 0],
  ["nextReviewDate", "ASC", 1],
  ["nextReviewType", "ASC", 2],
].forEach(([sortValue, sortOrder, index]) => {
  it(`Sort by direction ${sortOrder} order ${sortValue}`, () => {
    cy.get(".ant-table-column-sorters", { multiple: true }).eq(index).click();
    cy.intercept("GET", "/customers*").as("request");
    cy.wait("@request").then((interception) => {
      cy.wrap(interception.response.statusCode).should("eq", 200);

      cy.wrap(interception.request.url).should(
        "include",
        `https://allica.local.api/customers?page=1&sortBy=${sortValue}&pageSize=5&direction=${sortOrder}`
      );
    });
  });
});

The following error:

"No request ever occurred" error

If there is not overriding, how can overcome this test?


Solution

  • The intercept is an event listener. It must be set up before the event is triggered

    cy.intercept("GET", "/customers*").as("request");
    cy.get(".ant-table-column-sorters", { multiple: true }).eq(index).click();
    cy.wait("@request").then((interception) => {
      ...
    

    Actually, there's no change to the intercept between tests so you can just set it once and wait multiple times

    before(() => cy.intercept("GET", "/customers*").as("request"))
    
    [
      ["customerName", "ASC", 0],
      ["nextReviewDate", "ASC", 1],
      ["nextReviewType", "ASC", 2],
    ].forEach(([sortValue, sortOrder, index]) => {
      it(`Sort by direction ${sortOrder} order ${sortValue}`, () => {
        cy.get(".ant-table-column-sorters").eq(index).click();
        cy.wait("@request").then((interception) => {