Search code examples
javascripthtmlcypress

How to open new tab in same Cypress window when you don't have attributes like target and/or url in the href?


I am using Cypress 13.5.0 to automate testcases. My testcase is simple to click on link and it will open new tab then perform some actions in new tab.

I know Cypress do not support multi tabs and multi browser windows. I learn the workarounds and implemented as follows:

cy.get('MyLocator').invoke('attr', 'href').then(myLink => {
cy.visit(myLink)})

cy.get('MyLocator').should('have.attr', 'href')
.then((href) => {
cy.visit(href)})

None of above solution worked because in HTML i dont have a url link in href attribute instead a Javascript function is called in href attribute, following is the HTML code:

<td valign="center" style="width: 55%" class="row-white">
<a class="className" href="javascript:launchCourse('parameter')">courseName</a>
</td>

could any body help how to deal with that scenario. thanks for your help!


Solution

  • There is a pattern here Deal with window.open you can use to test this case.

    To summarize -

    There are a few ways that a window can be opened, one is by href as you pointed out. Another is by javascript call to window.open(addUrlParameters(url, params)).

    Using cy.stub() stops the window.open() call and allows you to assert that it has been called. It's necessary for regression testing to make sure no bug is introduced in the button click handler.

    cy.window().then(win => {
      cy.stub(win, 'open').as('open')
    })
    
    cy.get('MyLocator').click()
    
    cy.get('@open').should('have.been.calledOnceWithExactly', <url-for-window-open>)
    

    You need to know what <url-for-window-open> is - easy to find, just click in normal browser and copy the URL after window opens.

    To test that new page, start a second test and use cy.visit()

    it('regression test - new window is opened at <url-for-window-open>', () => {
      cy.visit(<page-with-link>)
      cy.window().then(win => {
        cy.stub(win, 'open').as('open')
      })
      cy.get('MyLocator').click()
      cy.get('@open').should('have.been.calledOnceWithExactly', <url-for-window-open>)
    })
    
    it('test page at <url-for-window-open>', () => {
      cy.visit(<url-for-window-open>)
      ... testing this page
    })