In Playwright, you can verify the current page URL using the toHaveURL method of the PageAssertions Interface.
Table of Content
- Syntax
- Verify URL using Exact Match
- Verify URL using Partial Match
- Verify URL containing slashes
- Verify URL using Regex Interface
- 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.
Fri, 10/07/2022 - 06:51
Tarun Goswami is a highly experienced professional, currently serving as Technical Lead at a well-established IT services company. With over 12 years of experience across multiple domains, he demonstrates his expertise and passion for the industry through his engaging and informative blog writing in his spare time.
Comments