Skip to main content

TestInfo

TestInfo 包含有关当前正在运行的测试的信息。它可用于测试函数、test.beforeEach()test.afterEach()test.beforeAll()test.afterAll() 钩子,以及测试范围的夹具。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'));
});

方法

🌐 Methods

attach

Added in: v1.10 testInfo.attach

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

🌐 Attach a value or a file from disk to the current test. Some reporters show test attachments. Either path or body must be specified, but not both.

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

🌐 For example, you can attach a screenshot to the test:

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

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

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

🌐 Or you can attach files returned by your APIs:

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 });
});
note

testInfo.attach() 会自动将附加的文件复制到报告者可以访问的位置。在等待 attach 调用之后,你可以安全地删除附件。

用法

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

参数

  • name string#

    附件名称。名称也会被净化,并在保存到磁盘时用作文件名的前缀。

  • options Object (optional)

    • body string | Buffer (optional)#

      附件正文。与 path 互斥。

    • contentType string (optional)#

      此附件的内容类型应正确显示在报告中,例如 'application/json''image/png'。如果省略,内容类型将根据path推断,或默认为string附件的 text/plainBuffer附件的 application/octet-stream

    • path string (optional)#

      附加文件在文件系统中的路径。与 body 互斥。

返回


fail()

Added in: v1.10 testInfo.fail()

将当前正在运行的测试标记为“应失败”。Playwright 测试会运行此测试并确保它实际上会失败。这对于文档记录很有用,以确认某些功能在修复前仍然存在问题。这类似于 test.fail()

🌐 Marks the currently running test as "should fail". Playwright Test runs this test and ensures that it is actually failing. This is useful for documentation purposes to acknowledge that some functionality is broken until it is fixed. This is similar to test.fail().

用法

testInfo.fail();

fail(condition)

Added in: v1.10 testInfo.fail(condition)

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

🌐 Conditionally mark the currently running test as "should fail" with an optional description. This is similar to test.fail().

用法

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

参数

  • condition boolean#

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

  • description string (optional)#

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


fixme()

Added in: v1.10 testInfo.fixme()

将测试标记为“fixme”,以修复它为目的。测试会立即中止。这与test.fixme()类似。

🌐 Mark a test as "fixme", with the intention to fix it. Test is immediately aborted. This is similar to test.fixme().

用法

testInfo.fixme();

fixme(condition)

Added in: v1.10 testInfo.fixme(condition)

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

🌐 Conditionally mark the currently running test as "fixme" with an optional description. This is similar to test.fixme().

用法

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

参数

  • condition boolean#

    当条件为 true 时,测试被标记为“待修复”。

  • description string (optional)#

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


outputPath

Added in: v1.10 testInfo.outputPath

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

🌐 Returns a path inside the testInfo.outputDir where the test can safely put a temporary file. Guarantees that tests running in parallel will not interfere with each other.

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

Added in: v1.10 testInfo.setTimeout

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

🌐 Changes the timeout for the currently running test. Zero means no timeout. Learn more about various timeouts.

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

🌐 Timeout is usually specified in the configuration file, but it could be useful to change the timeout in certain scenarios:

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()

Added in: v1.10 testInfo.skip()

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

🌐 Unconditionally skip the currently running test. Test is immediately aborted. This is similar to test.skip().

用法

testInfo.skip();

skip(condition)

Added in: v1.10 testInfo.skip(condition)

