Skip to main content

注解

Playwright Test 支持测试注解来处理失败、不稳定性、跳过、聚焦和标记测试:

  • test.skip(title, testFunction) 将测试标记为不相关。Playwright Test 不会运行此类测试。当测试在某些配置中不适用时使用此注解。
  • test.fail() 将测试标记为失败。Playwright Test 将运行此测试并确保它确实失败。如果测试没有失败,Playwright Test 会报错。
  • test.fixme(title, testFunction) 将测试标记为失败。与 fail 注解相反,Playwright Test 不会运行此测试。当运行测试很慢或崩溃时使用 fixme
  • test.slow() 将测试标记为慢速并将测试超时时间增加三倍。

注解可以用于单个测试或一组测试。注解可以是有条件的,在这种情况下,它们在条件为真时应用。注解可能依赖于测试 fixture。同一测试可能有多个注解,可能在不同的配置中。

聚焦测试

您可以聚焦某些测试。当有聚焦的测试时,只有这些测试会运行。

test.only('focus this test', async ({ page }) => {
// Run only focused tests in the entire project.
});

跳过测试

将测试标记为已跳过。

test.skip('skip this test', async ({ page }) => {
// This test is not run
});

有条件地跳过测试

您可以根据条件跳过某些测试。

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

分组测试

您可以对测试进行分组,以便为它们提供逻辑名称或将 before/after 钩子的作用域限定为该组。

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

test.describe('two tests', () => {
test('one', async ({ page }) => {
// ...
});

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

标记测试

有时您想将测试标记为 @fast@slow,并且只运行具有特定标记的测试。我们建议您为此使用 --grep--grep-invert 命令行标志:

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

test('Test login page @fast', async ({ page }) => {
// ...
});

test('Test full report @slow', async ({ page }) => {
// ...
});

然后您将能够只运行该测试:

npx playwright test --grep @fast

或者如果您想要相反的效果,您可以跳过具有特定标记的测试:

npx playwright test --grep-invert @slow

有条件地跳过一组测试

例如,您可以通过传递回调仅在 Chromium 中运行一组测试。

// example.spec.ts

test.describe('chromium only', () => {
test.skip(({ browserName }) => browserName !== 'chromium', 'Chromium only!');

test.beforeAll(async () => {
// This hook is only run in Chromium.
});

test('test 1', async ({ page }) => {
// This test is only run in Chromium.
});

test('test 2', async ({ page }) => {
// This test is only run in Chromium.
});
});

beforeEach 钩子中使用 fixme

为了避免运行 beforeEach 钩子,您可以将注解放在钩子本身中。

// example.spec.ts

test.beforeEach(async ({ page, isMobile }) => {
test.fixme(isMobile, 'Settings page does not work in mobile yet');

await page.goto('http://localhost:3000/settings');
});

test('user profile', async ({ page }) => {
await page.getByText('My Profile').click();
// ...
});

自定义注解

还可以以注解的形式向测试添加自定义元数据。注解是可通过 test.info().annotations 访问的键/值对。许多报告器会显示注解,例如 'html'

// example.spec.ts

test('user profile', async ({ page }) => {
test.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/<some-issue>' });
// ...
});