https://cypress.io logo
What is the correct way to test a link opening in ...
# i-need-help
b
Suppose there is an anchor tag or a button in an application. Clicking on that anchor tag or button opens up a new application in a new tab. I want to test if that new app opened correctly after the click event. What should be the correct way of testing it in Cypress? How I am trying to test is, I am spying on the window.open function and then making an assertion if the window.open function was called with an expected URL argument. Below is a sample test for this same scenario: describe('Global Navigation', () => { it(
should open app in new tab
, () => { cy.mount(); cy.spy(window, 'open').as('windowOpen'); const uniqueAppName = 'Sample App'; const expectedURL = 'http://localhost/sampleapp'; cy.contains(uniqueAppName).should('be.visible').click(); cy.get('@windowOpen').should('have.been.calledWith', expectedURL, '_blank'); }); }); But the problem is the URL that opens up in new tab return 404 error and I know that it will return 404 because it is a dummy URL. I don't care whatever that new tab returns I just wanted to test if that URL was called by window.open function. While running the test in Cypress desktop app (using cypress open command) the test shows it passed and runs all the other tests as well. But when running the test using
cypress run
command (in headless mode), the CLI passes the current test then throws error 404 and exits out and does not run rest of the tests. Is there a way to just ignore that error because I am anyway expecting it? I have attached the error message. If you think this is an incorrect approach to test a link in new tab, please do suggest what should be the right approach? Another query: If I am expecting an error that is known, like in above scenario I knew I will be getting a 404 error, is it a good practice to do error handling in a test environment like using try-catch blocks?
g
e
If you want to just make sure the call happens for the tab to open you could do something like
Copy code
cy.stub(win, 'open')
and then later after you click the button to open the tab
Copy code
cy.get('@open).should('have.been.calledOnce')
t
^^
2 Views