Testing downloads

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$/);
A slow server delays the 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.

Static file

A plain link to a file served by the app.

Download sample report

Server report

The server builds this report when you ask for it, which takes a moment. Its name includes the current month.

Download monthly report