Skip to main content

TestInfo

TestInfo 包含有关当前正在运行的测试的信息。它可用于测试功能、test.beforeEach()test.afterEach()test.beforeAll()test.afterAll() 钩子以及测试范围的夹具。TestInfo 提供了控制测试执行的实用程序:附加文件、更新测试超时、确定当前正在运行哪个测试以及是否重试等。

¥TestInfo contains information about currently running test. It is available to test functions, test.beforeEach(), test.afterEach(), test.beforeAll() and test.afterAll() hooks, and test-scoped fixtures. TestInfo provides utilities to control test execution: attach files, update test timeout, determine which test is currently running and whether it was retried, etc.

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 });
});
注意

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

¥testInfo.attach() automatically takes care of copying attached files to a location that is accessible to reporters. You can safely remove the attachment after awaiting the attach call.

用法

¥Usage

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

参数

¥Arguments

附件名称。保存到磁盘时,该名称也将被清理并用作文件名的前缀。

¥Attachment name. The name will also be sanitized and used as the prefix of file name when saving to disk.

附件体。与 path 互斥。

¥Attachment body. Mutually exclusive with path.

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

¥Content type of this attachment to properly present in the report, for example 'application/json' or 'image/png'. If omitted, content type is inferred based on the path, or defaults to text/plain for string attachments and application/octet-stream for Buffer attachments.

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

¥Path on the filesystem to the attached file. Mutually exclusive with body.

返回

¥Returns


fail()

Added in: v1.10 testInfo.fail()

将当前运行的测试标记为 "应该失败"。Playwright Test 运行此测试并确保它确实失败。这对于文档目的很有用,可以确认某些功能在修复之前已损坏。这与 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().

用法

¥Usage

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

用法

¥Usage

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

参数

¥Arguments

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

¥Test is marked as "should fail" when the condition is true.

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

¥Optional description that will be reflected in a test report.


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

用法

¥Usage

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

用法

¥Usage

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

参数

¥Arguments

当条件为 true 时,测试标记为 "fixme"。

¥Test is marked as "fixme" when the condition is true.

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

¥Optional description that will be reflected in a test report.


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),否则会抛出异常。

¥Note that pathSegments accepts path segments to the test output directory such as testInfo.outputPath('relative', 'path', 'to', 'output'). However, this path must stay within the testInfo.outputDir directory for each test (i.e. test-results/a-test-title), otherwise it will throw.

用法

¥Usage

testInfo.outputPath(...pathSegments);

参数

¥Arguments

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

¥Path segments to append at the end of the resulting path.

返回

¥Returns


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

用法

¥Usage

testInfo.setTimeout(timeout);

参数

¥Arguments

超时(以毫秒为单位)。

¥Timeout in milliseconds.


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

用法

¥Usage

testInfo.skip();

skip(condition)

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

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

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

用法

¥Usage

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

参数

¥Arguments

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

¥A skip condition. Test is skipped when the condition is true.

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

¥Optional description that will be reflected in a test report.


slow()

Added in: v1.10 testInfo.slow()

将当前运行的测试标记为 "slow",为其提供默认超时的三倍。这与 test.slow() 类似。

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

用法

¥Usage

testInfo.slow();

slow(condition)

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

有条件地将当前运行的测试标记为 "slow",并带有可选描述,为其提供三倍的默认超时。这与 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().

用法

¥Usage

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

参数

¥Arguments

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

¥Test is marked as "slow" when the condition is true.

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

¥Optional description that will be reflected in a test report.


snapshotPath

Added in: v1.10 testInfo.snapshotPath

返回具有给定 pathSegments 的快照文件的路径。了解有关 snapshots 的更多信息。

¥Returns a path to a snapshot file with the given pathSegments. Learn more about snapshots.

请注意,pathSegments 接受快照文件的路径段,例如 testInfo.snapshotPath('relative', 'path', 'to', 'snapshot.png')。但是,此路径必须保留在每个测试文件(即 a.spec.js-snapshots)的快照目录中,否则会抛出异常。

¥Note that pathSegments accepts path segments to the snapshot file such as testInfo.snapshotPath('relative', 'path', 'to', 'snapshot.png'). However, this path must stay within the snapshots directory for each test file (i.e. a.spec.js-snapshots), otherwise it will throw.

用法

¥Usage

