Web Assertions
Web assertions target locators and page-level state. This lesson focuses on page-wide checks beyond individual elements.
Page-Level Matchers
expect(page).toHaveURL() accepts strings, regex, or functions — ideal after navigation or redirects.
expect(page).toHaveTitle() verifies document title for SEO-sensitive flows or tab management.
await page.getByRole('link', { name: 'Settings' }).click();
await expect(page).toHaveURL(/\/settings/);
await expect(page).toHaveTitle(/Settings - MyApp/);
URL assertions retry through SPA client-side routing delays.
Common Page Matchers
await expect(page).toHaveURL(url | RegExp | fn)
await expect(page).toHaveTitle(title | RegExp)
await expect(page).toHaveScreenshot(name?, options?)
- URL can be relative when baseURL is set.
- Screenshot assertions compare against golden files in snapshots folder.
- Use
{ maxDiffPixels } for tolerating anti-aliasing differences. - Page errors can be listened via
page.on('pageerror').
Page Assertion Reference
Verify navigation and page state.
| Matcher | Use Case |
toHaveURL() | After login redirect, route change |
toHaveTitle() | Document title verification |
toHaveScreenshot() | Full page visual regression |
not.toHaveURL() | Confirm left sensitive page |
| Regex URL | toHaveURL(/\/checkout/step-2/) |
| Function URL | Dynamic query param checks |
Screenshot Assertion Options
await expect(page).toHaveScreenshot('homepage.png', {
fullPage: true,
maxDiffPixelRatio: 0.01,
animations: 'disabled',
});
URL Assertions with Regular Expressions
await expect(page).toHaveURL(/\/checkout\/step-2/) handles dynamic query params better than exact string equality when IDs vary.
Common Mistakes
- String URL match when query param order varies — use regex.
- Screenshot tests on dynamic ads or timestamps without masking.
- Checking title before client-side router updates document.title.
- Not updating snapshots intentionally after UI refresh.
Key Takeaways
- Page matchers retry like locator matchers.
- URL regex handles SPAs and query strings flexibly.
- Screenshot assertions belong in visual testing strategy.
- Combine page and locator assertions for complete checks.
Pro Tip
Use await page.waitForURL() for actions where navigation is the primary wait condition, then assert with toHaveURL for clarity in reports.