Cypress: cy.route2: Redefined route alias doesn't override the old one like cy.route

Created on 8 Oct 2020  路  2Comments  路  Source: cypress-io/cypress

Current behavior

We expect that different X-Custom-Header to be sent each time.

function mockPerson(id) {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Expose-Headers': '*',
    'Content-Type': 'application/json',
    'X-Custom-Header': `case-${id}`,
    'Last-Modified': 'Mon, 18 Jul 2016 02:36:04 GMT',
  };

  cy.route2(
    {
      hostname: 'swapi.dev',
      method: 'GET',
      pathname: '/api/people',
    },
    {
      fixture: 'example',
      headers,
    },
  ).as('getPerson');
}

describe('App', function () {
  it('renders the app', function () {
    mockPerson(1);
    cy.visit('/');
    cy.contains('Person 1').click();
    cy.wait('@getPerson');
    mockPerson(2);
    cy.contains('Person 2').click();
    cy.wait('@getPerson');
  });
});

We get the same header back both times X-Custom-Header: case-1.

image

Cypress has both aliases but it picks the wrong one.

image

The culprit seems to be this line of code. It finds the first alias rather than last defined alias. The fix is very simple find in reverse.

https://github.com/cypress-io/cypress/blob/4ce2a5acc141abe82b9407bf9ff82790345aa73f/packages/driver/src/cy/net-stubbing/wait-for-route.ts#L16-L17

Desired behavior

Route alias should be over-writable like cy.route. See this SO Answer

Test code to reproduce


https://github.com/ranjithnori/cy-route2-override-issue

Versions

Cypress 5.3.0

pknet-stubbing needs investigating unexpected behavior

Most helpful comment

@flotwig #8531 works well for my use case. Thanks for the quick response on issue. I love using cypress. Have a great day!!

All 2 comments

Hey @vramana, this is actually intentional, due to the design of cy.route2. If multiple routes match, the request will be passed to the next route until it is resolved via response.

See this example for more information: https://docs.cypress.io/api/commands/route2.html#Passing-a-request-to-the-next-route-handler

It sounds like, maybe what you want, is to be able to control the number of times that each route is matched? If so, check out this issue for progress on that feature, along with workaround code you can use today: https://github.com/cypress-io/cypress/issues/8531

@flotwig #8531 works well for my use case. Thanks for the quick response on issue. I love using cypress. Have a great day!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

carloscheddar picture carloscheddar  路  3Comments

Francismb picture Francismb  路  3Comments

jennifer-shehane picture jennifer-shehane  路  3Comments

zbigniewkalinowski picture zbigniewkalinowski  路  3Comments

egucciar picture egucciar  路  3Comments