← Back to Playwright Mastery
Advanced22 min read

Advanced Topics

Service workers, authentication patterns, PDF, accessibility, and clock control.

Service Workers

Playwright can register service workers in test context for PWA scenarios. route may intercept SW-controlled fetch depending on scope.

Test offline cache behavior with context.setOffline after SW precache.

  • Clear service workers between tests to avoid cache bleed
  • Wait for navigator.serviceWorker.ready before offline assertions
  • Mock SW at network layer if full SW setup heavy

Authentication Flows

Beyond storageState, test OAuth by mocking token endpoint or using test IdP. Multi-factor flows may need TOTP seed in vault.

HTTP credentials for basic auth: use: { httpCredentials: { username, password } }.

await page.context().storageState({ path: "playwright/.auth/user.json" });

PDF Generation

page.pdf() generates PDF in headless Chromium—test report export features. Assert file size or text extraction with pdf-parse library outside browser.

Not supported in Firefox/WebKit projects.

await page.goto("/invoice/123");
await page.pdf({ path: "invoice.pdf", format: "A4" });

Accessibility Testing

Integrate @axe-core/playwright for automated a11y scans. expect(page).toPassAxe() or analyze per route in E2E suite.

Combine with getByRole-first locators—dual benefit resilient tests and a11y.

import AxeBuilder from "@axe-core/playwright";

const results = await new AxeBuilder({ page }).analyze();
expect(results.violations).toEqual([]);

Clock and Permissions

page.clock.install() mocks Date and timers for time-dependent UI—subscription expiry, countdown. grantPermissions for notifications, geolocation.

setGeolocation tests map features without real GPS.

await page.clock.install({ time: new Date("2024-06-01") });
await context.grantPermissions(["geolocation"]);

Get In Touch


Ready to discuss your next project? Drop me a message.