跳转到主要内容

TestInfo

TestInfo 包含了当前正在运行的测试的相关信息。它可供测试函数、test.beforeEach()test.afterEach()test.beforeAll()test.afterAll() 钩子以及测试范围(test-scoped)的 fixture 使用。TestInfo 提供了控制测试执行的实用程序:附加文件、更新测试超时时间、确定当前正在运行的测试及其是否已重试等。

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

test('basic test', async ({ page }, testInfo) => {
expect(testInfo.title).toBe('basic test');
await page.screenshot(testInfo.outputPath('screenshot.png'));
});

方法

attach

新增于: v1.10 testInfo.attach

将值或磁盘上的文件附加到当前测试。某些报告器会显示测试附件。必须指定 pathbody 中的一项,不能同时指定两者。

例如,你可以将截图附加到测试中

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

test('basic test', async ({ page }, testInfo) => {
await page.goto('https://playwright.net.cn');
const screenshot = await page.screenshot();
await testInfo.attach('screenshot', { body: screenshot, contentType: 'image/png' });
});

或者,你可以附加 API 返回的文件

import { test, expect } from '@playwright/test';
import { download } from './my-custom-helpers';

test('basic test', async ({}, testInfo) => {
const tmpPath = await download('a');
await testInfo.attach('downloaded', { path: tmpPath });
});
注意

testInfo.attach() 会自动处理将附加的文件复制到报告器可访问的位置。在 await attach 调用之后,您可以安全地删除该附件。

用法

await testInfo.attach(name);
await testInfo.attach(name, options);

参数

  • name string#

    附件名称。该名称也会经过清理,并在保存到磁盘时用作文件名的前缀。

  • options Object (可选)

    • body string | Buffer (可选)#

      附件主体。与 path 互斥。

    • contentType string (可选)#

      此附件的内容类型,以便在报告中正确显示,例如 'application/json''image/png'。如果省略,则会根据 path 推断内容类型;对于 string 类型的附件,默认值为 text/plain;对于 Buffer 类型的附件,默认值为 application/octet-stream

    • path string (可选)#

      文件系统上已附加文件的路径。与 body 互斥。

返回


fail()

新增于: v1.10 testInfo.fail()

将当前正在运行的测试标记为“应失败”。Playwright Test 会运行此测试并确保它确实失败。这对于文档记录很有用,可以确认某些功能在修复之前是损坏的。这与 test.fail() 类似。

用法

testInfo.fail();

fail(condition)

新增于: v1.10 testInfo.fail(condition)

有条件地将当前正在运行的测试标记为“应失败”,并附带可选的描述。这与 test.fail() 类似。

用法

testInfo.fail(condition);
testInfo.fail(condition, description);

参数

  • condition boolean#

    当条件为 true 时,测试被标记为“应失败”。

  • description string (可选)#

    可选描述,将反映在测试报告中。


fixme()

新增于: v1.10 testInfo.fixme()

将测试标记为“fixme”,表示有待修复。测试会立即终止。这与 test.fixme() 类似。

用法

testInfo.fixme();

fixme(condition)

新增于: v1.10 testInfo.fixme(condition)

有条件地将当前正在运行的测试标记为“fixme”,并附带可选的描述。这与 test.fixme() 类似。

用法

testInfo.fixme(condition);
testInfo.fixme(condition, description);

参数

  • condition boolean#

    当条件为 true 时,测试被标记为“fixme”。

  • description string (可选)#

    可选描述,将反映在测试报告中。


outputPath

新增于: v1.10 testInfo.outputPath

返回 testInfo.outputDir 内的一个路径,测试可以在该路径下安全地放置临时文件。保证并行运行的测试不会相互干扰。

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

test('example test', async ({}, testInfo) => {
const file = testInfo.outputPath('dir', 'temporary-file.txt');
await fs.promises.writeFile(file, 'Put some data to the dir/temporary-file.txt', 'utf8');
});

请注意,pathSegments 接受测试输出目录的路径片段,例如 testInfo.outputPath('relative', 'path', 'to', 'output')。但是,该路径必须保留在每个测试的 testInfo.outputDir 目录(即 test-results/a-test-title)内,否则会抛出错误。

用法

testInfo.outputPath(...pathSegments);

参数

  • ...pathSegments Array<string>#

    要附加到结果路径末尾的路径片段。

返回


setTimeout

新增于: v1.10 testInfo.setTimeout

更改当前正在运行的测试的超时时间。零表示没有超时。了解有关 各种超时时间 的更多信息。

超时时间通常在 配置文件 中指定,但在某些情况下更改超时时间可能会很有用。

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

test.beforeEach(async ({ page }, testInfo) => {
// Extend timeout for all tests running this hook by 30 seconds.
testInfo.setTimeout(testInfo.timeout + 30000);
});

用法

testInfo.setTimeout(timeout);

参数

  • timeout number#

    超时时间,单位为毫秒。


skip()

新增于: v1.10 testInfo.skip()

无条件跳过当前正在运行的测试。测试会立即终止。这与 test.skip() 类似。

