How can I ignore query parameters when using waitForURL() or toHaveURL() in Playwright?
In Playwright, I want to check that a page navigates to a specific path while ignoring query parameters. For example, I want:
await expect(page).toHaveURL('/clients/new');
But the current URL might be:
https://server.com/clients/new?sort=name&direction=desc
Using a regular expression works, but I have to handle different server names across local, Docker, CI, and production environments. Is there a better way to make toHaveURL() or waitForURL() ignore query params?
Instead of trying to match the full URL with regex, I parse the URL and check only the path. This works regardless of host, port, or query parameters:
const currentUrl = new URL(page.url());
expect(currentUrl.pathname).toBe('/clients/new');
I do this in almost every test where the app adds dynamic query params (sorting, pagination, etc.). It’s cleaner than regex and avoids hardcoding server names across environments.
You can pass a function to toHaveURL that checks only what you care about. For example:
await expect(page).toHaveURL(url => {
const path = new URL(url).pathname;
return path === '/clients/new';
});
````Preformatted text`
This method keeps the nice toHaveURL waiting behavior but ignores the query string. I find it especially helpful in CI where URLs often include extra tracking or session params.
If you prefer a one-liner with toHaveURL, you can still use regex but focus only on the path:
await expect(page).toHaveURL(/\/clients\/new(\?.*)?$/);
It matches the path and optionally any query string, so it works for local, Docker, or production URLs without hardcoding hosts. I use this approach when I want a quick solution that works with waitForURL and toHaveURL directly.