I have one scenario where I have to click on one link, that opens a new tab/window, As cypress does not support multiple tabs, I have found below workaround but its not working, It opens the new tab, but not able to switch the new tab and my test is failing with the error :
expected redirect to have been called at least once, but it was never called.
cy.
visit('https://qa.abc.com/xyz/documents?action_id=1');
cy
.window().then((win) => {
cy.spy(win, 'open').as('redirect');
});
cy
.get(':nth-child(1) > [style="width: 228px;"] > .text-ellipsis')
.click();
cy
.get('@redirect')
.should('be.called');
Note: Redirected url is dynamic and bind with the javascript, so not able to fetch the url from console also not able to remove the attribute from the link.
Here is the attached screenshot: enter image description here
Take a look at Stub window.open - this may have some relevance to your use-case.
If the application navigates to a new page or even reloads, the old window object is destroyed and the new window object is created. Thus our window.open stub can "disappear": the application calls window.open, but the stub does not intercept the new calls.
It is suggested you add .callsFake(stub) to your win.open stub (two different stubs used).
From the article
it('opens a new window', () => {
// create a single stub we will use
const stub = cy.stub().as('open')
cy.on('window:before:load', (win) => {
cy.stub(win, 'open').callsFake(stub)
})
cy.visit('/')
// triggers the application to call window.open
cy.click('Open new window')
cy.get('@open').should('have.been.calledOnce')
// cause the window to be recreated
cy.reload()
cy.click('Open new window')
// all window.open calls are correctly forwarded to our stub
cy.get('@open').should('have.been.calledTwice')
})
Your code
cy.visit('https://qa.abc.com/xyz/documents?action_id=1');
const stub = cy.stub().as('redirect') // alias here
cy.window().then((win) => {
cy.stub(win, 'open').callsFake(stub); // stub & fake here
});
cy.get(':nth-child(1) > [style="width: 228px;"] > .text-ellipsis')
.click();
cy.get('@redirect')
.should('be.called');
If that doesn't work, perhaps the link is not using window.open, maybe setting window.location. There are examples for stubbing that as well.