A green click assertion does not prove that a downloaded file is correct. The browser may start a download while the server returns the wrong report, an empty archive, stale data, or a hostile filename. Reliable download testing therefore needs two independent results: Playwright must capture the expected download, and the test must validate the saved artifact.

1. Attach the listener before the action

Playwright emits the page download event when a download starts. The listener must exist before the click that triggers it; otherwise a fast response can be missed. Use an event promise and the action together:

const [download] = await Promise.all([
  page.waitForEvent('download'),
  page.getByRole('button', { name: 'Export report' }).click(),
]);

This pattern waits for an observable browser event rather than an arbitrary timeout. Do not replace it with waitForTimeout(5000): a fixed pause is both slower on a fast system and unreliable on a slow one.

Capturing the event is only the start. A Download object identifies the transfer, but it does not prove that the artifact contains the expected business data.

2. Check transfer failure correctly

Playwright's download.failure() waits for the download to finish and returns either a failure message or null. It is asynchronous and does not return an Error object.

const failure = await download.failure();
expect(failure).toBeNull();

There is no download.finished() method in the Playwright Download API. Both failure() and saveAs() wait for the download to complete when necessary. Tests that call an invented completion method may look plausible in review but fail at runtime—exactly why generated test code must be checked against the official API.

3. Treat the suggested filename as untrusted

suggestedFilename() is derived from the download, usually from the server-provided Content-Disposition header or the browser's download logic. It is useful metadata, not a safe destination path. A value can contain path separators, traversal fragments, misleading extensions, or an excessive length.

A safe policy should:

  1. reduce the value to a base name;
  2. replace characters outside a small allowed set;
  3. limit the length;
  4. allow only expected extensions;
  5. choose the destination directory independently.

Playwright Test's testInfo.outputPath() creates a path inside the current test's output directory. That makes parallel tests less likely to overwrite each other's artifacts and keeps the evidence with the test result.

4. A complete TypeScript example

The following test downloads a JSON report, saves it in an isolated folder, and verifies transport, file metadata, structure, and business content without adding a filename-sanitization dependency.

import { test, expect } from '@playwright/test';
import * as path from 'node:path';
import * as fs from 'node:fs/promises';

function safeDownloadName(rawName: string): string {
  const baseName = path.basename(rawName)
    .replace(/[^a-zA-Z0-9._-]/g, '_')
    .slice(0, 120);

  if (!baseName || baseName === '.' || baseName === '..') {
    throw new Error('Download did not provide a usable filename');
  }

  const extension = path.extname(baseName).toLowerCase();
  if (extension !== '.json') {
    throw new Error(`Unexpected download extension: ${extension || '(none)'}`);
  }

  return baseName;
}

test('exports the requested customer report', async ({ page }, testInfo) => {
  await page.goto('/reports/customers');

  const [download] = await Promise.all([
    page.waitForEvent('download'),
    page.getByRole('button', { name: 'Export JSON' }).click(),
  ]);

  expect(await download.failure()).toBeNull();

  const safeName = safeDownloadName(download.suggestedFilename());
  const destination = testInfo.outputPath('downloads', safeName);
  await fs.mkdir(path.dirname(destination), { recursive: true });
  await download.saveAs(destination);

  const stats = await fs.stat(destination);
  expect(stats.isFile()).toBe(true);
  expect(stats.size).toBeGreaterThan(0);
  expect(stats.size).toBeLessThan(10 * 1024 * 1024);

  const raw = await fs.readFile(destination, 'utf8');
  const report: unknown = JSON.parse(raw);

  expect(report).toMatchObject({
    reportType: 'customers',
    requestedBy: 'qa-download-test',
  });

  const customers = (report as { customers?: unknown }).customers;
  expect(Array.isArray(customers)).toBe(true);
  expect(customers).not.toHaveLength(0);
});

The size ceiling stops the test from processing an unexpectedly large artifact after it is saved. It is not a complete resource-control mechanism: production systems should also enforce download-size limits at the application, object store, or gateway.

5. Validate the payload, not only the extension

