Change fixture response in cypress for the same url with intercept Change fixture response in cypress for the same url with intercept angular angular

Change fixture response in cypress for the same url with intercept


Slightly clumsy, but you can use one cy.intercept() with a Function routeHandler, and count the calls.

Something like,

let interceptCount = 0;  cy.intercept('http://localhost:4200/testcall', (req) => {     req.reply(res => {         if (interceptCount === 0 ) {      interceptCount += 1;      res.send({ fixture: 'example.json' })    } else {      res.send({ fixture: 'example2.json' })    }  }); });

Otherwise, everything looks good in your code so I guess over-riding an intercept is not a feature at this time.


Cypress command cy.intercept has thetimes parameter that you can use to create intercepts that only are used N times. In your case it would be

cy.intercept('http://localhost:4200/testcall', {   fixture: 'example.json',  times: 1 });...cy.intercept('http://localhost:4200/testcall', {   fixture: 'example2.json',  times: 1});

See the cy.intercept example in the Cypress recipes repo https://github.com/cypress-io/cypress-example-recipes#network-stubbing-and-spying


As of Cypress v7.0.0 released 04/05/2021, cy.intercept() allows over-riding.

We introduced several breaking changes to cy.intercept().

  • Request handlers supplied to cy.intercept() are now matched starting with the most recently defined request interceptor. This allows users to override request handlers by calling cy.intercept() again.

So your example code above now works

cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });// when visiting the page it makes one request to http://localhost:4200/testcallcy.visit('http://localhost:4200');cy.get('.output').should('contain.text', '111');// now cypress should change the response to the other fixturecy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });cy.get('.button').click();cy.get('.output').should('contain.text', '222');