Search code examples
javascriptplaywrightplaywright-test

How can I set the baseURL for expect in playwright?


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?


Solution

  • 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');