</>

Technology

Playwright

Difficulty

Intermediate

Interview Question

How do you handle file downloads in Playwright?

Answer

File Downloads in Playwright

Basic Download

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

test('download invoice PDF', async ({ page }) => {
  await page.goto('/invoices');

  // Start waiting for download BEFORE the action that triggers it
  const downloadPromise = page.waitForEvent('download');

  // Click the download button
  await page.getByRole('button', { name: 'Download Invoice' }).click();

  // Wait for download to complete
  const download = await downloadPromise;

  // Get the filename
  console.log(download.suggestedFilename()); // "invoice-2024-01.pdf"

  // Save to a custom path
  const savePath = path.join('test-downloads', download.suggestedFilename());
  await download.saveAs(savePath);

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

Download from Link Click

TypeScript
test('download CSV report', async ({ page }) => {
  await page.goto('/reports');

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

  await download.saveAs(`downloads/${download.suggestedFilename()}`);

  // Verify file size is non-zero
  const stats = fs.statSync(`downloads/${download.suggestedFilename()}`);
  expect(stats.size).toBeGreaterThan(0);
});

Read Downloaded File Content

TypeScript
test('verify CSV content', async ({ page }) => {
  await page.goto('/data-export');

  const downloadPromise = page.waitForEvent('download');
  await page.getByRole('button', { name: 'Export' }).click();
  const download = await downloadPromise;

  // Get the downloaded file path (temp path)
  const filePath = await download.path();

  // Read and verify content
  const content = fs.readFileSync(filePath!, 'utf-8');
  expect(content).toContain('Name,Email,Phone');
  expect(content).toContain('John Doe');
});

Configure Download Directory

TypeScript
// playwright.config.ts
export default defineConfig({
  use: {
    acceptDownloads: true, // Must be true (default)
  },
});

Download Failure Check

TypeScript
test('handle download failure', async ({ page }) => {
  const downloadPromise = page.waitForEvent('download');
  await page.getByRole('button', { name: 'Download' }).click();
  const download = await downloadPromise;

  // Check for failure
  const failure = await download.failure();
  if (failure) {
    console.error('Download failed:', failure);
  } else {
    console.log('Download succeeded:', download.suggestedFilename());
  }
});

Follow AutomateQA

Related Topics