跳至主要内容

Playwright Test

Playwright Test 提供了一个 test 函数来声明测试,以及一个 expect 函数来编写断言。

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

test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev/');
const name = await page.innerText('.navbar__title');
expect(name).toBe('Playwright');
});

方法

测试

Added in: v1.10 test.test

声明一个测试。

  • test(title, body)
  • test(title, details, body)

用法

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

test('basic test', async ({ page }) => {
await page.goto('https://playwright.dev/');
// ...
});

标签

您可以通过提供额外的测试详情来标记测试。或者,您也可以在测试标题中包含标签。请注意,每个标签必须以@符号开头。

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

test('basic test', {
tag: '@smoke',
}, async ({ page }) => {
await page.goto('https://playwright.dev/');
// ...
});

test('another test @smoke', async ({ page }) => {
await page.goto('https://playwright.dev/');
// ...
});

测试标签会显示在测试报告中,并可通过TestCase.tags属性供自定义报告器使用。

你也可以在测试执行期间通过标签来筛选测试:

了解更多关于tagging的信息。

注解

您可以通过提供额外的测试细节来对测试进行注释。

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

test('basic test', {
annotation: {
type: 'issue',
description: 'https://github.com/microsoft/playwright/issues/23180',
},
}, async ({ page }) => {
await page.goto('https://playwright.dev/');
// ...
});

测试注解会显示在测试报告中,并且可以通过TestCase.annotations属性供自定义报告器使用。

您还可以通过操作testInfo.annotations在运行时添加注释。

了解更多关于测试注解的信息。

参数


test.afterAll

Added in: v1.10 test.test.afterAll

声明一个afterAll钩子,该钩子会在所有测试完成后每个工作线程执行一次。

在测试文件的范围内调用时,会在文件中的所有测试之后运行。在test.describe()分组内调用时,会在该分组中的所有测试之后运行。

用法

test.afterAll(async () => {
console.log('Done with tests');
// ...
});

或者,您可以使用标题声明一个钩子。

test.afterAll('Teardown', async () => {
console.log('Done with tests');
// ...
});

参数

详情

当添加多个afterAll钩子时,它们将按照注册顺序运行。

请注意,工作进程会在测试失败时重新启动,并且afterAll钩子会在新工作进程中再次运行。了解更多关于workers and failures的信息。

即使某些钩子失败,Playwright仍将继续运行所有适用的钩子。

  • test.afterAll(hookFunction)
  • test.afterAll(title, hookFunction)

test.afterEach

Added in: v1.10 test.test.afterEach

声明一个在每个测试后执行的afterEach钩子。

在测试文件范围内调用时,会在文件中的每个测试之后运行。在test.describe()分组内调用时,会在该组中的每个测试之后运行。

您可以访问与测试主体相同的所有Fixtures,以及提供大量有用信息的TestInfo对象。例如,您可以检查测试是成功还是失败。

  • test.afterEach(hookFunction)
  • test.afterEach(title, hookFunction)

用法

example.spec.ts
import { test, expect } from '@playwright/test';

test.afterEach(async ({ page }) => {
console.log(`Finished ${test.info().title} with status ${test.info().status}`);

if (test.info().status !== test.info().expectedStatus)
console.log(`Did not run as expected, ended up at ${page.url()}`);
});

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

或者,您可以使用标题声明一个钩子。

example.spec.ts
test.afterEach('Status check', async ({ page }) => {
if (test.info().status !== test.info().expectedStatus)
console.log(`Did not run as expected, ended up at ${page.url()}`);
});

参数

详情

当添加多个afterEach钩子时,它们将按照注册顺序运行。

即使某些钩子失败,Playwright仍将继续运行所有适用的钩子。


test.beforeAll

Added in: v1.10 test.test.beforeAll

声明一个beforeAll钩子,该钩子会在所有测试之前,每个工作进程执行一次。

在测试文件的作用域内调用时,会在文件中的所有测试之前运行。在test.describe()分组内调用时,会在该组所有测试之前运行。

