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 element” 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.

The example below loads the downloaded file content into memory and asserts that the text Q2 report is contained somewhere 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");

You can modify the above code snippet and assert against many other things related to downloading and downloaded files. See the Playwright documentation for more ideas on what download actions you can create in Autify Nexus’s Playwright steps.