How do I assert the page title in Playwright?
Written by Jatin Thacker, Automation Architect · Updated
await expect(page).toHaveTitle(...) with the exact title as a string, or a regular expression for part of it. It retries, so it waits for the title of a page that is still loading.This answer is one piece of Chapter 11: Assertions.
- Web-First Assertions Cookbook
- Retry & Polling Patterns
- Visual Regression Testing
- Making a Failure Explain Itself
The title is the text in the browser tab, set by the page's <title> element. It is a quick check that a navigation landed on the right page.
Two patterns go wrong. expect(page.title()).toBe('...') compares a Promise with a string, because page.title() is async. expect(await page.title()).toBe('...') works, but reads the title once, so straight after a click it may still hold the old page's title. toHaveTitle() avoids both: it retries until the title matches or the assertion timeout runs out.
In the example:
- On the catalogue, the test checks the exact title,
Catalog - Meridian Ops. - It then clicks the Orders link in the main navigation and checks
/^Orders/, a regular expression that only cares how the title starts.
Use a string when the whole title matters. Use a regular expression when part of it changes, such as a site name or a count.
import { test, expect } from '@playwright/test';
test('each page sets its own title', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42&autologin=1');
await expect(page).toHaveTitle('Catalog - Meridian Ops');
await page.getByRole('link', { name: 'Orders', exact: true }).click();
await expect(page).toHaveTitle(/^Orders/);
});1 passed (1.5s)
Orders - Meridian Ops. Which assertion passes?Practised in the full course: the drill A string is not a Promise.
See the chapterRelated questions
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