<html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Change Content - Javascript</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="robots" content="noindex, nofollow"> <meta name="googlebot" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <a id="myelement" href="javascript:void(0);" onclick="openNewTab()" "="">Open New Tab </a> <script type="text/javascript">//<![CDATA[ function openNewTab() { window.openNew({ target:'test_blank', url: 'https://www.google.co.in/' }); } function openNew(option) { const form = document.createElement("form"); form.target = option.target || "_blank"; form.action = option.url; form.method = "GET"; document.body.appendChild(form); form.submit(); //debugger; $(form).remove(); } //]]> </script> </body> </html>
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
Above is the sample HTML file, Which replicates the issue:
Advertisement
Answer
The redirect is quite unusual.
You can block the new tab by using an intercept on the page load.
Another intercept will verify the redirect goes to correct URL.
it('tests a funky redirect', () => { const baseUrl = Cypress.config('baseUrl') cy.intercept('GET', baseUrl, (req) => { req.continue(res => { res.body = res.body.replace( 'form.target = option.target || "_blank";', 'form.target = "_self";' // prevent tab opening ) }) }) cy.visit(baseUrl); cy.intercept('GET', '**/www.google.co.in/*').as('newTab') cy.get('a').click() cy.wait('@newTab').then(interception => { expect(interception.request.url).to.include('www.google.co.in') }) cy.go('back') // previous location });