Skip to contentPlayForge

How do I assert the page URL in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

Use await expect(page).toHaveURL(...), which retries until the page's URL matches a string, a regular expression or a predicate. Because it retries, it also covers the moment just after a redirect, when the URL has not changed yet.

This answer is one piece of Chapter 11: Assertions.

  • Web-First Assertions Cookbook
  • Retry & Polling Patterns
  • Visual Regression Testing
  • Making a Failure Explain Itself

Checking page.url() with a plain expect(...).toBe(...) reads the URL once. If the page is still redirecting, the read happens too early and the test fails for a timing reason, not a real one. toHaveURL() is a web-first assertion: it keeps checking until the URL matches or the assertion timeout runs out.

It takes three kinds of argument:

  • A string must match the whole URL, query string included. When baseURL is set in the config, a relative string such as '/login.html?...' is merged with it first, so you do not repeat the domain.
  • A regular expression matches part of the URL. /\/login\.html/ passes whatever the query string says.
  • A predicate receives a URL object, which is the cleanest way to check one query parameter.

In the example, opening orders.html signed out sends the browser to the login page. The three assertions check the same redirect three ways. The last one confirms that next=orders.html survived, which is what brings the user back after they sign in.

url.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('a signed-out visit to orders is sent to the login page', async ({ page }) => { await page.goto('/orders.html?mock=static&seed=42'); await expect(page).toHaveURL(/\/login\.html/); await expect(page).toHaveURL('/login.html?seed=42&mock=static&next=orders.html'); await expect(page).toHaveURL((url) => url.searchParams.get('next') === 'orders.html'); });
Output
1 passed (1.4s)
Test yourself
The page is at https://practice.learnplayforge.com/login.html?seed=42&mock=static&next=orders.html and baseURL is the practice app. Which assertion passes?

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.