Reputation: 6397
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
?
Upvotes: 9
Views: 25722
Reputation: 9416
The correct way is in the official docs https://playwright.dev/docs/test-use-options#basic-options
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: 'http://127.0.0.1:3000',
},
});
Upvotes: -1
Reputation: 2173
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();
Upvotes: 2
Reputation: 6397
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.
Upvotes: 1
Reputation: 677
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');
Upvotes: 18