Skip to main content

Fixtures

Playwright Test 基于测试夹具的概念。测试夹具用于为每个测试建立环境,为测试提供所需的一切,而不提供其他内容。

Playwright Test 查看每个测试声明,分析测试需要的夹具集,并专门为测试准备这些夹具。夹具准备的值被合并到一个对象中,该对象作为第一个参数可用于 test、钩子、注释和其他夹具。

import { test, expect } from '@playwright/test';

test('basic test', async ({ page }) => {
// ...
});

在上面的测试中,Playwright Test 将在运行测试之前设置 page 夹具,并在测试完成后将其拆除。page 夹具提供了一个可供测试使用的 Page 对象。

Playwright Test 附带下面列出的内置夹具,你也可以添加自己的夹具。Playwright Test 还提供选项来配置 fixtures.browserfixtures.contextfixtures.page

fixtures.browser

Added in: v1.10

Browser 实例在同一个 worker 中的所有测试之间共享 - 这使得测试更高效。但是,每个测试都在一个隔离的 BrowserContext 中运行,并获得一个全新的环境。

了解如何配置浏览器并查看可用选项

fixtures.browserName

Added in: v1.10
  • type: <"chromium"|"firefox"|"webkit">

运行测试的浏览器名称。默认为 'chromium'。可用于根据浏览器注释测试

test('skip this test in Firefox', async ({ page, browserName }) => {
test.skip(browserName === 'firefox', 'Still working on it');
// ...
});

fixtures.context

Added in: v1.10

隔离的 BrowserContext 实例,为每个测试创建。由于上下文彼此隔离,因此每个测试都会获得一个全新的环境,即使多个测试在单个 Browser 中运行以实现最高效率。

了解如何配置上下文并查看可用选项

默认的 fixtures.page 属于此上下文。

fixtures.page

Added in: v1.10

隔离的 Page 实例,为每个测试创建。由于 fixtures.context 隔离,页面在测试之间是隔离的。

这是测试中最常用的夹具。

import { test, expect } from '@playwright/test';

test('basic test', async ({ page }) => {
await page.goto('/signin');
await page.getByLabel('User Name').fill('user');
await page.getByLabel('Password').fill('password');
await page.getByText('Sign in').click();
// ...
});

fixtures.request

Added in: v1.10

为每个测试隔离的 APIRequestContext 实例。

import { test, expect } from '@playwright/test';

test('basic test', async ({ request }) => {
await request.post('/signin', {
data: {
username: 'user',
password: 'password'
}
});
// ...
});