testInfo.snapshotPath(...pathSegments);

参数

¥Arguments

快照的名称或定义快照文件路径的路径段。同一测试文件中具有相同名称的快照应该是相同的。

¥The name of the snapshot or the path segments to define the snapshot file path. Snapshots with the same name in the same test file are expected to be the same.

返回

¥Returns


属性

¥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.

用法

¥Usage

testInfo.annotations

类型

¥Type

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

¥Annotation type, for example 'skip' or 'fail'.

  • description string (optional)

可选描述。

¥Optional description.


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.

用法

¥Usage

testInfo.attachments

类型

¥Type

附件名称。

¥Attachment name.

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

¥Content type of this attachment to properly present in the report, for example 'application/json' or 'image/png'.

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

¥Optional path on the filesystem to the attached file.

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

¥Optional attachment body used instead of a file.


column

Added in: v1.10 testInfo.column

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

¥Column number where the currently running test is declared.

用法

¥Usage

testInfo.column

类型

¥Type


config

Added in: v1.10 testInfo.config

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

¥Processed configuration from the configuration file.

用法

¥Usage

testInfo.config

类型

¥Type


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.

用法

¥Usage

testInfo.duration

类型

¥Type


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.

用法

¥Usage

testInfo.error

类型

¥Type


errors

Added in: v1.10 testInfo.errors

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

¥Errors thrown during test execution, if any.

用法

¥Usage

testInfo.errors

类型

¥Type


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

    ¥'skipped' for skipped tests, e.g. with test.skip();

  • 'failed' 用于标记为失败并带有 test.fail() 的测试。

    ¥'failed' for tests marked as failed with 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!`);
});

用法

¥Usage

testInfo.expectedStatus

类型

¥Type

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

file

Added in: v1.10 testInfo.file

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

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

用法

¥Usage

testInfo.file

类型

¥Type


fn

Added in: v1.10 testInfo.fn

测试函数传递给 test(title, testFunction)

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

用法

¥Usage

testInfo.fn

类型

¥Type


line

Added in: v1.10 testInfo.line

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

¥Line number where the currently running test is declared.

用法

¥Usage

testInfo.line

类型

¥Type


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.

用法

¥Usage

testInfo.outputDir

类型

¥Type


parallelIndex

Added in: v1.10 testInfo.parallelIndex

0workers - 1 之间的工作线程的索引。保证同时运行的 worker 有不同的 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 测试了解有关 并行性和分片 的更多信息。

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

用法

¥Usage

testInfo.parallelIndex

类型

¥Type


project

Added in: v1.10 testInfo.project

已处理 配置文件 中的项目配置。

¥Processed project configuration from the configuration file.

用法

¥Usage

testInfo.project

类型

¥Type


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.

用法

¥Usage

testInfo.repeatEachIndex

类型

¥Type


retry

Added in: v1.10 testInfo.retry

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

¥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();
// ...
});

用法

¥Usage

testInfo.retry

类型

¥Type


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.

用法

¥Usage

testInfo.snapshotDir

类型

¥Type


snapshotSuffix

Added in: v1.10 testInfo.snapshotSuffix
注意

不鼓励使用 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) 将根据平台使用不同的快照。了解有关 snapshots 的更多信息。

¥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.

用法

¥Usage

testInfo.snapshotSuffix

类型

¥Type


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!`);
});

用法

¥Usage

testInfo.status

类型

¥Type

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

tags

Added in: v1.43 testInfo.tags

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

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

请注意,测试运行时对此列表所做的任何更改对于测试报告者来说都是不可见的。

¥Note that any changes made to this list while the test is running will not be visible to test reporters.

用法

¥Usage

testInfo.tags

类型

¥Type


testId

Added in: v1.32 testInfo.testId

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

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

用法

¥Usage

testInfo.testId

类型

¥Type


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

用法

¥Usage

testInfo.timeout

类型

¥Type


title

Added in: v1.10 testInfo.title

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

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

用法

¥Usage

testInfo.title

类型

¥Type


titlePath

Added in: v1.10 testInfo.titlePath

从项目开始的完整标题路径。

¥The full title path starting with the project.

用法

¥Usage

testInfo.titlePath

类型

¥Type


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 测试了解有关 并行性和分片 的更多信息。

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

用法

¥Usage

testInfo.workerIndex

类型

¥Type