Asserting on downloaded files

Prev Next

Some websites trigger a file download, such as when exporting a report or saving a document. In a test, you might want to check whether the file was downloaded, verify its name, or inspect its contents. This page provides starter code that can be used to set up an assertion against a downloaded file.

How to set it up

Start by identifying the step in your test that triggers the file download, usually a click step that clicks a download link or button.

Before that step, add a Playwright code step to wait for the download to start.

const downloadPromise = page.waitForEvent("download");

Then, after the click step, add another Playwright code step to handle and assert against the downloaded file.

Asserting the file content

The example below loads the downloaded file content into memory and asserts that the string Q2 report is contained within the file.

const download = await downloadPromise;

        const downloadStream = await download.createReadStream();
        const fileContent = await new Promise((resolve) => {
        const chunks: Buffer[] = [];
        downloadStream.on("data", (chunk) => {
        chunks.push(chunk);
        });
        downloadStream.on("end", () => {
        resolve(Buffer.concat(chunks));
        });
        });

        // Example assertion — update this to match your use case
        expect(fileContent.toString("utf-8")).toContain("Q2 report");

Asserting the filename

The example below asserts that the filename includes the string Q2 report.

const download = await downloadPromise;

        // Get the file name
        const fileName = download.suggestedFilename();

        // Example assertion for the file name
        expect(fileName).toContain("Q2 report");

Refer to the Playwright documentation for more ideas about other download actions you can create with Autify Nexus’s Playwright code steps.

Verifying multiple downloads in a single scenario

If you verify file downloads twice or more within a single scenario, subsequent verifications may not work correctly as is. This is because Playwright's page.waitForEvent("download") completes once it detects an event, continuing to reference the information from the first download.

To correctly assert on a newly downloaded file, you must add code to wait for the download event again immediately before the step that triggers the second download (e.g., clicking Download).

Please follow the steps below to make the correction.

  1. Insert a Playwright Code Step immediately before the step that performs the second or subsequent download (e.g., Click element).

  2. Enter the following code to redefine downloadPromise.

// Do not add const
downloadPromise = page.waitForEvent("download");

FAQ

Why does the file name change when downloading a file during replay?

This is due to Playwright's specifications.
If you want to verify the downloaded file name, you can do so by using the suggestedFilename() method mentioned above.