你可以使用 test.afterAll() 来清理在 beforeAll 中设置的任何资源。

  • test.beforeAll(hookFunction)
  • test.beforeAll(title, hookFunction)

用法

example.spec.ts
import { test, expect } from '@playwright/test';

test.beforeAll(async () => {
console.log('Before tests');
});

test.afterAll(async () => {
console.log('After tests');
});

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

或者,您可以使用标题声明一个钩子。

example.spec.ts
test.beforeAll('Setup', async () => {
console.log('Before tests');
});

参数

详情

当添加多个beforeAll钩子时,它们将按照注册顺序运行。

请注意,工作进程会在测试失败时重新启动,并且beforeAll钩子会在新工作进程中再次运行。了解更多关于workers and failures的信息。

即使某些钩子失败,Playwright仍将继续运行所有适用的钩子。


test.beforeEach

Added in: v1.10 test.test.beforeEach

声明一个在每个测试之前执行的beforeEach钩子。

在测试文件的范围内调用时,会在文件中的每个测试之前运行。在test.describe()分组内调用时,会在该组的每个测试之前运行。

你可以访问与测试主体相同的所有Fixtures,以及提供大量有用信息的TestInfo对象。例如,你可以在开始测试前导航页面。

你可以使用test.afterEach()来清理在beforeEach中设置的任何资源。

  • test.beforeEach(hookFunction)
  • test.beforeEach(title, hookFunction)

用法

example.spec.ts
import { test, expect } from '@playwright/test';

test.beforeEach(async ({ page }) => {
console.log(`Running ${test.info().title}`);
await page.goto('https://my.start.url/');
});

test('my test', async ({ page }) => {
expect(page.url()).toBe('https://my.start.url/');
});

或者,您可以使用标题声明一个钩子。

example.spec.ts
test.beforeEach('Open start URL', async ({ page }) => {
console.log(`Running ${test.info().title}`);
await page.goto('https://my.start.url/');
});

参数

详情

当添加多个beforeEach钩子时,它们将按照注册顺序运行。

即使某些钩子失败,Playwright仍将继续运行所有适用的钩子。


test.describe

Added in: v1.10 test.test.describe

声明一组测试。

  • test.describe(title, callback)
  • test.describe(callback)
  • test.describe(title, details, callback)

用法

您可以使用标题声明一组测试。该标题将作为每个测试标题的一部分显示在测试报告中。

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

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

匿名群组

你也可以声明一个没有标题的测试组。这样便于通过test.use()为一组测试提供共同的选项。