用法

testInfo.skip();

skip(condition)

新增于: v1.10 testInfo.skip(condition)

有条件地跳过当前正在运行的测试,并附带可选的描述。这与 test.skip() 类似。

用法

testInfo.skip(condition);
testInfo.skip(condition, description);

参数

  • condition boolean#

    跳过条件。当条件为 true 时,跳过测试。

  • description string (可选)#

    可选描述,将反映在测试报告中。


slow()

新增于: v1.10 testInfo.slow()

将当前正在运行的测试标记为“慢”,使其超时时间为默认值的 3 倍。这与 test.slow() 类似。

用法

testInfo.slow();

slow(condition)

新增于: v1.10 testInfo.slow(condition)

有条件地将当前正在运行的测试标记为“慢”,并附带可选的描述,使其超时时间为默认值的 3 倍。这与 test.slow() 类似。

用法

testInfo.slow(condition);
testInfo.slow(condition, description);

参数

  • condition boolean#

    当条件为 true 时,测试被标记为“慢”。

  • description string (可选)#

    可选描述,将反映在测试报告中。


snapshotPath

新增于: v1.10 testInfo.snapshotPath

返回给定 name 的快照文件路径。传递 kind 以获取特定路径

用法

await expect(page).toHaveScreenshot('header.png');
// Screenshot assertion above expects screenshot at this path:
const screenshotPath = test.info().snapshotPath('header.png', { kind: 'screenshot' });

await expect(page.getByRole('main')).toMatchAriaSnapshot({ name: 'main.aria.yml' });
// Aria snapshot assertion above expects snapshot at this path:
const ariaSnapshotPath = test.info().snapshotPath('main.aria.yml', { kind: 'aria' });

expect('some text').toMatchSnapshot('snapshot.txt');
// Snapshot assertion above expects snapshot at this path:
const snapshotPath = test.info().snapshotPath('snapshot.txt');

expect('some text').toMatchSnapshot(['dir', 'subdir', 'snapshot.txt']);
// Snapshot assertion above expects snapshot at this path:
const nestedPath = test.info().snapshotPath('dir', 'subdir', 'snapshot.txt');

参数

  • ...name Array<string>#

    快照的名称或用于定义快照文件路径的路径片段。在同一个测试文件中,名称相同的快照被视为相同。

    当传递 kind 时,不支持多个名称片段。

  • options Object (可选)

    • kind "snapshot" | "screenshot" | "aria" (可选)新增于: v1.53#

      快照种类控制使用哪个快照路径模板。有关更多详细信息,请参阅 testConfig.snapshotPathTemplate。默认为 'snapshot'

返回


属性

annotations

新增于: v1.10 testInfo.annotations

适用于当前测试的注释列表。包括来自测试本身的注释、测试所属的所有 test.describe() 分组的注释,以及测试文件层面的注释。

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

用法

testInfo.annotations

类型

  • Array<Object>
    • type 字符串

      注释类型,例如 'skip''fail'

    • description 字符串 (可选)

      可选描述。

    • location 位置 (可选)

      注释在源代码中的可选位置。


attachments

新增于: v1.10 testInfo.attachments

附加到当前测试的文件或缓冲区的列表。某些报告器会显示测试附件。

要添加附件,请使用 testInfo.attach(),而不是直接 push 到此数组。

用法

testInfo.attachments

类型

  • Array<Object>
    • name string

      附件名称。

    • contentType string

      此附件的内容类型,用于在报告中正确显示,例如 'application/json''image/png'

    • path string (可选)

      文件系统上附加文件的可选路径。

    • body Buffer (可选)

      可选的附件正文,用于代替文件。


column

新增于: v1.10 testInfo.column

声明当前正在运行的测试所在的列号。

用法

testInfo.column

类型


config

新增于: v1.10 testInfo.config

来自 配置文件 的处理后的配置。

用法

testInfo.config

类型


duration

新增于: v1.10 testInfo.duration

测试完成所花费的毫秒数。在测试成功或失败完成之前,始终为零。可在 test.afterEach() 钩子中使用。

用法

testInfo.duration

类型


error

新增于: v1.10 testInfo.error

测试执行期间抛出的第一个错误(如果有)。这等同于 testInfo.errors 中的第一个元素。

用法

testInfo.error

类型


errors

新增于: v1.10 testInfo.errors

测试执行期间抛出的错误(如果有)。

用法

testInfo.errors

类型


expectedStatus

新增于: v1.10 testInfo.expectedStatus

当前正在运行的测试的预期状态。这通常是 'passed',但在少数情况下除外

  • 'skipped' 用于跳过的测试,例如使用 test.skip()
  • 'failed' 用于使用 test.fail() 标记为失败的测试。

预期状态通常与实际的 testInfo.status 进行比较

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

test.afterEach(async ({}, testInfo) => {
if (testInfo.status !== testInfo.expectedStatus)
console.log(`${testInfo.title} did not run as expected!`);
});

用法

testInfo.expectedStatus

类型

  • "passed" | "failed" | "timedOut" | "skipped" | "interrupted"

