My web application, on load, automatically redirects the user to a URL on a different origin via the window.location.replace
method based on their user parameters.
When Cypress tests my application and attempts to follow the redirect, it detects the violation of the same-origin
security policy and the test crashes. But I still need to test that window.location.replace
is being called correctly.
Based on Cypress's documentation, I believe I need to use cy.stub()
to mock the function, in order to avoid the side effect of the browser actually redirecting to a different origin.
I have tried several different ways to stub window.location.replace
, but none of them seem to work as I expect.
// none of these work
cy.stub(window.location, "replace")
// TypeError: Cannot redefine property: replace
cy.stub(window, "location.replace")
// TypeError: Cannot stub non-existent own property location.replace
window.location.replace = cy.stub()
// TypeError: Cannot assign to read only property 'replace' of object '[object Location]'
cy.visit("http://localhost:3000");
expect(window.location.replace).to.be.called;
expect(window.location.replace).to.be.calledWith('https://some-other-origin.com/some/url')
I do not believe I want to use cy.location()
because, by the time the redirect has occurred, the test has already crashed due to the same-origin
security violation.