5

In my Playwright tests, I set the base-url according to the docs:

const config: PlaywrightTestConfig = {
  projects: [
    {
      name: 'Safari MacBook Air',
      use: {
        browserName: 'webkit',
        viewport: {
          width: 2560,
          height: 1620,
        },
        contextOptions: {
          ignoreHTTPSErrors: true,
        },
      },
    },
  ],
  use: {
    baseURL: process.env.PLATFORMSH_URL,
    headless: false,
    locale: 'ja-JP',

    // Debugging artifacts.
    screenshot: 'on',
    trace: 'on',
    video: 'on',
  },
};
export default config;

This is working for goto:

await this.page.goto('/myDirectory');

However, it fails for expect:

  expect(page.url()).toBe('/myPage');

The error is:

Expected: "/myPage"
Received: "https://www.example.com/myPage"

How can I use expect with baseURL?

Patrick Kenny
  • 4,515
  • 7
  • 47
  • 76

3 Answers3

13

Try using this assertion instead: For example, having configured Playwright homepage as our baseUrl

   {
     name: 'webkit',
     use: {
       ...devices['Desktop Safari'],
       baseURL: 'https://playwright.dev/'
     },
   },

Then:

test('baseUrl', async ({ page }) => {
  await page.goto('/docs/intro');
  await expect(page).toHaveURL('/docs/intro');
});

If you'd like to continue using this format:

  expect(page.url()).toBe('/myPage');

Then you need to change the assertion, because the url you're at is not equal to your directory. You can assert the url you're at contains the aforementioned directory, instead:

  expect(page.url()).toContain('/myPage');
Víctor
  • 533
  • 3
  • 7
2

There is nothing wrong in your code except the last line. page.url() will give you the whole URL address on wich your driver (browser,whathever) currently is, and expect(something)toBe(thing) is like equals, and it will fail in your case.

You can assert in several ways like:

await expect(page.url().includes(partOfUrl)).toBeTruthy();

Gaj Julije
  • 1,538
  • 15
  • 32
1

In the end I just wrapped it in my own utility function:

const pwaBaseUrl = process.env.NOSLASH_URL;

export const assertPath = async (page: Page, path: string) => {
  expect(page.url()).toBe(`${pwaBaseUrl}/${path}`);
};

This guarantees that I am on the exact path. Perhaps this isn't generally necessary, but coming from Behat testing on PHP, this is what I'm used to.

Patrick Kenny
  • 4,515
  • 7
  • 47
  • 76