How to Verify Downloaded Files in Playwright: Complete Practical Guide




Have you ever automated a Download button and received a successful test result, only to discover that the downloaded file was empty or contained incorrect information?

This is a common problem in automation testing.

A download action can complete successfully even when the application generates the wrong file.

For example, imagine an employee downloading a salary statement.

The application may download a PDF successfully, but the document could contain another employee's details, an incorrect salary amount or incomplete information.

Simply checking whether the file downloaded will not detect these problems.

You must verify the downloaded file.

Playwright provides built-in download handling, while Node.js provides file-system operations to inspect saved files. Additional libraries can help validate PDF, Excel, CSV and ZIP documents.

In this guide, you will learn how to verify downloaded files in Playwright using practical TypeScript examples.

What Does File Verification Mean in Playwright?

File verification in Playwright means checking whether a downloaded file meets the expected requirements.

It includes checking:

  • File download completion.

  • File name.

  • File extension.

  • File existence.

  • File size.

  • File format.

  • File content.

  • Expected records and values.

  • File integrity.

  • Access permissions.

For example, if a user downloads a customer report, your automation should confirm that the report contains the correct customer information.

A reliable test should answer three questions:

  1. Did the application download the file?

  2. Is the downloaded file valid?

  3. Does the downloaded file contain the expected information?

All three are important.

Understanding the Playwright Download Object

Playwright provides a Download object when a page starts downloading a file.

The Download object provides information about the downloaded file and methods to manage it.

Important methods:

Method

What it does

suggestedFilename()

Gets the suggested filename

saveAs()

Saves a copy to a specified location

failure()

Checks for download failure

path()

Gets the temporary download path

createReadStream()

Creates a readable stream

url()

Gets the download URL

delete()

Deletes the downloaded file

One important detail is that the download event is emitted when the download starts. The file becomes available after the download completes.

Playwright's saveAs() method waits for the download to finish before completing the save operation.

Step 1: Capture the Downloaded File

First, open the application and wait for the download event.

import { test, expect } from '@playwright/test';


test('verify downloaded file', async ({ page }) => {


  await page.goto('https://example.com/reports');


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


  await page.getByRole('button', {

    name: 'Download Report'

  }).click();


  const download = await downloadPromise;


  console.log(download.suggestedFilename());


});

This captures the downloaded file.

The suggestedFilename() method returns the filename suggested by the browser.

Step 2: Verify the Expected Filename

Suppose the application should generate:

employee-report.pdf

You can verify the filename using:

expect(download.suggestedFilename()).toBe(

  'employee-report.pdf'

);

This is useful when applications generate files with predefined names.

For dynamic filenames:

expect(download.suggestedFilename()).toMatch(

  /^employee-report-\d{4}-\d{2}-\d{2}\.pdf$/

);

This verifies a filename containing a date.

If filenames are generated dynamically, make sure your regular expression matches the application's actual naming convention.

Step 3: Save the Downloaded File

To inspect the downloaded file, save it to a known location.

import path from 'path';


const filePath = path.join(

  process.cwd(),

  'test-results',

  download.suggestedFilename()

);


await download.saveAs(filePath);

This saves the file inside the test-results folder.

Use a predictable folder structure so that your automation framework can locate downloaded files easily.

For parallel tests, use unique filenames or separate directories to prevent one test from overwriting another test's file.

Step 4: Check Whether the File Exists

Now verify that the file was saved successfully.

import fs from 'fs';


expect(fs.existsSync(filePath)).toBe(true);

The existsSync() method checks whether the specified file exists.

If it returns true, the file is present.

If it returns false, the file was not found at the expected location.

This check is useful, but it does not confirm whether the downloaded file is valid.

Step 5: Check the File Size

The next step is to check whether the downloaded file contains data.

const stats = fs.statSync(filePath);


expect(stats.size).toBeGreaterThan(0);

This checks whether the file size is greater than zero bytes.

For an application that generates reports, an empty file may indicate a problem with the export process.

You can also validate a minimum expected size when the application has a predictable output requirement.

However, do not use an arbitrary minimum size without understanding the application.

A valid small CSV file may contain only a few bytes.

Step 6: Verify the File Extension

Different applications generate different file types.

For example:

  • PDF for invoices.

  • CSV for exported records.

  • XLSX for spreadsheets.

  • ZIP for compressed downloads.

  • JSON for structured data.

Use Node.js to check the extension.

import path from 'path';


const extension = path.extname(filePath);


expect(extension).toBe('.pdf');

This confirms that the saved filename has the expected extension.

But remember:

A file extension does not prove the actual file format.

A file can be named report.pdf while containing HTML error content.

For stronger verification, inspect the file's contents or format signature.

Step 7: Verify CSV File Contents

CSV files are common in reporting applications.

Suppose an application allows users to download employee records.

The downloaded CSV should contain:

Employee Name,Department,Salary

John,Testing,50000

David,Development,60000

You can read the downloaded CSV using Node.js.

const csvContent = fs.readFileSync(

  filePath,

  'utf-8'

);


