如何在 Playwright 中使用 TypeScript 继续使用现有的浏览器会话进行测试?
我正在尝试在 Playwright UI 测试中使用页面对象模型。我已经创建了一个登录的设置文件,因为这是每个测试的第一步。
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 });
});
然而,当我继续进行测试的下一页时,浏览器会关闭,并打开一个新的空白浏览器会话。我希望测试能够继续使用现有的浏览器会话。
这是我用于测试的 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);
});
这是我的配置
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;
任何帮助都始终受到欢迎和感激。谢谢
答案#1
在设置状态并在启动测试时重用它时,你会想要使用浏览器状态而不是页面状态来存储状态。
例如:
test('User can integrate with third parties', async ({ page, browser }) => {....})
然后在设置文件中,你可以像这样操作
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 });
});
你会想把这个传递给每个重用该上下文的测试。这里有一些关于 Playwright 的更多文档。
答案#2
对于更新的版本,以下代码片段应该有效:
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.contexts().forEach(async context => {
await context.storageState({ path: authFile });
});
});
将先前保存的 cookie 合并到您的测试中。
const fs = require('fs');
const storageState = JSON.parse(fs.readFileSync(authFile, 'utf8'));
const context: BrowserContext = await browser.newContext({ storageState });
const newpage = await context.newPage();
await newpage.goto('https://your_url_here/');
