Verify URL in Playwright

Verify URL in Playwright

In Playwright, you can verify the current page URL using the toHaveURL method of the PageAssertions Interface.

Table of Content

  1. Syntax
  2. Verify URL using Exact Match
  3. Verify URL using Partial Match
  4. Verify URL containing slashes
  5. Verify URL using Regex Interface
  6. Video Tutorial

Syntax

expect(page).toHaveURL(urlOrRegExp[, options])
  • urlOrRegExp <string|RegExp> Expected URL string or RegExp. Added in: v1.18#
  • options? <Object>
    • timeout? <number> Time to retry the assertion for. Defaults to timeout in TestConfig.expect. Added in: v1.18#
  • returns: <Promise<void>>

Verify URL using Exact Match

test.only('verify page title', async ({page})=>{
    await page.goto('https://www.programsbuzz.com')
    await page.locator('text=Blog').click()
    await expect(page).toHaveURL('https://www.programsbuzz.com/blog');  
    })

Verify URL using Partial Match

await expect(page).toHaveURL(/blog/);

Here we are using RegExp. This will verify that the URL contains blog text.

Verify URL containing slashes

await expect(page).toHaveURL(/\/blog/);

This will verify that the URL contains /blog. Use a backslash (\) to escape forward slash (/).

Verify URL using Regex Interface

We can also use the regex interface for regular expression matches. 

await expect(page).toHaveURL(new RegExp('/blog$'));

This will verify that the URL ends with /blog. We use $ for ends with and ^ for starts with. Escaping forward slash is not required here.

Video Tutorial: Playwright Check URL

Managed ad


Ashwin R
Ashwin possesses over 7 years of experience in the Quality Assurance industry. His expertise encompasses a broad range of technologies, including Cypress, Rest Assured, Selenium, Cucumber, JavaScript and TypeScript.