Playwright + TS · Lesson 23 of 36
Module 23: Browser Events & File Handling
Try it yourself
Implement validateDownloadedFileSize:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
In this lesson
A test can pass its UI assertions while the browser console throws critical JavaScript uncaught exceptions:
test("page should load with zero console errors", async ({ page }) => {
const errors: string[] = [];
page.on("pageerror", (exception) => {
errors.push(exception.message);
});
await page.goto("https://targetqa.com");
expect(errors).toHaveLength(0);
});If a file input is hidden behind a stylized button:
// Start waiting for file chooser before clicking the trigger:
const fileChooserPromise = page.waitForEvent("filechooser");
await page.getByRole("button", { name: "Select Document" }).click();
const fileChooser = await fileChooserPromise;
// Attach file:
await fileChooser.setFiles("fixtures/sample-contract.pdf");import fs from "fs";
test("download invoice pdf and verify file exists", async ({ page }) => {
const downloadPromise = page.waitForEvent("download");
await page.getByRole("button", { name: "Download PDF" }).click();
const download = await downloadPromise;
const savePath = `test-results/${download.suggestedFilename()}`;
await download.saveAs(savePath);
// Assert file exists on disk and is non-empty:
expect(fs.existsSync(savePath)).toBeTruthy();
expect(fs.statSync(savePath).size).toBeGreaterThan(100);
});A comprehensive automated test does more than click buttons; it also verifies that no console errors occurred and validates downloaded files. In this lesson, we will learn how to listen to browser events, intercept console logs, handle custom file uploaders, and verify downloaded documents. Let's get started!
Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
Playwright stores downloads in a temporary isolated cache directory. If you don't call saveAs(), the file is automatically deleted when the BrowserContext closes.
Yes! You can use page.on('websocket', ws => { ws.on('framereceived', ...); }) to inspect real-time communications.
Finished reading?
Review the worked example in the editor, then mark the lesson complete.