Skip to main content

TestProject

Playwright Test 支持同时运行多个测试项目。这对于在多种配置中运行测试非常有用。例如,考虑针对多个浏览器运行测试。

¥Playwright Test supports running multiple test projects at the same time. This is useful for running tests in multiple configurations. For example, consider running tests against multiple browsers.

TestProject 封装了特定于单个项目的配置。项目在 配置文件 中指定的 testConfig.projects 中配置。请注意,TestProject 的所有属性在顶层 TestConfig 中均可用,在这种情况下,它们在所有项目之间共享。

¥TestProject encapsulates configuration specific to a single project. Projects are configured in testConfig.projects specified in the configuration file. Note that all properties of TestProject are available in the top-level TestConfig, in which case they are shared between all projects.

以下是在 Chromium、Firefox 和 WebKit(桌面版和移动版)中运行每个测试的示例配置。

¥Here is an example configuration that runs every test in Chromium, Firefox and WebKit, both Desktop and Mobile versions.

playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
// Options shared for all projects.
timeout: 30000,
use: {
ignoreHTTPSErrors: true,
},

// Options specific to each project.
projects: [
{
name: 'chromium',
use: devices['Desktop Chrome'],
},
{
name: 'firefox',
use: devices['Desktop Firefox'],
},
{
name: 'webkit',
use: devices['Desktop Safari'],
},
{
name: 'Mobile Chrome',
use: devices['Pixel 5'],
},
{
name: 'Mobile Safari',
use: devices['iPhone 12'],
},
],
});

属性

¥Properties

dependencies

Added in: v1.31 testProject.dependencies

在该项目中的任何测试运行之前需要运行的项目列表。依赖对于配置全局设置操作非常有用,因为每个操作都是测试的形式。传递 --no-deps 参数会忽略依赖,其行为就像未指定它们一样。

¥List of projects that need to run before any test in this project runs. Dependencies can be useful for configuring the global setup actions in a way that every action is in a form of a test. Passing --no-deps argument ignores the dependencies and behaves as if they were not specified.

使用依赖允许全局设置生成跟踪和其他工件,请参阅测试报告中的设置步骤等。

¥Using dependencies allows global setup to produce traces and other artifacts, see the setup steps in the test report, etc.

用法

¥Usage

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /global.setup\.ts/,
},
{
name: 'chromium',
use: devices['Desktop Chrome'],
dependencies: ['setup'],
},
{
name: 'firefox',
use: devices['Desktop Firefox'],
dependencies: ['setup'],
},
{
name: 'webkit',
use: devices['Desktop Safari'],
dependencies: ['setup'],
},
],
});

类型

¥Type


expect

Added in: v1.10 testProject.expect

expect 断言库的配置。

¥Configuration for the expect assertion library.

使用 testConfig.expect 为所有项目更改此选项。

¥Use testConfig.expect to change this option for all projects.

用法

¥Usage

testProject.expect

类型

¥Type

异步期望匹配器的默认超时(以毫秒为单位),默认为 5000 毫秒。

¥Default timeout for async expect matchers in milliseconds, defaults to 5000ms.

  • toHaveScreenshot Object (optional)

比较图片中相同像素之间可接受的感知色差,范围从 0(严格)到 1(宽松)。"pixelmatch" 比较器计算 YIQ 色彩空间 中的色差,并将 threshold 值默认为 0.2

¥an acceptable perceived color difference between the same pixel in compared images, ranging from 0 (strict) and 1 (lax). "pixelmatch" comparator computes color difference in YIQ color space and defaults threshold value to 0.2.

  • maxDiffPixels number (optional)

可接受的像素数量,可能不同,默认情况下未设置。

¥an acceptable amount of pixels that could be different, unset by default.

  • maxDiffPixelRatio number (optional)

与像素总数不同的可接受的像素比率,介于 01 之间,默认情况下未设置。

¥an acceptable ratio of pixels that are different to the total amount of pixels, between 0 and 1 , unset by default.

  • animations "allow"|"disabled"(可选)

    ¥animations "allow"|"disabled" (optional)

    参见 page.screenshot() 中的 animations。默认为 "disabled"

    ¥See animations in page.screenshot(). Defaults to "disabled".

  • caret "hide"|"initial"(可选)

    ¥caret "hide"|"initial" (optional)

    参见 page.screenshot() 中的 caret。默认为 "hide"

    ¥See caret in page.screenshot(). Defaults to "hide".

  • scale "css"|"device"(可选)

    ¥scale "css"|"device" (optional)

    参见 page.screenshot() 中的 scale。默认为 "css"

    ¥See scale in page.screenshot(). Defaults to "css".

