File Download
Files made in the browser, served as they are, and generated by the server. Catch each one and check what is inside.
Catch the download
Start waiting for the download event, then click. The file is saved to a temporary folder that is deleted when the browser context closes.
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export users as CSV' }).click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toBe('users.csv');Read what is inside
A file that downloads is not yet a correct file. Read it and assert its contents:
const content = await readFile(await download.path(), 'utf-8');
const users = JSON.parse(content); // for the JSON export
expect(users).toHaveLength(4);To keep a file after the test, for example to attach it to the report, use download.saveAs(testInfo.outputPath(name)).
Names you cannot predict
The server names the monthly report after the current month. Match the pattern, not one exact name:
expect(download.suggestedFilename()).toMatch(/^report-\d{4}-\d{2}\.txt$/);download event, not the click. The event waits up to the test timeout, so a slow file needs no extra code.Generated file
The file is built in the browser when you click the button.
Server report
The server builds this report when you ask for it, which takes a moment. Its name includes the current month.
Download monthly reportRelated exercises
- FormsIntermediateFile UploadUpload files without the operating system dialog: plain inputs, checked files, hidden inputs, drop zones and a real upload.
- Mini ShopAdvancedUI + API TogetherCombine the API and the browser for tests that are fast, independent and thorough.
- Network & APIAdvancedAPI TestingTest the practice API directly with the request fixture, without a browser.
Read the guide: File upload and download in Playwright