Ability to prevent/stop loading 'Page load' in Cypress when clicked a hyperlink

Viewed 2330

In my Cypress test, I need to test a link which downloads a .txt, .xlsx and a .zip file when clicked, but when I use "click()" to click the hyperlink, it starts a page load and expects a new action to happen as a result of clicking a link.

Here is a screenshot of the issue described above

As an alternative to this I tried using the cy.downloadFile() to download the files directly through the link but the link I am using is dynamically generated hence I am unable to use that as well. Hence I want to store the newly generated link in the variable and then use it in cy.downloadFile() every time I run the test.

Are there any other ways to test a hyperlink or how to store the dynamically generated link every time the test is run?

2 Answers

Hi there i been through this problem before.

I think it is the same scenario where the cypress test runner just keep waiting page load event and not go to the next test command while file are successfully downloaded.

Add custom cy.window event to listen the click event and add timeout to "force" reload current page, you need to tweak the timeout value so it suitable for your test.

    it.only('tes button download', ()=> {
        // visit url
        cy.visit("/spmb/list_nilaiseleksi");
        cy.get('#wrap-button > .btn').click()
        
        //download
        cy.window().document().then(function (doc) {
            doc.addEventListener('click', () => {
              setTimeout(function () { doc.location.reload() }, 5000)
            })
            cy.get(':nth-child(9) > .col-md-12 > .btn').click()
        })

    })

More details and discussion available here on cypress github issue : https://github.com/cypress-io/cypress/issues/14857

I found a way to store the link of the element I want to click. Since I am able to store the link, I am able to solve the requirement by using cy.downloadFile().

cy.get('@selector', {timeout: 15000}).then(($input) => {
            cy.downloadFile($input.attr('href'),'cypress/downloads','filename.csv')
        });
Related