23. Listening to Browser Events & Managing File Workflows

1. Intercepting Console Errors

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);
});

---

2. Handling File Chooser & Custom Upload Buttons

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");

---

3. File Downloads & Verification

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);
});

Task

  • Implement validateDownloadedFileSize:
  • 1. Accept sizeBytes and optional minBytes (default 1024).
  • 2. Return true if sizeBytes is at least minBytes.
πŸ’‘Common doubts
Did you like the problem?
Lesson 23 of 36
TypeScript
Loading code editor…
Next