Validate Page Title and URL
In this example, we will learn how to validate a web page’s title and URL using Playwright assertions.
Code Example
// Import Playwright test and expect assertion library
import { test, expect } from '@playwright/test';
// Define a test case with title
test('Validate Page Title and URL', async ({ page }) => {
// Step 1: Navigate to the website
await page.goto('https://vinothqaacademy.com/');
// Step 2: Get the actual page title
const actualTitle = await page.title();
console.log('Page Title:', actualTitle); // For debugging
// Step 3: Validate (assert) the page title
await expect(page).toHaveTitle('Vinoth Tech Solutions – Empowering Tech Careers');
// Negative scenario example (kept commented):
// await expect(page).toHaveTitle('Vinoth Tech Solutions – Empowering Tech Career')
// Step 4: Get the actual page URL
const actualURL = page.url();
console.log('Page URL:', actualURL); // For debugging
// Step 5: Validate (assert) the page URL
await expect(page).toHaveURL('https://vinothqaacademy.com/');
});
Explanation
– import { test, expect } from '@playwright/test'
→ imports Playwright’s built-in test runner and assertion library.
- test('Validate Page Title and URL', async ({ page }) => { ... })
→ defines a test case with a descriptive title.
- page.goto(URL)
→ launches the browser and navigates to the given URL.
- page.title()
→ fetches the actual title of the loaded page.
– expect(page).toHaveTitle(expectedTitle)
→ asserts the title matches exactly.
– page.url()
→ fetches the actual URL of the page.
– expect(page).toHaveURL(expectedURL)
→ asserts the URL is correct.
– Commented negative test shows how an assertion failure would look.
Behind the Scenes
– Playwright automatically opens a new browser context for each test and closes it at the end.
– The expect
assertion library is optimized with auto-waiting, so it retries until the title/URL matches or times out.
– console.log()
is optional and mainly used for debugging values
What You’ll See
– Browser opens and navigates to vinothqaacademy.com.
– Console prints the page title and URL.
– Title and URL assertions pass successfully.
– Browser closes automatically.
Try It Yourself
– Change the URL to another site (e.g., https://playwright.dev/
) and validate its title.
– Uncomment the negative scenario to see how assertion errors appear.
– Replace toHaveTitle
with a regex for flexible validation:
– awaitexpect(page).
toHaveTitle(
/Vinoth Tech/);