test.describe(() => {
test.use({ colorScheme: 'dark' });

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

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

标签

您可以通过提供额外详情来为组中的所有测试打标签。请注意每个标签必须以@符号开头。

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

test.describe('two tagged tests', {
tag: '@smoke',
}, () => {
test('one', async ({ page }) => {
// ...
});

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

了解更多关于tagging的信息。

注解

您可以通过提供额外详细信息来为组中的所有测试添加注释。

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

test.describe('two annotated tests', {
annotation: {
type: 'issue',
description: 'https://github.com/microsoft/playwright/issues/23180',
},
}, () => {
test('one', async ({ page }) => {
// ...
});

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

了解更多关于测试注解的信息。

参数


test.describe.configure

Added in: v1.10 test.test.describe.configure

配置封闭作用域。可以在顶层或describe内部执行。配置适用于整个作用域,无论它是在测试声明之前还是之后运行。

了解更多关于执行模式的信息请点击这里

用法

  • Running tests in parallel.

    // Run all the tests in the file concurrently using parallel workers.
    test.describe.configure({ mode: 'parallel' });
    test('runs in parallel 1', async ({ page }) => {});
    test('runs in parallel 2', async ({ page }) => {});
  • Running tests serially, retrying from the start.

    note

    Running serially is not recommended. It is usually better to make your tests isolated, so they can be run independently.

    // Annotate tests as inter-dependent.
    test.describe.configure({ mode: 'serial' });
    test('runs first', async ({ page }) => {});
    test('runs second', async ({ page }) => {});
  • Configuring retries and timeout for each test.

    // Each test in the file will be retried twice and have a timeout of 20 seconds.
    test.describe.configure({ retries: 2, timeout: 20_000 });
    test('runs first', async ({ page }) => {});
    test('runs second', async ({ page }) => {});
  • Run multiple describes in parallel, but tests inside each describe in order.

    test.describe.configure({ mode: 'parallel' });

    test.describe('A, runs in parallel with B', () => {
    test.describe.configure({ mode: 'default' });
    test('in order A1', async ({ page }) => {});
    test('in order A2', async ({ page }) => {});
    });

    test.describe('B, runs in parallel with A', () => {
    test.describe.configure({ mode: 'default' });
    test('in order B1', async ({ page }) => {});
    test('in order B2', async ({ page }) => {});
    });

参数

  • options Object (optional)
    • mode "default" | "parallel" | "serial" (可选)#

      执行模式。了解更多关于执行模式的信息请点击这里

    • retries number (可选) 添加于: v1.28#

      每个测试的重试次数。

    • timeout number (可选) v1.28版本新增#

      每个测试的超时时间(毫秒)。会覆盖testProject.timeouttestConfig.timeout的设置。


test.describe.fixme

Added in: v1.25 test.test.describe.fixme

声明一个测试组,类似于test.describe()。该组中的测试将被标记为"fixme"且不会被执行。

  • test.describe.fixme(title, callback)
  • test.describe.fixme(callback)
  • test.describe.fixme(title, details, callback)

用法

test.describe.fixme('broken tests that should be fixed', () => {
test('example', async ({ page }) => {
// This test will not run
});
});

你也可以省略标题。

test.describe.fixme(() => {
// ...
});

参数


test.describe.only

Added in: v1.10 test.test.describe.only

声明一个聚焦的测试组。如果有某些聚焦的测试或套件,将只运行这些聚焦项而忽略其他内容。

  • test.describe.only(title, callback)
  • test.describe.only(callback)
  • test.describe.only(title, details, callback)

用法

test.describe.only('focused group', () => {
test('in the focused group', async ({ page }) => {
// This test will run
});
});
test('not in the focused group', async ({ page }) => {
// This test will not run
});

你也可以省略标题。

test.describe.only(() => {
// ...
});

参数


test.describe.skip

Added in: v1.10 test.test.describe.skip

声明一个跳过的测试组,类似于test.describe()。跳过的组中的测试永远不会运行。

  • test.describe.skip(title, callback)
  • test.describe.skip(title)
  • test.describe.skip(title, details, callback)

用法

test.describe.skip('skipped group', () => {
test('example', async ({ page }) => {
// This test will not run
});
});

你也可以省略标题。

test.describe.skip(() => {
// ...
});

参数


test.extend

Added in: v1.10 test.test.extend

通过定义可在测试中使用的fixtures和/或选项来扩展test对象。

用法

首先定义一个fixture和/或一个选项。

import { test as base } from '@playwright/test';
import { TodoPage } from './todo-page';

export type Options = { defaultItem: string };

// Extend basic test by providing a "defaultItem" option and a "todoPage" fixture.
export const test = base.extend<Options & { todoPage: TodoPage }>({
// Define an option and provide a default value.
// We can later override it in the config.
defaultItem: ['Do stuff', { option: true }],

// Define a fixture. Note that it can use built-in fixture "page"
// and a new option "defaultItem".
todoPage: async ({ page, defaultItem }, use) => {
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo(defaultItem);
await use(todoPage);
await todoPage.removeAll();
},
});

然后在测试中使用该夹具。

example.spec.ts
import { test } from './my-test';

test('test 1', async ({ todoPage }) => {
await todoPage.addToDo('my todo');
// ...
});

在配置文件中设置该选项。

playwright.config.ts
import { defineConfig } from '@playwright/test';
import type { Options } from './my-test';

export default defineConfig<Options>({
projects: [
{
name: 'shopping',
use: { defaultItem: 'Buy milk' },
},
{
name: 'wellbeing',
use: { defaultItem: 'Exercise!' },
},
]
});

了解更多关于fixturesparametrizing tests的信息。

参数

  • fixtures Object#

    一个包含fixtures和/或选项的对象。了解更多关于fixtures格式的信息。

返回


test.fail

Added in: v1.10 test.test.fail

将测试标记为"预期失败"。Playwright会运行该测试并确保它确实失败。这对于文档目的很有用,可以确认某些功能在被修复前是存在问题的。

声明一个"失败"的测试:

  • test.fail(title, body)
  • test.fail(title, details, body)

在运行时将测试标注为"失败":

  • test.fail(condition, description)
  • test.fail(callback, description)
  • test.fail()

用法

你可以将测试声明为失败,这样Playwright就能确保它确实会失败。

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

test.fail('not yet ready', async ({ page }) => {
// ...
});

如果您的测试在某些配置下失败,但并非所有配置都失败,您可以根据某些条件在测试体内将测试标记为失败。在这种情况下,我们建议传递一个description参数。

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

test('fail in WebKit', async ({ page, browserName }) => {
test.fail(browserName === 'webkit', 'This feature is not implemented for Mac yet');
// ...
});

你可以基于某些条件,通过一次test.fail(callback, description)调用,将文件中的所有测试或test.describe()组标记为"应该失败"。

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

test.fail(({ browserName }) => browserName === 'webkit', 'not implemented yet');

test('fail in WebKit 1', async ({ page }) => {
// ...
});
test('fail in WebKit 2', async ({ page }) => {
// ...
});

你也可以在测试体内不带参数地调用test.fail()来始终将测试标记为失败。我们建议使用test.fail(title, body)来声明失败的测试。

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

test('less readable', async ({ page }) => {
test.fail();
// ...
});

参数

  • title string (可选) 添加于: v1.42#

    测试标题。

  • details Object (可选) 新增于: v1.42#

    查看test()获取测试详情描述。

  • body function(Fixtures, TestInfo) (可选) 添加于: v1.42#

    测试体,接受一个或两个参数:一个包含fixtures的对象和可选的TestInfo

  • condition boolean (可选)#

    当条件为true时,测试会被标记为"预期失败"。

  • callback function(Fixtures):boolean (可选)#

    一个基于测试夹具返回是否标记为"应该失败"的函数。当返回值为true时,测试或测试集将被标记为"应该失败"。

  • description string (可选)#

    可选描述,将在测试报告中体现。


test.fail.only

Added in: v1.49 test.test.fail.only

你可以使用test.fail.only来专注于预期会失败的特定测试。这在调试失败测试或处理特定问题时特别有用。

声明一个聚焦的"失败"测试:

  • test.fail.only(title, body)
  • test.fail.only(title, details, body)

用法

您可以声明一个聚焦的失败测试,这样Playwright仅运行此测试并确保它确实失败。

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

test.fail.only('focused failing test', async ({ page }) => {
// This test is expected to fail
});
test('not in the focused group', async ({ page }) => {
// This test will not run
});

参数


test.fixme

Added in: v1.10 test.test.fixme

将测试标记为"待修复",目的是稍后修复它。Playwright不会运行test.fixme()调用之后的测试。

要声明一个"待修复"测试:

  • test.fixme(title, body)
  • test.fixme(title, details, body)

在运行时将测试标注为"fixme":

  • test.fixme(condition, description)
  • test.fixme(callback, description)
  • test.fixme()

用法

您可以将测试声明为待修复,这样Playwright就不会运行它。

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

test.fixme('to be fixed', async ({ page }) => {
// ...
});

如果您的测试需要在某些配置下修复但并非所有配置,您可以根据某些条件在测试体内将测试标记为"fixme"。我们建议在这种情况下传递一个description参数。Playwright会运行该测试,但在test.fixme调用后立即中止它。

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

test('to be fixed in Safari', async ({ page, browserName }) => {
test.fixme(browserName === 'webkit', 'This feature breaks in Safari for some reason');
// ...
});

你可以通过单个test.fixme(callback, description)调用,根据某些条件将文件或test.describe()组中的所有测试标记为"待修复"。

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

test.fixme(({ browserName }) => browserName === 'webkit', 'Should figure out the issue');

test('to be fixed in Safari 1', async ({ page }) => {
// ...
});
test('to be fixed in Safari 2', async ({ page }) => {
// ...
});

你也可以在测试体内不带参数地调用test.fixme()来始终将测试标记为失败。我们推荐使用test.fixme(title, body)替代。

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

test('less readable', async ({ page }) => {
test.fixme();
// ...
});

参数

  • title string (可选)#

    测试标题。

  • details Object (可选) 新增于: v1.42#

    查看test()获取测试详情描述。

  • body function(Fixtures, TestInfo) (可选)#

    测试主体函数,接收一个或两个参数:包含fixtures的对象和可选的TestInfo

  • condition boolean (可选)#

    当条件为true时,测试会被标记为"预期失败"。

  • callback function(Fixtures):boolean (可选)#

    一个基于测试夹具返回是否标记为"应失败"的函数。当返回值为true时,测试会被标记为"应失败"。

  • description string (可选)#

    可选描述,将在测试报告中体现。


测试信息

Added in: v1.10 test.test.info

返回当前运行测试的相关信息。此方法只能在测试执行期间调用,否则会抛出异常。

用法

test('example test', async ({ page }) => {
// ...
await test.info().attach('screenshot', {
body: await page.screenshot(),
contentType: 'image/png',
});
});

返回


仅测试

Added in: v1.10 test.test.only

声明一个聚焦测试。如果存在一些聚焦测试或测试套件,将只运行这些聚焦测试/套件,其他测试不会运行。

  • test.only(title, body)
  • test.only(title, details, body)

用法

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

参数


test.setTimeout

Added in: v1.10 test.test.setTimeout

更改测试的超时时间。零表示无超时。了解更多关于各种超时的信息。

当前运行测试的超时时间可通过 testInfo.timeout 获取。

用法

  • 修改测试超时时间。

    test('very slow test', async ({ page }) => {
    test.setTimeout(120000);
    // ...
    });
  • 从缓慢的beforeEach钩子中更改超时时间。请注意,这会影响与beforeEach钩子共享的测试超时。

    test.beforeEach(async ({ page }, testInfo) => {
    // 为所有运行此钩子的测试延长30秒超时时间
    test.setTimeout(testInfo.timeout + 30000);
    });
  • 更改beforeAllafterAll钩子的超时时间。请注意这会影响钩子的超时,而不是测试的超时。

    test.beforeAll(async () => {
    // 设置此钩子的超时时间
    test.setTimeout(60000);
    });
  • Changing timeout for all tests in a test.describe() group.

    test.describe('group', () => {
    // Applies to all tests in this group.
    test.describe.configure({ timeout: 60000 });

    test('test one', async () => { /* ... */ });
    test('test two', async () => { /* ... */ });
    test('test three', async () => { /* ... */ });
    });

参数

  • timeout number#

    超时时间(毫秒)。


test.skip

Added in: v1.10 test.test.skip

跳过测试。Playwright 将不会执行 test.skip() 调用之后的测试。

跳过的测试不应该被执行。如果您打算修复测试,请使用test.fixme()代替。

声明一个跳过的测试:

  • test.skip(title, body)
  • test.skip(title, details, body)

要在运行时跳过测试:

  • test.skip(condition, description)
  • test.skip(callback, description)
  • test.skip()

用法

您可以声明一个跳过的测试,Playwright将不会运行它。

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

test.skip('never run', async ({ page }) => {
// ...
});

如果您的测试在某些配置下需要跳过,但并非所有情况,您可以根据某些条件在测试体内跳过测试。我们建议在这种情况下传递一个description参数。Playwright会运行测试,但在test.skip调用后立即中止它。

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

test('Safari-only test', async ({ page, browserName }) => {
test.skip(browserName !== 'webkit', 'This feature is Safari-only');
// ...
});

您可以根据某些条件,通过单个test.skip(callback, description)调用来跳过文件或test.describe()组中的所有测试。

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

test.skip(({ browserName }) => browserName !== 'webkit', 'Safari-only');

test('Safari-only test 1', async ({ page }) => {
// ...
});
test('Safari-only test 2', async ({ page }) => {
// ...
});

你也可以在测试体内不带参数地调用test.skip()来始终将测试标记为失败。我们推荐使用test.skip(title, body)替代。

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

test('less readable', async ({ page }) => {
test.skip();
// ...
});

参数

  • title string (可选)#

    测试标题。

  • details Object (可选) 新增于: v1.42#

    查看test()获取测试详情描述。

  • body function(Fixtures, TestInfo) (可选)#

    测试主体函数,接收一个或两个参数:包含fixtures的对象和可选的TestInfo

  • condition boolean (可选)#

    当条件为true时,测试会被标记为"预期失败"。

  • callback function(Fixtures):boolean (可选)#

    一个基于测试夹具返回是否标记为"应该失败"的函数。当返回值为true时,测试或测试集将被标记为"应该失败"。

  • description string (可选)#

    可选描述,将在测试报告中体现。


test.slow

Added in: v1.10 test.test.slow

将测试标记为"慢速"。慢速测试将获得默认超时时间的三倍。

请注意test.slow()不能在beforeAllafterAll钩子中使用。请改用test.setTimeout()

  • test.slow()
  • test.slow(condition, description)
  • test.slow(callback, description)

用法

你可以通过在测试体内调用test.slow()来将测试标记为慢速测试。

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

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

如果您的测试在某些配置下运行缓慢,但并非所有配置都如此,您可以根据条件将其标记为慢速测试。在这种情况下,我们建议传递一个description参数。

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

test('slow in Safari', async ({ page, browserName }) => {
test.slow(browserName === 'webkit', 'This feature is slow in Safari');
// ...
});

您可以通过传递回调函数,根据某些条件将文件中的所有测试或test.describe()组标记为"slow"。

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

test.slow(({ browserName }) => browserName === 'webkit', 'all tests are slow in Safari');

test('slow in Safari 1', async ({ page }) => {
// ...
});
test('fail in Safari 2', async ({ page }) => {
// ...
});

参数

  • condition boolean (可选)#

    当条件为true时,测试会被标记为"slow"。

  • callback function(Fixtures):boolean (可选)#

    一个基于测试夹具返回是否标记为"慢"的函数。当返回值为true时,测试或测试集会被标记为"慢"。

  • description string (可选)#

    可选描述,将在测试报告中体现。


test.step

Added in: v1.10 test.test.step

声明一个在报告中显示的测试步骤。

用法

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

test('test', async ({ page }) => {
await test.step('Log in', async () => {
// ...
});

await test.step('Outer step', async () => {
// ...
// You can nest steps inside each other.
await test.step('Inner step', async () => {
// ...
});
});
});

参数

  • title string#

    步骤名称。

  • body function(TestStepInfo):Promise<Object>#

    步骤主体。

  • options Object (可选)

    • box boolean (可选) 添加于: v1.39#

      是否在报告中将该步骤框起来。默认为false。当步骤被框起来时,从步骤内部抛出的错误会指向步骤调用位置。更多详情请见下文。

    • location Location (可选) 添加于: v1.48#

      指定测试报告和追踪查看器中显示步骤的自定义位置。默认情况下会显示test.step()调用的位置。

    • timeout number (可选) 添加于: v1.50#

      允许步骤完成的最长时间,以毫秒为单位。如果步骤未在指定的超时时间内完成,test.step()方法将抛出TimeoutError。默认为0(无超时)。

返回

详情

该方法返回由步骤回调函数返回的值。

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

test('test', async ({ page }) => {
const user = await test.step('Log in', async () => {
// ...
return 'john';
});
expect(user).toBe('john');
});

装饰器

你可以使用TypeScript方法装饰器将方法转换为步骤。每次调用被装饰的方法都会在报告中显示为一个步骤。

function step(target: Function, context: ClassMethodDecoratorContext) {
return function replacementMethod(...args: any) {
const name = this.constructor.name + '.' + (context.name as string);
return test.step(name, async () => {
return await target.call(this, ...args);
});
};
}

class LoginPage {
constructor(readonly page: Page) {}

@step
async login() {
const account = { username: 'Alice', password: 's3cr3t' };
await this.page.getByLabel('Username or email address').fill(account.username);
await this.page.getByLabel('Password').fill(account.password);
await this.page.getByRole('button', { name: 'Sign in' }).click();
await expect(this.page.getByRole('button', { name: 'View profile and more' })).toBeVisible();
}
}

test('example', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.login();
});

装箱

当步骤中的某个操作失败时,通常会看到错误指向具体的失败操作。例如,考虑以下登录步骤:

async function login(page) {
await test.step('login', async () => {
const account = { username: 'Alice', password: 's3cr3t' };
await page.getByLabel('Username or email address').fill(account.username);
await page.getByLabel('Password').fill(account.password);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible();
});
}

test('example', async ({ page }) => {
await page.goto('https://github.com/login');
await login(page);
});
Error: Timed out 5000ms waiting for expect(locator).toBeVisible()
... error details omitted ...

8 | await page.getByRole('button', { name: 'Sign in' }).click();
> 9 | await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible();
| ^
10 | });

如上所示,测试可能会失败并指向步骤内部的错误。如果您希望错误高亮显示"login"步骤而非其内部细节,请使用box选项。在boxed步骤中发生的错误会指向该步骤的调用位置。

async function login(page) {
await test.step('login', async () => {
// ...
}, { box: true }); // Note the "box" option here.
}
Error: Timed out 5000ms waiting for expect(locator).toBeVisible()
... error details omitted ...

14 | await page.goto('https://github.com/login');
> 15 | await login(page);
| ^
16 | });

你也可以为boxed步骤创建一个TypeScript装饰器,类似于上面的常规步骤装饰器:

function boxedStep(target: Function, context: ClassMethodDecoratorContext) {
return function replacementMethod(...args: any) {
const name = this.constructor.name + '.' + (context.name as string);
return test.step(name, async () => {
return await target.call(this, ...args);
}, { box: true }); // Note the "box" option here.
};
}

class LoginPage {
constructor(readonly page: Page) {}

@boxedStep
async login() {
// ....
}
}

test('example', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.login(); // <-- Error will be reported on this line.
});