expect(csvContent).toContain('Employee Name');


expect(csvContent).toContain('Department');


expect(csvContent).toContain('Salary');

This checks whether the expected column names exist.

For more advanced validation, parse the CSV into rows and compare actual values.

You can use a CSV parsing library for this.

import { parse } from 'csv-parse/sync';


const csvContent = fs.readFileSync(filePath, 'utf-8');


const records = parse(csvContent, {

  columns: true,

  skip_empty_lines: true

});


expect(records.length).toBeGreaterThan(0);


expect(records[0].Department).toBe('Testing');

This verifies actual structured data rather than simply searching for text.

It is especially useful for:

  • Employee exports.

  • Customer reports.

  • Sales reports.

  • Transaction histories.

  • Inventory data.

Step 8: Verify PDF File Contents

PDF files are commonly used for invoices, receipts, account statements and reports.

Checking that a PDF exists is not enough.

You should verify whether the PDF contains the expected information.

For example, an invoice should contain:

  • Invoice number.

  • Customer name.

  • Invoice date.

  • Product details.

  • Total amount.

You can use a PDF parsing library to extract text.

One option is pdf-parse.

Install the package:

npm install pdf-parse

Then use the library to extract text from the PDF.

The exact API can vary by package version, so keep the implementation aligned with the installed version.

A typical validation flow looks like this:

const pdfText = await extractPdfText(filePath);


expect(pdfText).toContain('Invoice Number');


expect(pdfText).toContain('Customer Name');


expect(pdfText).toContain('Total Amount');

Here, extractPdfText() represents your PDF extraction helper.

The extracted text is then checked using Playwright assertions.

For production testing, also consider PDFs with scanned images, tables, multiple pages and different text layouts.

A scanned PDF may require OCR rather than ordinary text extraction.

Step 9: Verify Excel Files

Many business applications generate Excel reports.

For example:

  • Sales reports.

  • Employee information.

  • Financial statements.

  • Inventory reports.

  • Customer records.

You can use the xlsx package to read Excel files.

Install:

npm install xlsx

Example:

import * as XLSX from 'xlsx';


const workbook = XLSX.readFile(filePath);


const sheetName = workbook.SheetNames[0];


const worksheet = workbook.Sheets[sheetName];


const data = XLSX.utils.sheet_to_json(worksheet);


expect(data.length).toBeGreaterThan(0);

This reads the downloaded Excel workbook and converts the first worksheet into JavaScript objects.

You can then validate expected values.

For example:

expect(data[0]).toHaveProperty('Employee Name');

For more complete verification, check:

  • Expected worksheet names.

  • Column headers.

  • Number of records.

  • Important cell values.

  • Empty rows.

  • Duplicate records.

  • Date and number formats.

Step 10: Verify ZIP Downloads

Some applications allow users to download multiple documents as a ZIP archive.

A ZIP file should contain the expected documents.

You can use an archive-reading library to inspect its contents.

For example, install:

npm install adm-zip

Then:

import AdmZip from 'adm-zip';


const zip = new AdmZip(filePath);


const entries = zip.getEntries();


const fileNames = entries.map(entry => entry.entryName);


expect(fileNames).toContain('invoice.pdf');


expect(fileNames).toContain('report.csv');

This checks whether the ZIP archive contains the expected files.

You can also inspect the extracted documents individually.

For important business workflows, check that the archive is readable and that its required files are present.

Step 11: Validate File Contents Against Expected Test Data

One of the strongest verification strategies is comparing downloaded information against known test data.

Imagine your application has a customer named John.

The expected report contains:

Customer: John

Order ID: ORD1001

Amount: 2500

Status: Completed

Your test should verify that the downloaded report contains the correct values.

Do not just check whether the word John appears.

Check whether the correct order ID, amount and status appear together.

This prevents false positives.

For structured files, parse the contents and compare the relevant fields.

For example:

expect(report.customer).toBe('John');


expect(report.orderId).toBe('ORD1001');


expect(report.amount).toBe(2500);


expect(report.status).toBe('Completed');

This approach connects file verification with actual business requirements.

Step 12: Create a Reusable File Verification Helper

A large automation project may contain dozens of download scenarios.

Instead of repeating file verification logic, create reusable helpers.

For example:

import fs from 'fs';


import path from 'path';


import { expect, Download } from '@playwright/test';


export async function verifyDownloadedFile(

  download: Download,

  expectedName: string,

  outputDirectory: string

) {


  const actualName = download.suggestedFilename();


  expect(actualName).toBe(expectedName);


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


  const filePath = path.join(

    outputDirectory,

    actualName

  );


  await download.saveAs(filePath);


  expect(fs.existsSync(filePath)).toBe(true);


  const stats = fs.statSync(filePath);


  expect(stats.size).toBeGreaterThan(0);


  return filePath;


}

Now your test files can reuse the same verification function.

This improves readability and makes future maintenance easier.

For a production framework, also consider safe filename handling, unique paths and cleanup.

