Testing File Download with Playwright

Testing file downloads in web applications can seem tricky, especially when aiming for reliable automation. Thankfully, Playwright simplifies the process significantly. Since Playwright testing is done against real browser(s), you can test and verify downloads very much like you would do it manually. You can do things like check the name of the file that’s prompted to be downloaded, check its file size and much more. Let’s look at how we can achieve this.

Testing a File Download

Consider an example: you have a button on your web page labeled “Download Report,” and clicking it triggers a file download. Here’s a Playwright test that you may right to test that:

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

test('should download a report file', async ({ page }) => {
  // Navigate to your web page
  await page.goto('https://example.com/reports');

  // Set up to wait for the download event
  const [download] = await Promise.all([
    page.waitForEvent('download'),
    page.click('text=Download Report'), // Trigger the download
  ]);

  // Verify filename (optional)
  expect(download.suggestedFilename()).toMatch(/report_\d{4}-\d{2}-\d{2}\.csv/);

  // Save the file to a known location
  const downloadPath = path.join(__dirname, 'downloads', download.suggestedFilename());
  await download.saveAs(downloadPath);

  // Verify the file exists
  expect(fs.existsSync(downloadPath)).toBeTruthy();

  // Optionally, verify file contents
  const fileContent = fs.readFileSync(downloadPath, 'utf8');
  expect(fileContent).toContain('Date,Amount,Description');
});

Code Breakdown

Using waitForEvent(‘download’)

Playwright’s waitForEvent('download') listens explicitly for the download triggered by your action. Wrapping it in Promise.all() ensures that Playwright captures the event triggered by your click.

Saving the Downloaded File

Playwright downloads files into a temporary location by default. Use download.saveAs() to move it to a known location for easier validation.

Checking Filename, Type, Contents

The browser APIs exposed by Playwright allows you to check the filename that’s suggested by the download dialog using the suggestedFilename() function. Depending on the filetype and contents, you may also be able to open the file and inspect its contents to ensure accuracy.

Wrapping Up


Testing file downloads doesn’t have to be complicated. Playwright simplifies the process, providing powerful tools for automating and verifying this common functionality. With these strategies, you’ll confidently ensure your app’s file downloads are working smoothly.

Leave a Comment

Your email address will not be published. Required fields are marked *