test.step.skip

Added in: v1.50 test.test.step.skip

将测试步骤标记为"跳过"以临时禁用其执行,适用于当前失败并计划近期修复的步骤。Playwright不会运行该步骤。另请参阅testStepInfo.skip()

我们推荐使用 testStepInfo.skip() 替代。

用法

您可以声明一个跳过的步骤,Playwright将不会运行它。

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

test('my test', async ({ page }) => {
// ...
await test.step.skip('not yet ready', async () => {
// ...
});
});

参数

  • title string#

    步骤名称。

  • body function():Promise<Object>#

    步骤体。

  • options Object (可选)

    • box boolean (可选)#

      是否在报告中将该步骤框起来。默认为false。当步骤被框起来时,从步骤内部抛出的错误会指向步骤调用位置。更多详情请见下文。

    • location Location (可选)#

      指定该步骤在测试报告和跟踪查看器中显示的自定义位置。默认情况下,会显示test.step()调用的位置。

    • timeout number (可选)#

      步骤完成的最大时间(毫秒)。默认为0(无超时)。

返回


test.use

Added in: v1.10 test.test.use

指定在单个测试文件或test.describe()组中使用的选项或夹具。最常用于设置选项,例如设置locale来配置context夹具。

用法

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

test.use({ locale: 'en-US' });

