QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Interaction: actions, tabs, frames, files, dialogs

File uploads and downloads

Files are uploaded with setInputFiles on a file input without the OS dialog, and a dynamic file picker is caught with the filechooser event. Downloads are caught with the download event, with the promise created before the click. The temporary file disappears with the context, so it is saved with saveAs. Check the content, not just the name: header, row count, totals.

Playwright · Interaction

The CSV export "worked", yet the file has only a header. Why did the test not notice?

The "Export" button is clicked, the browser hands over a file with the right name transactions.csv, and the test is green. Then accounting opens the file and sees only the header row: a query failure made the report empty. The test checked the name and left the content unchecked. Files in a browser are a separate class of actions: the system file-picker dialog is not available to automation, and downloads land in a temporary folder that the browser cleans itself. Playwright avoids both problems by working with browser events instead of OS windows. Below: how upload and download are built and what to check in them.

Upload: how it works. The main method is setInputFiles on an input type="file" element. It works even if the input is hidden behind a nice button (getByLabel finds it by its label), and it does not open a real OS dialog: Playwright puts the files straight into the element, as the browser would after a selection. You can pass a path, an array of paths for multiple, or an object { name, mimeType, buffer }: the file is created right in the test with no binaries in the repository, which is handy for edge cases (a huge file, a forbidden extension, empty content). An empty array clears the selection. Relative paths are resolved from the current working directory (usually the project root), not from the test file.

await page.getByLabel('Document').setInputFiles('fixtures/passport.pdf');
await page.getByLabel('Documents').setInputFiles(['fixtures/a.pdf', 'fixtures/b.pdf']);

// a file generated in the test: no binary in the repository
await page.getByLabel('Statement').setInputFiles({
  name: 'report.csv',
  mimeType: 'text/csv',
  buffer: Buffer.from('id,amount'),
});

// negative test: a file above the limit of the form
await page.getByLabel('Document').setInputFiles({
  name: 'big.pdf',
  mimeType: 'application/pdf',
  buffer: Buffer.alloc(11 * 1024 * 1024),
});
await expect(page.getByRole('alert')).toContainText('10 MB');

await page.getByLabel('Document').setInputFiles([]); // clear the selection

If there is no input in the DOM and a button opens the dialog dynamically (for example via input.click() in JavaScript), you catch the filechooser event. It is the same scheme as with a new tab: listener before the click, await after. setInputFiles also works for directories (webkitdirectory). After an upload you check not only that "the file name appeared" but also the backend's reaction: processing status, preview, validation error message.

// there is no input in the DOM: a button opens the system dialog
const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Upload photo' }).click();
const chooser = await chooserPromise;
expect(chooser.isMultiple()).toBe(false);
await chooser.setFiles('fixtures/photo.png');

Download: how it works. A download starts with a click, so the download event is listened for in advance, by the same "promise before the click" rule. The Download object gives suggestedFilename(), url(), failure() (an error text or null), path() and saveAs(). The browser downloads the file into a temporary folder, and when the context closes, the file is deleted. So to keep it as an artifact you need saveAs, and the best place is testInfo.outputPath: isolated between tests and workers, and the folder is cleaned up together with the results.

The life of a downloaded file

1 waitForEvent('download') 2 click "Export" 3 file in a temporary folder saveAs into thetest's outputPath:read the content,check it context closed:the temporary fileis deleted, thecontent is gone
Figure 1. The temporary file lives only while the context lives. Anything you need to check or keep is done before it closes.

Example: from checking the name to checking the content. The initial version, which "passed" an empty report:

// before: the name is checked, the content is not
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: 'Export CSV' }).click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toBe('transactions.csv'); // an empty file passes too

Its weakness is that the names match even for an empty file. The fixed version saves the file to outputPath, reads it and checks the header and the row count:

import { readFile } from 'node:fs/promises';

test('export of transactions', async ({ page }, testInfo) => {
  await page.goto('/transactions');

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

  expect(download.suggestedFilename()).toBe('transactions.csv');
  expect(await download.failure()).toBeNull();

  const filePath = testInfo.outputPath(download.suggestedFilename());
  await download.saveAs(filePath);
  const rows = (await readFile(filePath, 'utf-8')).trim().split(/\r?\n/);
  expect(rows[0]).toBe('id,date,amount,currency');
  expect(rows.length - 1).toBe(25);
});

What we check in a downloaded file

Typical

Only suggestedFilename()

An empty file, a truncated report or a file in the wrong encoding has the right name. The test is green, the defect is in production.

Better

Name, failure, content

failure() is null, and the CSV has the right header, row count and totals. The test catches exactly what would break a user.

Figure 2. The file name is the minimum. The real value is in the content.

What to check in the content. The CSV header, the row count, totals, encoding (BOM, delimiter, date format). For CSV readFile and a split into lines is enough; for XLSX or PDF you add libraries (exceljs, pdf-parse), and for a quick check of the file type its signature is enough. A big file is read as a stream:

const download = await downloadPromise;
const stream = await download.createReadStream(); // alternative to saveAs
const chunks: Buffer[] = [];
for await (const chunk of stream) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);

expect(body.subarray(0, 5).toString()).toBe('%PDF-'); // the file is really a PDF
expect(body.length).toBeGreaterThan(1000);

In fintech such checks are part of the requirements: statements and reports for accounting must match what the user sees, down to the cent.

Limits and alternatives. Playwright hands you the downloaded file but does not open it in an app: for a PDF it gives bytes, not a rendered page, so "does the PDF look right" cannot be verified this way. In Selenium there is no download event: the file appears in the browser's folder and the test waits for it on disk by polling, which is slower and more fragile. In Cypress a download also lands in a folder (downloadsFolder) and is read with cy.readFile. The key advantage of Playwright is the download event with a ready object and isolation between workers.

Common mistakes.

  • Clicking "Export" without a prior waitForEvent('download'): the event is missed and no download is received.
  • Checking only suggestedFilename() without the content: an empty file with the right name passes.
  • Saving to an arbitrary folder (./downloads): parallel workers overwrite each other's files and CI is left with junk.
  • Binary fixtures in the repository for every edge case instead of generating them through buffer.
  • Finding the input by the button's CSS class instead of getByLabel: breaks when the design changes.

Check yourself

The test from the first example passes an export that contains only the header row. Why, and which lines of the fixed version catch such a file?

Answer

The first example has only suggestedFilename(): the name is right even for an empty file. In the fixed version expect(rows.length - 1).toBe(25) counts the data rows: an empty report gives 0 and the test fails. expect(rows[0]) additionally checks the header itself.

At the end of a test the downloaded file is needed as an artifact, but it turns out to be gone. Why, and what do you do?

Answer

A downloaded file lives in a temporary folder and is deleted when the context closes. Save it inside the test with download.saveAs(testInfo.outputPath(…)) while the context is alive. That folder is isolated between workers, so parallel tests do not overwrite each other.

The form has no input type="file" in the DOM, and the "Upload photo" button opens the system dialog. Which method do you use, and in what order?

Answer

The filechooser event: create page.waitForEvent('filechooser') before the click, click, await the promise and call chooser.setFiles(…). The order is the same as for popup and download: listener before the action.

In an interview. Junior: For upload I use setInputFiles, and for download I create the waitForEvent('download') promise before the click and check the file. Middle/Senior: I do upload through setInputFiles, often with a buffer to generate edge-case files in the test, and if the dialog opens dynamically I catch filechooser. I save a download with saveAs into testInfo.outputPath, because the temporary file disappears with the context and a shared folder breaks on parallel workers. I check not only the name but also the content: header, row count, totals and encoding.

More articles in this chapter