如何在特定浏览器和视口上运行Playwright测试



我有一个带有Playwright的E2E测试套件,可以在不同的浏览器和视口上运行。

我在playwright.config.ts:中指定了不同的浏览器和视口

projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
},
},
{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
},
},
{
name: 'webkit',
use: {
...devices['Desktop Safari'],
},
},
/* Test against mobile viewports. */
{
name: 'Mobile Chrome',
use: {
...devices['Pixel 5'],
},
},
{
name: 'Mobile Safari',
use: {
...devices['iPhone 12'],
},
},
]

有些测试需要根据视口执行不同的断言和单击。

例如,当视口变得足够小时,标题会收缩为汉堡菜单。在桌面上,有一个";注销";按钮,但在手机上,你必须先打开汉堡菜单才能看到";注销";按钮

如何编写只在移动视口上运行的测试(反之亦然,只在桌面视口上运行测试(?

我能够与Playwright合作,但我不喜欢我的解决方案,并怀疑有更好的方法可以做到这一点。

我从test函数中获取了isMobile属性,然后添加了一个有条件的点击来打开手机上的汉堡菜单,如下所示:

test('given the user is logged in: lets the user log out', async ({
page,
baseURL,
isMobile,
browserName,
}) => {
const { id } = await loginAndSaveUserProfileToDatabase({ page });
await page.goto('./home');
if (isMobile) {
await page.getByRole('button', { name: /open main menu/i }).click();
}
// Logging the user out should redirect you to the landing page.
await page.getByRole('button', { name: /open user menu/i }).click();
await page.getByRole('menuitem', { name: /log out/i }).click();
expect(page.url()).toEqual(baseURL + '/');
// ...
}));

我不喜欢这种方法,因为它在测试中引入了一个条件,这是一个反模式(由Playwright ESLint插件调用(。此外,isMobile不适用于Firefox。

理想情况下,Playwright中会有一个类似TestCafe的meta标签的功能。在TestCafe中,您可以将meta添加到测试中,并通过此标记筛选出测试。

test
.meta('mobile', true)
('My test that only runs on mobile', async t => { /* ... */});

但我在文档中找不到类似的东西(除了grep标记,我不确定它是否适合这个用例(,所以我问这个问题。

您可以在测试中使用test.skip来避免条件语句的Lint错误,如下所示:test.skip(!isMobile || browserName==firefox, 'is not mobile');

除此之外,我脑海中浮现的只有grep或grepConvert。也许你可以在描述块中收集你的移动测试

test.describe('mobile', () => {
test.beforeEach(async ({ page }) => {
await page.goto(pageUrl);
});
test('some test', async ({ page })=>{

});
});

然后在你的剧作家配置中,你只需在你的项目中添加一个grep或grepConvert。例如:

{
name: 'chromium',
grepInvert: /mobile/,
use: {
...devices['Desktop Chrome'],
},
},
{
name: 'Mobile Chrome',
grep: /mobile/,
use: {
...devices['Pixel 5'],
},
},

最新更新