test('test with locale', async ({ page }) => {
// Default context and page have locale as specified
});

参数

详情

test.use 可以在全局作用域内或 test.describe 内部调用。在 beforeEachbeforeAll 中调用它是错误的。

也可以通过提供一个函数来覆盖fixture。

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

test.use({
locale: async ({}, use) => {
// Read locale from some configuration file.
const locale = await fs.promises.readFile('test-locale', 'utf-8');
await use(locale);
},
});

test('test with locale', async ({ page }) => {
// Default context and page have locale as specified
});

属性

test.expect

Added in: v1.10 test.test.expect

expect 函数可用于创建测试断言。了解更多关于测试断言的信息。

用法

test('example', async ({ page }) => {
await test.expect(page).toHaveTitle('Title');
});

类型


已弃用

test.describe.parallel

Added in: v1.10 test.test.describe.parallel
Discouraged

有关配置执行模式的首选方法,请参阅test.describe.configure()

声明一组可以并行运行的测试。默认情况下,单个测试文件中的测试会按顺序运行,但使用test.describe.parallel()可以让它们并行运行。

  • test.describe.parallel(title, callback)
  • test.describe.parallel(callback)
  • test.describe.parallel(title, details, callback)

用法

test.describe.parallel('group', () => {
test('runs in parallel 1', async ({ page }) => {});
test('runs in parallel 2', async ({ page }) => {});
});