参见 page.screenshot() 中的 style

¥See style in page.screenshot().

expect(page).toHaveScreenshot() 方法的配置。

¥Configuration for the expect(page).toHaveScreenshot() method.

  • toMatchSnapshot Object (optional)

比较图片中相同像素之间可接受的感知色差,范围从 0(严格)到 1(宽松)。"pixelmatch" 比较器计算 YIQ 色彩空间 中的色差,并将 threshold 值默认为 0.2

¥an acceptable perceived color difference between the same pixel in compared images, ranging from 0 (strict) and 1 (lax). "pixelmatch" comparator computes color difference in YIQ color space and defaults threshold value to 0.2.

  • maxDiffPixels number (optional)

可接受的像素数量,可能不同,默认情况下未设置。

¥an acceptable amount of pixels that could be different, unset by default.

  • maxDiffPixelRatio number (optional)

与像素总数不同的可接受的像素比率,介于 01 之间,默认情况下未设置。

¥an acceptable ratio of pixels that are different to the total amount of pixels, between 0 and 1 , unset by default.

expect(value).toMatchSnapshot() 方法的配置。

¥Configuration for the expect(value).toMatchSnapshot() method.

toPass 方法的超时时间(以毫秒为单位)。

¥timeout for toPass method in milliseconds.

expect(value).toPass() 方法的配置。

¥Configuration for the expect(value).toPass() method.


fullyParallel

Added in: v1.10 testProject.fullyParallel

Playwright Test 并行运行测试。为了实现这一点,它运行多个同时运行的工作进程。默认情况下,测试文件并行运行。单个文件中的测试在同一工作进程中按顺序运行。

¥Playwright Test runs tests in parallel. In order to achieve that, it runs several worker processes that run at the same time. By default, test files are run in parallel. Tests in a single file are run in order, in the same worker process.

你可以使用此选项将整个测试项目配置为同时运行所有文件中的所有测试。

¥You can configure entire test project to concurrently run all tests in all files using this option.

用法

¥Usage

testProject.fullyParallel

类型

¥Type


grep

Added in: v1.10 testProject.grep

过滤以仅运行标题与其中一种模式匹配的测试。例如,通过 grep: /cart/ 应该只运行标题中包含 "cart" 的测试。也适用于全局以及带有 -g 选项的 命令行。正则表达式将针对由测试文件名、test.describe 名称(如果有)和由空格分隔的测试名称组成的字符串进行测试,例如 my-test.spec.ts my-suite my-test

¥Filter to only run tests with a title matching one of the patterns. For example, passing grep: /cart/ should only run tests with "cart" in the title. Also available globally and in the command line with the -g option. The regular expression will be tested against the string that consists of the test file name, test.describe name (if any) and the test name divided by spaces, e.g. my-test.spec.ts my-suite my-test.

grep 选项对于 标记测试 也很有用。

¥grep option is also useful for tagging tests.

用法

¥Usage

testProject.grep

类型

¥Type


grepInvert

Added in: v1.10 testProject.grepInvert

过滤以仅运行标题与其中一种模式不匹配的测试。这与 testProject.grep 相反。也适用于全局以及带有 --grep-invert 选项的 命令行

¥Filter to only run tests with a title not matching one of the patterns. This is the opposite of testProject.grep. Also available globally and in the command line with the --grep-invert option.

grepInvert 选项对于 标记测试 也很有用。

¥grepInvert option is also useful for tagging tests.

用法

¥Usage

testProject.grepInvert

类型

¥Type


metadata

Added in: v1.10 testProject.metadata

将直接放入序列化为 JSON 的测试报告中的元数据。

¥Metadata that will be put directly to the test report serialized as JSON.

用法

¥Usage

testProject.metadata

类型

¥Type


name

Added in: v1.10 testProject.name

项目名称在报告中和测试执行期间可见。

¥Project name is visible in the report and during test execution.

用法

¥Usage

testProject.name

类型

¥Type


outputDir

Added in: v1.10 testProject.outputDir

测试执行期间创建的文件的输出目录。默认为 <package.json-directory>/test-results