有条件地跳过当前正在进行的测试,并附带可选描述。这类似于 [test.skip()](/api/class-test.mdx#test-skip)。

🌐 Conditionally skips the currently running test with an optional description. This is similar to test.skip().

用法

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

参数

  • condition boolean#

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

  • description string (optional)#

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


slow()

Added in: v1.10 testInfo.slow()

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

🌐 Marks the currently running test as "slow", giving it triple the default timeout. This is similar to test.slow().

用法

testInfo.slow();

slow(condition)

Added in: v1.10 testInfo.slow(condition)

有条件地将当前正在运行的测试标记为“慢”,并添加可选描述,使其超时时间增加三倍。这类似于 [test.slow()](/api/class-test.mdx#test-slow)。

🌐 Conditionally mark the currently running test as "slow" with an optional description, giving it triple the default timeout. This is similar to test.slow().

用法

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

参数

  • condition boolean#

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

  • description string (optional)#

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


snapshotPath

Added in: v1.10 testInfo.snapshotPath

返回具有给定 name 的快照文件路径。传入 kind 可获取特定路径:

🌐 Returns a path to a snapshot file with the given name. Pass kind to obtain a specific path:

用法

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 (optional)

    • kind "snapshot" | "screenshot" | "aria" (optional) Added in: v1.53#

      快照类型控制使用哪个快照路径模板。有关更多详情,请参见 testConfig.snapshotPathTemplate。默认值为 'snapshot'

返回


属性

🌐 Properties

annotations

Added in: v1.10 testInfo.annotations

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

🌐 The list of annotations applicable to the current test. Includes annotations from the test, annotations from all test.describe() groups the test belongs to and file-level annotations for the test file.

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

🌐 Learn more about test annotations.

用法

testInfo.annotations

类型

  • [数组]<[对象]>
    • type string

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

    • description string (optional)

      可选描述。

    • location Location (optional)

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


attachments

Added in: v1.10 testInfo.attachments

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

🌐 The list of files or buffers attached to the current test. Some reporters show test attachments.

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

🌐 To add an attachment, use testInfo.attach() instead of directly pushing onto this array.

用法

testInfo.attachments

类型

  • [数组]<[对象]>
    • name string

      附件名称。

    • contentType string

      该附件的内容类型,以便在报告中正确呈现,例如 'application/json''image/png'

    • path string (optional)

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

    • body Buffer (optional)

      使用可选附件正文代替文件。


column

Added in: v1.10 testInfo.column

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

🌐 Column number where the currently running test is declared.

用法

testInfo.column

类型


config

Added in: v1.10 testInfo.config

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

🌐 Processed configuration from the configuration file.

用法

testInfo.config

类型


duration

Added in: v1.10 testInfo.duration

测试完成所花费的毫秒数。在测试完成之前,无论是否成功,总是为零。可以在 test.afterEach() 钩子中使用。

🌐 The number of milliseconds the test took to finish. Always zero before the test finishes, either successfully or not. Can be used in test.afterEach() hook.

用法

testInfo.duration

类型


error

Added in: v1.10 testInfo.error

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

🌐 First error thrown during test execution, if any. This is equal to the first element in testInfo.errors.

用法

testInfo.error

类型


errors

Added in: v1.10 testInfo.errors

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

🌐 Errors thrown during test execution, if any.

用法

testInfo.errors

类型

  • [数组]<[测试信息错误]>

expectedStatus

Added in: v1.10 testInfo.expectedStatus

当前运行测试的预期状态。通常是 'passed',除了一些特殊情况:

🌐 Expected status for the currently running test. This is usually 'passed', except for a few cases:

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

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

🌐 Expected status is usually compared with the actual 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

类型

  • "通过" | "未通过" | "超时" | "跳过" | "中断"

file

Added in: v1.10 testInfo.file

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

🌐 Absolute path to a file where the currently running test is declared.

用法

testInfo.file

类型


fn

Added in: v1.10 testInfo.fn

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

🌐 Test function as passed to test(title, testFunction).

用法

testInfo.fn

类型


line

Added in: v1.10 testInfo.line

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

🌐 Line number where the currently running test is declared.

用法

testInfo.line

类型


outputDir

Added in: v1.10 testInfo.outputDir

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

🌐 Absolute path to the output directory for this specific test run. Each test run gets its own directory so they cannot conflict.

用法

testInfo.outputDir

类型


parallelIndex

Added in: v1.10 testInfo.parallelIndex

位于 0workers - 1 之间的工作者索引。保证同时运行的工作者具有不同的 parallelIndex。当工作者重启时,例如在发生故障之后,新的工作者进程具有相同的 parallelIndex

🌐 The index of the worker between 0 and workers - 1. It is guaranteed that workers running at the same time have a different parallelIndex. When a worker is restarted, for example after a failure, the new worker process has the same parallelIndex.

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

🌐 Also available as process.env.TEST_PARALLEL_INDEX. Learn more about parallelism and sharding with Playwright Test.

用法

testInfo.parallelIndex

类型


project

Added in: v1.10 testInfo.project

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

🌐 Processed project configuration from the configuration file.

用法

testInfo.project

类型


repeatEachIndex

Added in: v1.10 testInfo.repeatEachIndex

在“每次重复”模式下运行时指定唯一的重复索引。通过向命令行传递 --repeat-each 可以启用此模式。

🌐 Specifies a unique repeat index when running in "repeat each" mode. This mode is enabled by passing --repeat-each to the command line.

用法

testInfo.repeatEachIndex

类型


retry

Added in: v1.10 testInfo.retry

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

🌐 Specifies the retry number when the test is retried after a failure. The first test run has testInfo.retry equal to zero, the first retry has it equal to one, and so on. Learn more about retries.

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

Added in: v1.10 testInfo.snapshotDir

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

🌐 Absolute path to the snapshot output directory for this specific test. Each test suite gets its own directory so they cannot conflict.

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

🌐 This property does not account for the testProject.snapshotPathTemplate configuration.

用法

testInfo.snapshotDir

类型


snapshotSuffix

Added in: v1.10 testInfo.snapshotSuffix
note

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

🌐 Use of testInfo.snapshotSuffix is discouraged. Please use testConfig.snapshotPathTemplate to configure snapshot paths.

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

🌐 Suffix used to differentiate snapshots between multiple test configurations. For example, if snapshots depend on the platform, you can set testInfo.snapshotSuffix equal to process.platform. In this case expect(value).toMatchSnapshot(snapshotName) will use different snapshots depending on the platform. Learn more about snapshots.

用法

testInfo.snapshotSuffix

类型


status

Added in: v1.10 testInfo.status

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

🌐 Actual status for the currently running test. Available after the test has finished in test.afterEach() hook and fixtures.

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

🌐 Status is usually compared with the 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

类型

  • "通过" | "未通过" | "超时" | "跳过" | "中断"

tags

Added in: v1.43 testInfo.tags

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

🌐 Tags that apply to the test. Learn more about tags.

note

在测试运行期间对该列表所做的任何更改都不会显示给测试报告者。

🌐 Any changes made to this list while the test is running will not be visible to test reporters.

用法

testInfo.tags

类型

  • [数组]<[字符串]>

testId

Added in: v1.32 testInfo.testId

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

🌐 Test id matching the test case id in the reporter API.

用法

testInfo.testId

类型


timeout

Added in: v1.10 testInfo.timeout

当前运行的测试的超时毫秒数。零表示没有超时。了解更多关于各种超时的信息。

🌐 Timeout in milliseconds for the currently running test. Zero means no timeout. Learn more about various timeouts.

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

🌐 Timeout is usually specified in the configuration file

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

Added in: v1.10 testInfo.title

当前正在运行的测试标题已传递给 test(title, testFunction)

🌐 The title of the currently running test as passed to test(title, testFunction).

用法

testInfo.title

类型


titlePath

Added in: v1.10 testInfo.titlePath

以测试文件名开头的完整标题路径。

🌐 The full title path starting with the test file name.

用法

testInfo.titlePath

类型

  • [数组]<[字符串]>

workerIndex

Added in: v1.10 testInfo.workerIndex

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

🌐 The unique index of the worker process that is running the test. When a worker is restarted, for example after a failure, the new worker process gets a new unique workerIndex.

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

🌐 Also available as process.env.TEST_WORKER_INDEX. Learn more about parallelism and sharding with Playwright Test.

用法

testInfo.workerIndex

类型