请注意,并行测试是在单独的进程中执行的,无法共享任何状态或全局变量。每个并行测试都会执行所有相关的钩子。

你也可以省略标题。

test.describe.parallel(() => {
// ...
});

参数


test.describe.parallel.only

Added in: v1.10 test.test.describe.parallel.only
Discouraged

有关配置执行模式的首选方式,请参阅test.describe.configure()

声明一个可以并行运行的测试聚焦组。这类似于test.describe.parallel(),但会聚焦该组。如果存在一些聚焦测试或套件,将运行所有这些聚焦项而忽略其他内容。

  • test.describe.parallel.only(title, callback)
  • test.describe.parallel.only(callback)
  • test.describe.parallel.only(title, details, callback)

用法

test.describe.parallel.only('group', () => {
test('runs in parallel 1', async ({ page }) => {});
test('runs in parallel 2', async ({ page }) => {});
});

你也可以省略标题。

test.describe.parallel.only(() => {
// ...
});

参数


test.describe.serial

Added in: v1.10 test.test.describe.serial
Discouraged

有关配置执行模式的首选方法,请参阅test.describe.configure()

声明一组应该始终串行运行的测试。如果其中一个测试失败,则跳过所有后续测试。组中的所有测试会一起重试。

note

不建议使用串行模式。通常更好的做法是让您的测试相互隔离,这样它们可以独立运行。

  • test.describe.serial(title, callback)
  • test.describe.serial(title)
  • test.describe.serial(title, details, callback)

用法

test.describe.serial('group', () => {
test('runs first', async ({ page }) => {});
test('runs second', async ({ page }) => {});
});

你也可以省略标题。

test.describe.serial(() => {
// ...
});

参数


test.describe.serial.only

Added in: v1.10 test.test.describe.serial.only
Discouraged

有关配置执行模式的首选方法,请参阅test.describe.configure()

声明一组需要始终串行执行的焦点测试。如果其中一个测试失败,所有后续测试将被跳过。组内的所有测试会一起重试。如果存在某些焦点测试或测试套件,它们都将被执行,但其他内容不会运行。

note

不建议使用串行模式。通常更好的做法是让您的测试相互隔离,这样它们可以独立运行。

  • test.describe.serial.only(title, callback)
  • test.describe.serial.only(title)
  • test.describe.serial.only(title, details, callback)

用法

test.describe.serial.only('group', () => {
test('runs first', async ({ page }) => {
});
test('runs second', async ({ page }) => {
});
});

你也可以省略标题。

test.describe.serial.only(() => {
// ...
});

参数