¥The output directory for files created during test execution. Defaults to <package.json-directory>/test-results.

该目录在开始时被清理。运行测试时,会在 testProject.outputDir 内创建一个唯一的子目录,保证并行运行的测试不会发生冲突。该目录可由 testInfo.outputDirtestInfo.outputPath() 访问。

¥This directory is cleaned at the start. When running a test, a unique subdirectory inside the testProject.outputDir is created, guaranteeing that test running in parallel do not conflict. This directory can be accessed by testInfo.outputDir and testInfo.outputPath().

下面是使用 testInfo.outputPath() 创建临时文件的示例。

¥Here is an example that uses testInfo.outputPath() to create a temporary file.

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

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

使用 testConfig.outputDir 为所有项目更改此选项。

¥Use testConfig.outputDir to change this option for all projects.

用法

¥Usage

testProject.outputDir

类型

¥Type


repeatEach

Added in: v1.10 testProject.repeatEach

重复每个测试的次数,对于调试片状测试很有用。

¥The number of times to repeat each test, useful for debugging flaky tests.

使用 testConfig.repeatEach 为所有项目更改此选项。

¥Use testConfig.repeatEach to change this option for all projects.

用法

¥Usage

testProject.repeatEach

类型

¥Type


retries

Added in: v1.10 testProject.retries

失败测试的最大重试次数。了解有关 测试重试 的更多信息。

¥The maximum number of retry attempts given to failed tests. Learn more about test retries.

使用 test.describe.configure() 更改特定文件或一组测试的重试次数。

¥Use test.describe.configure() to change the number of retries for a specific file or a group of tests.

使用 testConfig.retries 为所有项目更改此选项。

¥Use testConfig.retries to change this option for all projects.

用法

¥Usage

testProject.retries

类型

¥Type


snapshotDir

Added in: v1.10 testProject.snapshotDir

相对于配置文件的基本目录,用于使用 toMatchSnapshot 创建的快照文件。默认为 testProject.testDir

¥The base directory, relative to the config file, for snapshot files created with toMatchSnapshot. Defaults to testProject.testDir.

每个测试的目录可由 testInfo.snapshotDirtestInfo.snapshotPath() 访问。

¥The directory for each test can be accessed by testInfo.snapshotDir and testInfo.snapshotPath().

该路径将作为每个测试文件快照目录的基目录。将 snapshotDir 设置为 'snapshots'testInfo.snapshotDir 将解析为 snapshots/a.spec.js-snapshots

¥This path will serve as the base directory for each test file snapshot directory. Setting snapshotDir to 'snapshots', the testInfo.snapshotDir would resolve to snapshots/a.spec.js-snapshots.

用法

¥Usage

testProject.snapshotDir

类型

¥Type


snapshotPathTemplate

Added in: v1.28 testProject.snapshotPathTemplate

此选项配置控制 expect(page).toHaveScreenshot()expect(value).toMatchSnapshot() 生成的快照位置的模板。

¥This option configures a template controlling location of snapshots generated by expect(page).toHaveScreenshot() and expect(value).toMatchSnapshot().

用法

¥Usage

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
testDir: './tests',
snapshotPathTemplate: '{testDir}/__screenshots__/{testFilePath}/{arg}{ext}',
});

类型

¥Type

细节

¥Details

该值可能包括一些 "tokens",这些 "tokens" 将在测试执行期间替换为实际值。

¥The value might include some "tokens" that will be replaced with actual values during test execution.

考虑以下文件结构:

¥Consider the following file structure:

playwright.config.ts
tests/
└── page/
└── page-click.spec.ts

以及以下使用 toHaveScreenshot() 调用的 page-click.spec.ts

¥And the following page-click.spec.ts that uses toHaveScreenshot() call:

page-click.spec.ts
import { test, expect } from '@playwright/test';

test.describe('suite', () => {
test('test should work', async ({ page }) => {
await expect(page).toHaveScreenshot(['foo', 'bar', 'baz.png']);
});
});

支持的令牌列表:

¥The list of supported tokens:

  • {testDir} - 项目 testConfig.testDir

    ¥{testDir} - Project's testConfig.testDir.

    • 值:/home/playwright/tests(绝对路径是因为 testDir 是相对于配置目录进行解析的)

      ¥Value: /home/playwright/tests (absolute path is since testDir is resolved relative to directory with config)

  • {snapshotDir} - 项目 testConfig.snapshotDir

    ¥{snapshotDir} - Project's testConfig.snapshotDir.

    • 值:/home/playwright/tests(由于配置中未提供 snapshotDir,因此默认为 testDir

      ¥Value: /home/playwright/tests (since snapshotDir is not provided in config, it defaults to testDir)

  • {platform} - process.platform 的值。

    ¥{platform} - The value of process.platform.

  • {projectName} - 项目的文件系统清理名称(如果有)。

    ¥{projectName} - Project's file-system-sanitized name, if any.

    • 值:''(空字符串)。

      ¥Value: '' (empty string).

  • {testFileDir} - 从 testDir 到测试文件的相对路径中的目录。

    ¥{testFileDir} - Directories in relative path from testDir to test file.

    • 值:page

      ¥Value: page

  • {testFileName} - 带扩展名的测试文件名。

    ¥{testFileName} - Test file name with extension.

    • 值:page-click.spec.ts

      ¥Value: page-click.spec.ts

  • {testFilePath} - 从 testDir 到测试文件的相对路径

    ¥{testFilePath} - Relative path from testDir to test file

    • 值:page/page-click.spec.ts

      ¥Value: page/page-click.spec.ts

  • {testName} - 文件系统清理的测试标题,包括父描述但不包括文件名。

    ¥{testName} - File-system-sanitized test title, including parent describes but excluding file name.

    • 值:suite-test-should-work

      ¥Value: suite-test-should-work

  • {arg} - 不带扩展名的相对快照路径。这些来自传递给 toHaveScreenshot()toMatchSnapshot() 调用的参数;如果不带参数调用,这将是自动生成的快照名称。

    ¥{arg} - Relative snapshot path without extension. These come from the arguments passed to the toHaveScreenshot() and toMatchSnapshot() calls; if called without arguments, this will be an auto-generated snapshot name.

    • 值:foo/bar/baz

      ¥Value: foo/bar/baz

  • {ext} - 快照扩展名(带点)

    ¥{ext} - snapshot extension (with dots)

    • 值:.png

      ¥Value: .png

每个标记前面可以有一个字符,仅当该标记具有非空值时才会使用该字符。

¥Each token can be preceded with a single character that will be used only if this token has non-empty value.

考虑以下配置:

¥Consider the following config:

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
snapshotPathTemplate: '__screenshots__{/projectName}/{testFilePath}/{arg}{ext}',
testMatch: 'example.spec.ts',
projects: [
{ use: { browserName: 'firefox' } },
{ name: 'chromium', use: { browserName: 'chromium' } },
],
});

在此配置中:

¥In this config:

  1. 第一个项目没有名称,因此它的快照将存储在 <configDir>/__screenshots__/example.spec.ts/... 中。

    ¥First project does not have a name, so its snapshots will be stored in <configDir>/__screenshots__/example.spec.ts/....

  2. 第二个项目确实有名称,因此它的快照将存储在 <configDir>/__screenshots__/chromium/example.spec.ts/.. 中。

    ¥Second project does have a name, so its snapshots will be stored in <configDir>/__screenshots__/chromium/example.spec.ts/...

  3. 由于 snapshotPathTemplate 解析为相对路径,因此它将相对于 configDir 进行解析。

    ¥Since snapshotPathTemplate resolves to relative path, it will be resolved relative to configDir.

  4. 正斜杠 "/" 可以在任何平台上用作路径分隔符。

    ¥Forward slashes "/" can be used as path separators on any platform.


teardown

Added in: v1.34 testProject.teardown

此项目和所有依赖目完成后需要运行的项目的名称。拆卸对于清理该项目获取的任何资源很有用。

¥Name of a project that needs to run after this and all dependent projects have finished. Teardown is useful to cleanup any resources acquired by this project.

传递 --no-deps 参数会忽略 testProject.teardown,其行为就像未指定一样。

¥Passing --no-deps argument ignores testProject.teardown and behaves as if it was not specified.

用法

¥Usage

常见模式是具有相应 "teardown" 的 "setup" 依赖:

¥A common pattern is a "setup" dependency that has a corresponding "teardown":

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /global.setup\.ts/,
teardown: 'teardown',
},
{
name: 'teardown',
testMatch: /global.teardown\.ts/,
},
{
name: 'chromium',
use: devices['Desktop Chrome'],
dependencies: ['setup'],
},
{
name: 'firefox',
use: devices['Desktop Firefox'],
dependencies: ['setup'],
},
{
name: 'webkit',
use: devices['Desktop Safari'],
dependencies: ['setup'],
},
],
});

类型

¥Type


testDir

Added in: v1.10 testProject.testDir

将递归扫描测试文件的目录。默认为配置文件的目录。

¥Directory that will be recursively scanned for test files. Defaults to the directory of the configuration file.

每个项目可以使用不同的目录。以下示例在三个浏览器中运行冒烟测试,并在稳定的 Chrome 浏览器中运行所有其他测试。

¥Each project can use a different directory. Here is an example that runs smoke tests in three browsers and all other tests in stable Chrome browser.

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'Smoke Chromium',
testDir: './smoke-tests',
use: {
browserName: 'chromium',
}
},
{
name: 'Smoke WebKit',
testDir: './smoke-tests',
use: {
browserName: 'webkit',
}
},
{
name: 'Smoke Firefox',
testDir: './smoke-tests',
use: {
browserName: 'firefox',
}
},
{
name: 'Chrome Stable',
testDir: './',
use: {
browserName: 'chromium',
channel: 'chrome',
}
},
],
});

使用 testConfig.testDir 为所有项目更改此选项。

¥Use testConfig.testDir to change this option for all projects.

用法

¥Usage

testProject.testDir

类型

¥Type


testIgnore

Added in: v1.10 testProject.testIgnore

与这些模式之一匹配的文件不会作为测试文件执行。匹配是针对绝对文件路径执行的。字符串被视为通配符模式。

¥Files matching one of these patterns are not executed as test files. Matching is performed against the absolute file path. Strings are treated as glob patterns.

例如,'**/test-assets/**' 将忽略 test-assets 目录中的任何文件。

¥For example, '**/test-assets/**' will ignore any files in the test-assets directory.

使用 testConfig.testIgnore 为所有项目更改此选项。

¥Use testConfig.testIgnore to change this option for all projects.

用法

¥Usage

testProject.testIgnore

类型

¥Type


testMatch

Added in: v1.10 testProject.testMatch

只有与这些模式之一匹配的文件才会作为测试文件执行。匹配是针对绝对文件路径执行的。字符串被视为通配符模式。

¥Only the files matching one of these patterns are executed as test files. Matching is performed against the absolute file path. Strings are treated as glob patterns.

默认情况下,Playwright 会查找与以下 glob 模式匹配的文件:**/*.@(spec|test).?(c|m)[jt]s?(x)。这意味着带有 ".test"".spec" 后缀的 JavaScript 或 TypeScript 文件,例如 login-screen.wrong-credentials.spec.ts

¥By default, Playwright looks for files matching the following glob pattern: **/*.@(spec|test).?(c|m)[jt]s?(x). This means JavaScript or TypeScript files with ".test" or ".spec" suffix, for example login-screen.wrong-credentials.spec.ts.

使用 testConfig.testMatch 为所有项目更改此选项。

¥Use testConfig.testMatch to change this option for all projects.

用法

¥Usage

testProject.testMatch

类型

¥Type


timeout

Added in: v1.10 testProject.timeout

每个测试的超时时间(以毫秒为单位)。默认为 30 秒。

¥Timeout for each test in milliseconds. Defaults to 30 seconds.

这是所有测试的基本超时。每个测试都可以使用 test.setTimeout() 配置自己的超时。每个文件或一组测试都可以使用 test.describe.configure() 配置超时。

¥This is a base timeout for all tests. Each test can configure its own timeout with test.setTimeout(). Each file or a group of tests can configure the timeout with test.describe.configure().

使用 testConfig.timeout 为所有项目更改此选项。

¥Use testConfig.timeout to change this option for all projects.

用法

¥Usage

testProject.timeout

类型

¥Type


use

Added in: v1.10 testProject.use

该项目中所有测试的选项,例如 testOptions.browserName。了解有关 configuration 的更多信息并参见 可用选项

¥Options for all tests in this project, for example testOptions.browserName. Learn more about configuration and see available options.

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
projects: [
{
name: 'Chromium',
use: {
browserName: 'chromium',
},
},
],
});

使用 testConfig.use 为所有项目更改此选项。

¥Use testConfig.use to change this option for all projects.

用法

¥Usage

testProject.use

类型

¥Type