I am trying to use Page Object Model for Playwright UI tests. I have created a setup file for login, as this is always the first step in each test.
import { test as setup, expect } from '@playwright/test';
import { Credentials } from '../pages/Credentials';
import { LoginPage } from '../pages/Login.page';
const authFile = 'playwright/.auth/user.json';
setup('authenticate', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.navigate();
await loginPage.enterUsername(Credentials.username);
await loginPage.enterPassword(Credentials.password);
await loginPage.clickLoginButton();
expect (await loginPage.getWelcomeMessage()).toBe(true);
// End of authentication steps.
await page.context().storageState({ path: authFile });
});
However, when I continue to the next page of my test, the browser closes and a new empty browser session opens. I want the test to carry on using the existing browser session.
This is my code for the test using POM.
// PMSIntegrations.ts
import { test, expect } from '@playwright/test';
import PMSIntegrations from '../pages/PMSIntegrations.page';
test('User can integrate with third parties', async ({ page }) => {
const pmsIntegrationsPage = new PMSIntegrations(page);
await pmsIntegrationsPage.navigateToIntegrations();
expect (await pmsIntegrationsPage.areServicesConnected()).toBe(true);
});
And this is my config
import { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'Chromium',
use: { browserName: 'chromium',
// Use prepared auth state.
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
}
],
};
export default config;
Any help always welcomed and appreciated. Thanks
You will want to use the browser state rather than page when storing the state in the set up and then reusing this when starting your tests.
For example:
test('User can integrate with third parties', async ({ page, browser }) => {....})
and then in the setup file you can do so like this
setup('authenticate', async ({ page, browser }) => {
const loginPage = new LoginPage(page);
await loginPage.navigate();
await loginPage.enterUsername(Credentials.username);
await loginPage.enterPassword(Credentials.password);
await loginPage.clickLoginButton();
expect (await loginPage.getWelcomeMessage()).toBe(true);
// End of authentication steps.
await browser.context().storageState({ path: authFile });
});
You will want to pass this into each test that is reusing the context. Here's some more Playwright documentation on this.