file

新增于: v1.10 testInfo.file

声明当前正在运行的测试所在文件的绝对路径。

用法

testInfo.file

类型


fn

新增于: v1.10 testInfo.fn

作为 test(title, testFunction) 传递的测试函数。

用法

testInfo.fn

类型


line

新增于: v1.10 testInfo.line

声明当前正在运行的测试所在的行号。

用法

testInfo.line

类型


outputDir

新增于: v1.10 testInfo.outputDir

此特定测试运行的输出目录的绝对路径。每个测试运行都有自己的目录,因此它们不会冲突。

用法

testInfo.outputDir

类型


parallelIndex

新增于: v1.10 testInfo.parallelIndex

Worker 的索引,范围在 0workers - 1 之间。保证同时运行的 worker 具有不同的 parallelIndex。当 worker 重启(例如在失败后)时,新的 worker 进程具有相同的 parallelIndex

也可作为 process.env.TEST_PARALLEL_INDEX 使用。了解有关使用 Playwright Test 进行 并行和分片(sharding) 的更多信息。

用法

testInfo.parallelIndex

类型


project

新增于: v1.10 testInfo.project

来自 配置文件 的处理后的项目配置。

用法

testInfo.project

类型


repeatEachIndex

新增于: v1.10 testInfo.repeatEachIndex

在“重复每个(repeat each)”模式下运行时指定唯一的重复索引。通过将 --repeat-each 传递给 命令行 来启用此模式。

用法

testInfo.repeatEachIndex

类型


retry

新增于: v1.10 testInfo.retry

在失败后重试测试时指定重试次数。第一次测试运行时 testInfo.retry 等于 0,第一次重试时等于 1,依此类推。了解有关 重试 的更多信息。

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

test.beforeEach(async ({}, testInfo) => {
// You can access testInfo.retry in any hook or fixture.
if (testInfo.retry > 0)
console.log(`Retrying!`);
});

test('my test', async ({ page }, testInfo) => {
// Here we clear some server-side state when retrying.
if (testInfo.retry)
await cleanSomeCachesOnTheServer();
// ...
});

用法

testInfo.retry

类型


snapshotDir

新增于: v1.10 testInfo.snapshotDir

此特定测试的快照输出目录的绝对路径。每个测试套件都有自己的目录,因此它们不会冲突。

此属性不考虑 testProject.snapshotPathTemplate 配置。

用法

testInfo.snapshotDir

类型


snapshotSuffix

新增于: v1.10 testInfo.snapshotSuffix
注意

不建议使用 testInfo.snapshotSuffix。请使用 testConfig.snapshotPathTemplate 来配置快照路径。

用于区分多个测试配置之间的快照后缀。例如,如果快照依赖于平台,您可以将 testInfo.snapshotSuffix 设置为 process.platform。在这种情况下,expect(value).toMatchSnapshot(snapshotName) 将根据平台使用不同的快照。了解有关 快照 的更多信息。

用法

testInfo.snapshotSuffix

类型


status

新增于: v1.10 testInfo.status

当前正在运行的测试的实际状态。在测试结束后,可在 test.afterEach() 钩子和 fixture 中使用。

状态通常与 testInfo.expectedStatus 进行比较

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

test.afterEach(async ({}, testInfo) => {
if (testInfo.status !== testInfo.expectedStatus)
console.log(`${testInfo.title} did not run as expected!`);
});

用法

testInfo.status

类型

  • "passed" | "failed" | "timedOut" | "skipped" | "interrupted"

tags

新增于: v1.43 testInfo.tags

适用于测试的标签。了解有关 标签 的更多信息。

注意

在测试运行时对此列表所做的任何更改对测试报告器都不可见。

用法

testInfo.tags

类型


testId

新增于: v1.32 testInfo.testId

与报告器 API 中的测试用例 id 匹配的测试 id。

用法

testInfo.testId

类型


timeout

新增于: v1.10 testInfo.timeout

当前正在运行的测试的超时时间(以毫秒为单位)。零表示没有超时。了解有关 各种超时时间 的更多信息。

超时时间通常在 配置文件 中指定

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

test.beforeEach(async ({ page }, testInfo) => {
// Extend timeout for all tests running this hook by 30 seconds.
testInfo.setTimeout(testInfo.timeout + 30000);
});

用法

testInfo.timeout

类型


title

新增于: v1.10 testInfo.title

作为 test(title, testFunction) 传递的当前正在运行的测试的标题。

用法

testInfo.title

类型


titlePath

新增于: v1.10 testInfo.titlePath

从测试文件名开始的完整标题路径。

用法

testInfo.titlePath

类型


workerIndex

新增于: v1.10 testInfo.workerIndex

运行测试的 worker 进程的唯一索引。当 worker 重启(例如在失败后)时,新的 worker 进程将获得一个新的唯一 workerIndex

也可作为 process.env.TEST_WORKER_INDEX 使用。了解有关使用 Playwright Test 进行 并行和分片(sharding) 的更多信息。

用法

testInfo.workerIndex

类型