Frames and Files
File Download in Playwright
File Download in Playwright: definition, download event handling, saveAs examples, mistakes, interview notes, and practice.
Definition and Brief Explanation
Definition: File download in Playwright captures a download event triggered by the page and gives access to the downloaded file.
Explanation: The download wait must start before the click that triggers the file. After the event is captured, the test can inspect the suggested file name, save the file, or verify that the download happened correctly.
Why It Matters
- It proves that export, invoice, report, and attachment downloads actually start.
- It captures the browser download event reliably when the wait starts before the click.
- It lets the test verify the suggested file name or save the file for deeper checks.
- It is useful in CI because the browser download UI is not visible.
How It Works
- Create a download wait before clicking the download control.
- Trigger the download from the page.
- Read the suggested filename or save the downloaded file.
- Assert that the expected file was downloaded and, when needed, inspect its content.
Syntax and Examples
Example 1: Download file
const downloadPromise = page.waitForEvent('download');
await page.getByRole('link', { name: 'Export' }).click();
const download = await downloadPromise;
await download.saveAs('report.csv');
Explanation: Start waiting before clicking Export, then save the downloaded file.
Common Mistakes
- Starting waitForEvent("download") after the click.
- Only clicking Download without checking the download object.
- Assuming the local Downloads folder is available in CI.
- Not validating file name, type, or saved path.
Interview Notes
- Why should the download wait start before the click?
- How do you get the suggested filename?
- How do you save a downloaded file?
- What can make download tests fail in CI?
Practice Task
Write a test that downloads a report, checks the suggested filename, saves it to a test output folder, and verifies the file exists.