Step 13: Verify Multiple Downloaded Files

Sometimes one user action downloads multiple files.

For example, an application may allow users to export several reports.

You should verify every expected download.

One approach is to capture each download event separately.

const firstDownloadPromise =

  page.waitForEvent('download');


await page.getByRole('button', {

  name: 'Download First Report'

}).click();


const firstDownload = await firstDownloadPromise;


const secondDownloadPromise =

  page.waitForEvent('download');


await page.getByRole('button', {

  name: 'Download Second Report'

}).click();


const secondDownload = await secondDownloadPromise;


expect(firstDownload.suggestedFilename())

  .toBe('first-report.pdf');


expect(secondDownload.suggestedFilename())

  .toBe('second-report.pdf');

For multiple downloads triggered by one action, you can also listen for multiple download events and verify the expected number.

The test should identify each file using its expected name or another reliable property.

Step 14: Clean Up Downloaded Files

Automation tests should not leave unnecessary files behind.

Downloaded files can increase storage usage and cause confusion during later test executions.

Use a cleanup strategy.

For example:

import fs from 'fs';


if (fs.existsSync(filePath)) {


  fs.unlinkSync(filePath);


}

For large projects, create a dedicated download directory and remove its test files after validation.

Make sure cleanup runs even when an assertion fails.

Playwright fixtures and test lifecycle hooks can help manage this process.

Common Problems When Verifying Downloaded Files

Problem 1: Downloaded file does not exist

Possible reasons:

  • Incorrect download path.

  • Download did not complete.

  • Browser context closed too early.

  • Incorrect file-saving logic.

Solution: Wait for the download event and use saveAs() before closing the browser context.

Problem 2: File is empty

Possible reasons:

  • Server-side export failure.

  • Missing test data.

  • Incomplete file generation.

  • Incorrect export request.

Solution: Validate the file size and inspect the application response.

Problem 3: PDF file contains incorrect information

Possible reasons:

  • Incorrect customer selection.

  • Wrong report filters.

  • Backend data problems.

  • Application generating an outdated document.

Solution: Extract PDF text and compare important values against expected test data.

Problem 4: Downloaded file has an incorrect extension

Possible reasons:

  • Incorrect server response headers.

  • Incorrect application file-generation logic.

  • Incorrect download naming configuration.

Solution: Validate both the filename and actual file format.

Problem 5: Tests pass locally but fail in CI/CD

Possible reasons:

  • Different file paths.

  • Missing dependencies.

  • Incorrect permissions.

  • Different operating systems.

  • Parallel tests overwriting files.

  • Browser context closing before file persistence.

Solution: Use controlled paths, install required dependencies, isolate downloads and save files before context cleanup.

Best Practices for Downloaded File Verification

  1. Always capture the download event.

  2. Save files to a controlled directory.

  3. Validate filenames and extensions.

  4. Check file existence.

  5. Check file size.

  6. Verify actual file format.

  7. Parse file contents.

  8. Compare downloaded data against expected values.

  9. Use unique paths for parallel tests.

  10. Handle temporary storage correctly.

  11. Clean up downloaded files.

  12. Test both valid and invalid download scenarios.

  13. Keep reusable verification helpers.

  14. Include meaningful error messages.

  15. Test download workflows in CI/CD.

Frequently Asked Questions

1. How do I verify a downloaded file in Playwright?

Capture the download event, save the file using saveAs(), and validate its filename, existence, size, format and contents.

2. How do I check whether a downloaded file exists?

Use Node.js fs.existsSync() with the saved file path.

3. How do I verify a downloaded PDF in Playwright?

Save the PDF and use a PDF parsing library to extract text. Then compare the extracted text with expected invoice, customer or report information.

4. Can Playwright verify Excel downloads?

Yes. Use a spreadsheet library such as xlsx to read the downloaded workbook and validate worksheets, rows, columns and values.

5. How do I verify CSV downloads?

Read the CSV file or parse it using a CSV library. Check headers, rows and expected values.

6. How do I verify ZIP downloads?

Use a ZIP-reading library to inspect the archive and confirm that the expected files are present.

7. Why should I check file size?

A file may exist without containing useful data. File-size validation helps identify empty or incomplete downloads.

8. Can Playwright verify file contents?

Yes. Playwright handles the browser download, while Node.js and format-specific libraries help read and validate the saved file.

9. How do I verify multiple downloaded files?

Capture each download event, save the files separately and validate the expected filenames and contents.

10. How do I prevent downloaded files from affecting other tests?

Use unique filenames, isolated download folders and cleanup logic. This is particularly important when tests run in parallel.

Conclusion

Verifying downloaded files is more than checking whether a browser completed a download.

Automation testers must confirm that the correct file was generated, saved and delivered with the expected information.

Playwright handles download events through its Download object, while Node.js and additional libraries help inspect different file formats.

By combining filename validation, file-size checks, format verification and content comparison, you can create reliable download automation tests.

The most important lesson is simple:

A downloaded file should not be considered correct until its actual contents have been verified.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide