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将一个值或磁盘上的文件附加到当前测试。一些报告工具会显示测试附件。必须指定 path 或 body 中的一个,但不能同时指定两者。
🌐 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() 会自动将附加的文件复制到报告者可以访问的位置。在等待 attach 调用之后,你可以安全地删除附件。
用法
await testInfo.attach(name);
await testInfo.attach(name, options);
参数
-
附件名称。名称也会被净化,并在保存到磁盘时用作文件名的前缀。
-
optionsObject (optional)
返回
fail()
Added in: v1.10将当前正在运行的测试标记为“应失败”。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有条件地将当前正在运行的测试标记为“应该失败”,并可添加可选描述。这类似于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);
参数
fixme()
Added in: v1.10将测试标记为“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有条件地将当前正在运行的测试标记为“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);
参数
outputPath
Added in: v1.10返回 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);
参数
返回
setTimeout
Added in: v1.10更改当前正在运行的测试的超时时间。零表示没有超时。了解更多关于各种超时的信息。
🌐 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);
参数
skip()
Added in: v1.10无条件跳过当前正在运行的测试。测试会立即中止。这类似于 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有条件地跳过当前正在进行的测试,并附带可选描述。这类似于 [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);
参数
slow()
Added in: v1.10将当前正在运行的测试标记为“慢”,使其超时时间为默认值的三倍。这类似于 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有条件地将当前正在运行的测试标记为“慢”,并添加可选描述,使其超时时间增加三倍。这类似于 [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);
参数
snapshotPath
Added in: v1.10返回具有给定 name 的快照文件路径。传入 kind 可获取特定路径:
🌐 Returns a path to a snapshot file with the given name. Pass kind to obtain a specific path:
kind: 'screenshot'用于 expect(page).toHaveScreenshot();kind: 'aria'用于 expect(locator).toMatchAriaSnapshot();kind: 'snapshot'用于 expect(value).toMatchSnapshot()。
用法
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');
参数
-
快照的名称或用于定义快照文件路径的路径段。在同一个测试文件中,具有相同名称的快照应当相同。
在传递 kind 时,不支持多个名称段。
-
optionsObject (optional)-
kind"snapshot" | "screenshot" | "aria" (optional) Added in: v1.53#快照类型控制使用哪个快照路径模板。有关更多详情,请参见 testConfig.snapshotPathTemplate。默认值为
'snapshot'。
-
返回
属性
🌐 Properties
annotations
Added in: v1.10适用于当前测试的注释列表。包括来自该测试的注释、测试所属的所有 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
类型
- [数组]<[对象]>
attachments
Added in: v1.10附加到当前测试的文件或缓冲区列表。一些报告程序会显示测试附件。
🌐 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
类型
- [数组]<[对象]>
column
Added in: v1.10声明当前正在运行的测试的列号。
🌐 Column number where the currently running test is declared.
用法
testInfo.column
类型
config
Added in: v1.10已处理来自配置文件的配置。
🌐 Processed configuration from the configuration file.
用法
testInfo.config
类型
duration
Added in: v1.10测试完成所花费的毫秒数。在测试完成之前,无论是否成功,总是为零。可以在 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.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测试执行期间抛出的错误(如果有)。
🌐 Errors thrown during test execution, if any.
用法
testInfo.errors
类型
- [数组]<[测试信息错误]>
expectedStatus
Added in: v1.10当前运行测试的预期状态。通常是 '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声明当前正在运行的测试的文件的绝对路径。
🌐 Absolute path to a file where the currently running test is declared.
用法
testInfo.file
类型
fn
Added in: v1.10作为传给 test(title, testFunction) 的测试函数。
🌐 Test function as passed to test(title, testFunction).
用法
testInfo.fn
类型
line
Added in: v1.10声明当前正在运行的测试的行号。
🌐 Line number where the currently running test is declared.
用法
testInfo.line
类型
outputDir
Added in: v1.10该特定测试运行的输出目录的绝对路径。每次测试运行都有自己的目录,因此它们不会相互冲突。
🌐 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位于 0 和 workers - 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已处理来自配置文件的项目配置。
🌐 Processed project configuration from the configuration file.
用法
testInfo.project
类型
repeatEachIndex
Added in: v1.10在“每次重复”模式下运行时指定唯一的重复索引。通过向命令行传递 --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 等于零,第一次重试等于一,依此类推。了解更多关于 重试 的信息。
🌐 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该特定测试的快照输出目录的绝对路径。每个测试套件都有自己的目录,因此它们不会冲突。
🌐 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。请使用 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当前正在运行的测试的实际状态。在测试结束后,可在 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适用于测试的标签。了解更多关于标签的信息。
🌐 Tags that apply to the test. Learn more about tags.
在测试运行期间对该列表所做的任何更改都不会显示给测试报告者。
🌐 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测试 ID 与报告器 API 中的测试用例 ID 匹配。
🌐 Test id matching the test case id in the reporter API.
用法
testInfo.testId
类型
timeout
Added in: v1.10当前运行的测试的超时毫秒数。零表示没有超时。了解更多关于各种超时的信息。
🌐 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当前正在运行的测试标题已传递给 test(title, testFunction)。
🌐 The title of the currently running test as passed to test(title, testFunction).
用法
testInfo.title
类型
titlePath
Added in: v1.10以测试文件名开头的完整标题路径。
🌐 The full title path starting with the test file name.
用法
testInfo.titlePath
类型
- [数组]<[字符串]>
workerIndex
Added in: v1.10正在运行测试的工作进程的唯一索引。例如,当工作进程在失败后重启时,新的工作进程将获得一个新的唯一 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
类型