Playwright · Reliable end-to-end tests
How do you test file downloads?
Short answer
Wait for the download event, then save or inspect the file with saveAs() or path(). Downloads are accepted by default in Playwright contexts.
A download is not a navigation, so a click alone does not give you the file. Start waiting for the download event before the action that triggers it, then use the Download object to save or read the file.
const downloadPromise = page.waitForEvent("download");
await page.getByRole("button", { name: "Export CSV" }).click();
const download = await downloadPromise;
await download.saveAs("downloads/export.csv");
expect(download.suggestedFilename()).toContain(".csv");What you can do with a download
download.saveAs(path)copies the file to a location you controldownload.path()returns the temporary file path for readingdownload.suggestedFilename()returns the server's suggested namedownload.failure()returns the failure reason, or null on success- Set
acceptDownloads: falsein the context if a test should reject downloads
If the test needs to verify content, read the saved file with Node's file APIs and parse it. That turns a download test from checking that a click happened into checking that the exported data is correct.
import { readFile } from "node:fs/promises";
const downloadPromise = page.waitForEvent("download");
await page.getByRole("button", { name: "Export JSON" }).click();
const download = await downloadPromise;
const path = await download.path();
const raw = await readFile(path, "utf8");
const data = JSON.parse(raw);
expect(data.orders).toHaveLength(3);Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you read the contents of a downloaded file?
- 2What is the difference between path and saveAs?
- 3How do you reject downloads in a context?
- 4Why should download artifacts not be committed?
Say it in the interview
I set up a wait for the download event before clicking the export button, then save the file with saveAs or read the temporary path. If the content matters, I parse the saved file and assert on the exported data, not just the filename. The temporary file can disappear when the context closes, so I copy it somewhere stable first. I keep generated downloads out of version control.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Playwright mock interview and get scored feedback on depth, clarity and confidence.