в моём cypress проекте есть тест где после нажатия на кнопку download с сайта скачивается xlsx файл. файл без проблем скачивается в папку cypress/downloads. но в выводе результатов работы теста в cypressя вижу, что после нажатия на кнопку downloads тест падает с ошибкой:
(page load)--waiting for new page to load--
(download)C:\Users\Oleg\settlement_smoke_tests\cypress\downloads\powerunit_sample.xlsx
CypressError
Timed out after waiting 60000ms for your remote page to load.
Your page did not fire its load event within 60000ms.
You can try increasing the pageLoadTimeout value in dev.config.js to wait longer.
Browsers will not fire the load event until all stylesheets and scripts are done downloading.
When this load event occurs, Cypress will continue running commands.
похоже на то, что тест ждёт загрузки какой-то страницы, хотя файл уже скачался без проблем и никакая страница открываться не должна.
The issue you're experiencing is a common one when automating file downloads in Cypress, especially when the download is triggered via a change to window.location.href. When you click the download button, the browser navigates to the file's URL (/samples/powerunit_sample.xlsx), which initiates the file download. However, since this URL serves an .xlsx file rather than an HTML page, the browser doesn't fire a load event for a new page. Cypress expects a load event after any navigation and waits for it by default. Because the load event never occurs, Cypress times out after 60 seconds (60000ms), resulting in the error you're seeing.
Understanding the Problem:
Navigation Triggered by location.href: The button's onclick handler sets window.location.href to the URL of the file, which causes the browser to navigate to the file URL.
Cypress Waits for load Event: Cypress detects navigation and waits for the new page's load event before proceeding.
No load Event for File Downloads: Since the file download doesn't load a new HTML page, the load event never fires.
Test Times Out: Cypress waits until the default pageLoadTimeout (60 seconds) and then throws a timeout error.
Solution:
To resolve this issue, you can prevent the navigation from occurring and instead handle the file download directly within your test using cy.request(). This allows you to:
Bypass the browser's navigation, so Cypress doesn't wait for the load event.
Directly download the file and save it to a specified location.
Verify the file's content or properties as needed.
Step-by-Step Fix:
Extract the Download URL:
Since the download URL is embedded in the button's onclick attribute, you can extract it using a regular expression.
Use cy.request() to Download the File:
Use cy.request() to send a GET request to the download URL. Set the encoding option to 'binary' to correctly handle binary files like .xlsx.
Save the File with cy.writeFile():
Write the response body to a file in the cypress/downloads directory using cy.writeFile() and specify the binary encoding.
Example Code:
javascript
cy.get('button#sample_file').then($button => {
// Extract the URL from the onclick attribute
const onclickAttr = $button.attr('onclick');
const urlMatch = onclickAttr.match(/location.href='([^']+)'/);
const downloadUrl = urlMatch ? urlMatch[1] : null;
if (downloadUrl) {
// Use cy.request() to download the file
cy.request({
url: downloadUrl,
encoding: 'binary',
}).then((response) => {
// Verify the response status code
expect(response.status).to.eq(200);
// Write the file to the downloads folder
cy.writeFile('cypress/downloads/powerunit_sample.xlsx', response.body, 'binary');
// Optionally, perform further assertions on the file
// For example, verify the file size or content
});
} else {
throw new Error('Download URL not found');
}
});
Explanation of the Code:
Extracting the URL:
onclickAttr.match(/location.href='([^']+)'/): This regular expression captures the URL inside the single quotes after location.href=.
Downloading the File:
cy.request({ url: downloadUrl, encoding: 'binary' }): Sends a GET request to the download URL, treating the response body as binary data.
Writing the File:
cy.writeFile('cypress/downloads/powerunit_sample.xlsx', response.body, 'binary'): Saves the binary response body to a file in the specified path.
Benefits of This Approach:
Prevents Cypress Timeout: Since no navigation occurs, Cypress doesn't wait for the load event, and the test doesn't time out.
Direct Control Over Download: You can handle the file directly, allowing for additional assertions or file manipulations.
No Need to Alter Application Code: This solution doesn't require changes to the application under test, making it a clean and maintainable approach.
Alternative Approaches:
Adjust pageLoadTimeout: While you could increase or disable the pageLoadTimeout, this isn't recommended as it can mask underlying issues and lead to longer test execution times.
Prevent Navigation in the App Code: Modifying the application's JavaScript to prevent navigation during tests is invasive and not ideal.
Use Plugins: There are Cypress plugins that can assist with file downloads, but they add extra dependencies and complexity.
Conclusion:
The problem arises because Cypress waits for a page load event that never occurs when downloading a file via navigation. By preventing the navigation and handling the download directly with cy.request(), you can avoid the timeout error and have more control over the file download process in your Cypress tests.
Answer Summary:
The error occurs because clicking the download button navigates to the file's URL, causing Cypress to wait for a page load event that never occurs (since it downloads a file, not an HTML page). To fix this, prevent the navigation by not clicking the button, and instead use cy.request() to download the file directly in your test. Here's how: