I'm having a really hard time trying to override an existing Intercept handler in my Cypress tests. I was using Cypress version 5 but I'm in the process of updating it. I'm currently on version 7, trying to get my tests to work before updating to newer versions.
I have checked existing questions here, but none of them worked for me, I even see contradictory information between them. For example here the accepted answer mentions that if you set up identical handlers with different aliases only the first one will fire BUT in here and here people indicate you can have similar handlers with different aliases and both will fire.
My code is pretty simple, this is a snippet :
...
describe("Loading Inventory", () => {
beforeEach(() => {
cy.intercept("GET", "/ui_connect/inventory/**", {
fixture: "operator/file.json",
statusCode: 200,
}).as("checkInventoryRequest");
});
it("My test", () => {
cy.intercept("GET", "/ui_connect/inventory/**", {
body: {},
statusCode: 500,
}).as("checkInventoryRequestWithError");
cy.get("[data-test=inventory-button]").click(); // This triggers the request
cy.wait("@checkInventoryRequestWithError").then(() => {
cy.get(".e-alert-dialog")
.contains("Inventory Generation Error")
.should("be.visible");
});
});
});
});
What I'm trying to do is to override the Intercept that was defined in the beforeEach
, but I have been unable to. I tried also naming both with the same tag, but the result is the same, my request always returns a 200 status code and the body from the fixture.
According to the documentation when executing the Request Phase it should take the last handler I defined, process it and end there, but that is not the behavior I'm seeing.
What could be the issue with my code?
Thanks
The code you have is working with Cypress v7.7.0.
Here is a minimal, reproducible variant using the same intercept pattern, but triggering the fetch from the test instead of the app.
The checkInventoryRequestWithError
alias is caught and processed correctly.
describe('Loading Inventory', () => {
beforeEach(() => {
cy.intercept('GET', '/ui_connect/inventory/**', {
fixture: 'operator/file.json',
statusCode: 200,
}).as('checkInventoryRequest')
})
it('My test', () => {
cy.intercept('GET', '/ui_connect/inventory/**', {
body: {},
statusCode: 500,
}).as('checkInventoryRequestWithError')
// This triggers the request
cy.window().then(win => {
win.fetch('https://some-domain/ui_connect/inventory/1')
})
cy.wait('@checkInventoryRequestWithError').then(interception => {
console.log(interception)
expect(interception.response.statusCode).to.eq(500)
})
})
})
If we change to cy.wait('@checkInventoryRequest')
, the test fails.
You should note, the documentation is for Cypress v12.11.0 and unlikely to give you what you need to know for prior versions, particularly the cy.intercept()
API which changed a lot over time.