A non-empty file with a .pdf suffix can still contain HTML from an error page. A .csv can be syntactically readable but contain yesterday's tenant data. Choose checks that match the format and the business risk:

  1. Confirm the file exists and has a plausible size.
  2. Check the allowed extension, but do not treat it as proof of type.
  3. Inspect a content signature where the format has one, such as %PDF- for PDF or PK for ZIP-based formats.
  4. Parse structured formats with a real parser. For CSV, account for quoting, delimiters, encoding, and line endings rather than splitting every line on commas.
  5. Validate a schema or required fields.
  6. Assert values tied to the initiating action: report period, tenant, filters, record count, currency, or correlation ID.
  7. Use a checksum only when the output is deterministic. Timestamps, generated IDs, ZIP metadata, and row ordering can make byte-for-byte hashes unstable even when the result is correct.

If the application exposes response metadata through a separate API or audit event, compare it with the saved artifact. Do not assume a filename or a declared media type proves the actual content.

6. Remote browsers and streams

download.path() waits for completion and returns the temporary path in a local run. According to Playwright's API documentation, it throws when the browser is connected remotely. Tests intended for local and remote execution should prefer saveAs() or createReadStream().

createReadStream() is useful when the artifact should be passed directly to a parser or hashing pipeline. Streaming can also enforce a byte limit while reading. Whatever approach you choose, preserve enough diagnostic evidence—safe filename, expected format, size, and validation result—to explain a failure without logging sensitive file content.

Downloads belong to the browser context and Playwright deletes their temporary files when that context closes. Save any required evidence before teardown.

7. Cross-platform and parallel safety

Do not build paths with string concatenation or hard-coded / and \ separators. Use node:path and a destination produced by testInfo.outputPath().

Isolation matters even when filenames are correct. Two parallel workers can legitimately download report.json at the same time. A shared directory creates races, stale-file false positives, and accidental overwrites. Per-test output paths make ownership explicit and allow the test runner's normal artifact retention policy to clean up evidence.

Also avoid assertions that search a general downloads folder for “the newest file.” The Download object already represents the transfer caused by the tested action.

8. Security cases worth automating

Download features cross a trust boundary, so add negative tests based on the product's threat model:

  1. Reject traversal names, absolute paths, reserved device names, and unexpected double extensions.
  2. Verify authorization: one user must not export another tenant's data.
  3. Confirm secrets, tokens, and hidden columns are absent from the artifact.
  4. Enforce expected size and record-count limits.
  5. For archives, limit entry count, nesting depth, and total uncompressed size before extraction; reject entries that escape the extraction directory.
  6. Store evidence with restricted access and avoid printing full sensitive payloads in CI logs.
  7. Test cancellation and server errors so the UI does not present a failed export as successful.

An antivirus scan may be appropriate for high-risk file types, but it supplements rather than replaces structural and business validation.

9. Common anti-patterns

  1. Clicking first and attaching waitForEvent('download') afterward.
  2. Sleeping for a fixed duration and then searching the filesystem.
  3. Checking only suggestedFilename() or the extension.
  4. Saving server-provided names directly into a shared directory.
  5. Assuming download.path() works with a remote browser.
  6. Parsing CSV with a naive split(',') in production-grade tests.
  7. Retrying a failed download test without recording the original failure.
  8. Verifying the file format but not the tenant, filters, or business values.

10. Release-ready checklist

  1. The listener is registered before the trigger action.
  2. download.failure() is awaited and checked.
  3. The filename is normalized and restricted to expected extensions.
  4. The file is saved inside a per-test output directory.
  5. The test works with local and intended remote-browser modes.
  6. Size, signature, structure, and business data are validated at the appropriate risk level.
  7. Parallel workers cannot share or overwrite artifacts.
  8. Sensitive content is not exposed in logs or unrestricted artifacts.
  9. Archive extraction has explicit safety limits.
  10. Failures preserve concise diagnostic evidence.

Conclusion

Reliable download testing is an evidence chain: the expected action triggers one observable download, the transfer completes without a reported failure, the artifact is stored in an isolated safe path, and independent checks confirm its structure and business meaning. Playwright provides the event and artifact APIs; the QA design supplies the oracle.

Sources

  1. Playwright Downloads guide
  2. Playwright Download API
  3. Playwright TestInfo API
  4. Node.js Path API
  5. Node.js File system promises API