Skip to main content

TestProject

Playwright Test 支持同时运行多个测试项目。这对于在多种配置下运行测试非常有用。例如,考虑对多个浏览器进行测试。这种类型描述了配置文件中项目的格式,要在运行时访问已解析的配置参数,可以使用 FullProject

🌐 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. This type describes format of a project in the configuration file, to access resolved configuration parameters at run time use FullProject.

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

以下是在 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.

用法

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'],
},
],
});

类型

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

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.

用法

testProject.expect

类型

  • Object
    • timeout number (optional)

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

    • toHaveScreenshot Object (optional)

      • threshold number (optional)

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

      • maxDiffPixels number (optional)

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

      • maxDiffPixelRatio number (optional)

        可接受的像素差异比例,即不同像素与总像素的比例,介于 01 之间,默认未设置。

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

        请参见 animationspage.screenshot() 中。默认值为 "disabled"

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

        请参见 caretpage.screenshot() 中。默认值为 "hide"

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

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

      • stylePath string | Array<string> (optional)

        请参见 stylepage.screenshot() 中。

      • pathTemplate string (optional)

        一个控制截图位置的模板。详情请参见 testProject.snapshotPathTemplate

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

    • toMatchAriaSnapshot Object (optional)

      expect(locator).toMatchAriaSnapshot() 方法的配置。

    • toMatchSnapshot Object (optional)

      • threshold number (optional)

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

      • maxDiffPixels number (optional)

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

      • maxDiffPixelRatio number (optional)

        可接受的像素差异比例,即不同像素与总像素的比例,介于 01 之间,默认未设置。

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

    • toPass Object (optional)

      • timeout number (optional)

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

      • intervals Array<number> (optional)

        toPass 方法的探测间隔(以毫秒为单位)。

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


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.

用法

testProject.fullyParallel

类型


grep

Added in: v1.10 testProject.grep

过滤以仅运行标题匹配某个模式的测试。例如,传入 grep: /cart/ 应该只运行标题中包含 “cart” 的测试。该功能也可在全局范围和命令行中通过 -g 选项使用。正则表达式将针对由项目名称、测试文件名、test.describe 名称(如果有)、测试名称以及以空格分隔的测试标签组成的字符串进行测试,例如 chromium 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 project name, the test file name, the test.describe name (if any), the test name and the test tags divided by spaces, e.g. chromium my-test.spec.ts my-suite my-test.

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

用法

testProject.grep

类型

  • [正则表达式] | [数组]<[正则表达式]>

grepInvert

Added in: v1.10 testProject.grepInvert

仅运行标题符合任何模式的测试。这与testProject.grep相反。也可以在全局范围内以及通过--grep-invert选项在命令行中使用。

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

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

用法

testProject.grepInvert

类型

  • [正则表达式] | [数组]<[正则表达式]>

ignoreSnapshots

Added in: v1.44 testProject.ignoreSnapshots

是否跳过快照期望,例如 expect(value).toMatchSnapshot()await expect(page).toHaveScreenshot()

🌐 Whether to skip snapshot expectations, such as expect(value).toMatchSnapshot() and await expect(page).toHaveScreenshot().

用法

以下示例将仅在 Chromium 上执行屏幕截图断言。

🌐 The following example will only perform screenshot assertions on Chromium.

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

export default defineConfig({
projects: [
{
name: 'chromium',
use: devices['Desktop Chrome'],
},
{
name: 'firefox',
use: devices['Desktop Firefox'],
ignoreSnapshots: true,
},
{
name: 'webkit',
use: devices['Desktop Safari'],
ignoreSnapshots: true,
},
],
});

类型


metadata

Added in: v1.10 testProject.metadata

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

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

用法

testProject.metadata

类型


name

Added in: v1.10 testProject.name

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

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

warning

Playwright 会多次执行配置文件。不要在配置中动态生成不稳定的值。

🌐 Playwright executes the configuration file multiple times. Do not dynamically produce non-stable values in your configuration.

用法

testProject.name

类型


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](/api/class-testconfig.mdx#test-config-output-dir) 来更改所有项目的这个选项。

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

用法

testProject.outputDir

类型


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.

用法

testProject.repeatEach

类型


respectGitIgnore

Added in: v1.45 testProject.respectGitIgnore

在搜索测试文件时是否跳过来自 .gitignore 的条目。默认情况下,如果未明确指定 testConfig.testDirtestProject.testDir,Playwright 将忽略任何匹配 .gitignore 条目的测试文件。此选项允许覆盖该行为。

🌐 Whether to skip entries from .gitignore when searching for test files. By default, if neither testConfig.testDir nor testProject.testDir are explicitly specified, Playwright will ignore any test files matching .gitignore entries. This option allows to override that behavior.

用法

testProject.respectGitIgnore

类型


retries

Added in: v1.10 testProject.retries

给予失败测试的最大重试次数。了解有关test 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.

用法

testProject.retries

类型


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.

用法

testProject.snapshotDir

类型


snapshotPathTemplate

Added in: v1.28 testProject.snapshotPathTemplate

此选项配置一个模板,用于控制由 expect(page).toHaveScreenshot()expect(locator).toMatchAriaSnapshot()expect(value).toMatchSnapshot() 生成的快照的位置。

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

你可以在testConfig.expect中为每个断言单独配置模板。

🌐 You can configure templates for each assertion separately in testConfig.expect.

用法

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

export default defineConfig({
testDir: './tests',

// Single template for all assertions
snapshotPathTemplate: '{testDir}/__screenshots__/{testFilePath}/{arg}{ext}',

// Assertion-specific templates
expect: {
toHaveScreenshot: {
pathTemplate: '{testDir}/__screenshots__{/projectName}/{testFilePath}/{arg}{ext}',
},
toMatchAriaSnapshot: {
pathTemplate: '{testDir}/__snapshots__/{testFilePath}/{arg}{ext}',
},
},
});

类型

详情

该值可能包含一些“令牌”,这些令牌将在测试执行过程中被实际值替换。

🌐 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:

  • {arg} - 相对快照路径 不带扩展名。这是从传递给 toHaveScreenshot()toMatchAriaSnapshot()toMatchSnapshot() 的参数中得到的;如果在没有参数的情况下调用,将会生成一个自动的快照名称。
    • 值:foo/bar/baz
  • {ext} - 快照扩展名(带前导点)。
    • 值:.png
  • {platform} - process.platform 的值。
  • {projectName} - 项目的文件系统安全名称(如果有的话)。
    • 值:''(空字符串)。
  • {snapshotDir} - 项目的 testProject.snapshotDir
    • 值:/home/playwright/tests(由于配置中未提供 snapshotDir,因此默认为 testDir
  • {testDir} - 项目的testProject.testDir
    • 值:/home/playwright/tests(绝对路径,因为 testDir 是相对于配置所在目录解析的)
  • {testFileDir} - testDir测试文件 的相对路径目录。
    • 值:page
  • {testFileName} - 带扩展名的测试文件名。
    • 值:page-click.spec.ts
  • {testFilePath} - 从 testDir测试文件 的相对路径。
    • 价值:“page/page-click.spec.ts”
  • {testName} - 经过文件系统清理的测试标题,包括父描述,但不包括文件名。
    • 值:suite-test-should-work

每个标记前都可以加一个字符,仅当该标记有非空值时使用。

🌐 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/... 中。
  2. 第二个项目确实有一个名字,因此它的快照将存储在 <configDir>/__screenshots__/chromium/example.spec.ts/..
  3. 由于 snapshotPathTemplate 解析为相对路径,它将相对于 configDir 进行解析。
  4. 正斜杠 "/" 可以在任何平台上用作路径分隔符。

teardown

Added in: v1.34 testProject.teardown

在此项目及所有依赖目完成后需要运行的项目名称。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.

用法

一个常见的模式是一个“设置”依赖,它有一个对应的“拆除”

🌐 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'],
},
],
});

类型


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.

用法

testProject.testDir

类型


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.

用法

testProject.testIgnore

类型

  • [字符串] | [正则表达式] | [数组]<[字符串] | [正则表达式]>

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 会查找匹配以下通配符模式的文件:**/*.@(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.

用法

testProject.testMatch

类型

  • [字符串] | [正则表达式] | [数组]<[字符串] | [正则表达式]>

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.

用法

testProject.timeout

类型


use

Added in: v1.10 testProject.use

此项目中所有测试的选项,例如 testOptions.browserName。了解有关 配置 的更多信息,并查看 可用选项

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

用法

testProject.use

类型


workers

Added in: v1.52 testProject.workers

用于并行化此项目测试的最大并发工作进程数。也可以设置为逻辑 CPU 核心的百分比,例如 '50%'.

🌐 The maximum number of concurrent worker processes to use for parallelizing tests from this project. Can also be set as percentage of logical CPU cores, e.g. '50%'.

例如,当一个项目的所有测试共享一个资源(如测试账户)时,这可能会很有用,因此不能并行执行。将此类项目的工作进程限制为一个,可以防止同时使用共享资源。

🌐 This could be useful, for example, when all tests from a project share a single resource like a test account, and therefore cannot be executed in parallel. Limiting workers to one for such a project will prevent simultaneous use of the shared resource.

请注意,全局 testConfig.workers 限制适用于工作进程的总数。然而,Playwright 会根据 testProject.workers 的值限制此项目使用的工作进程数量。

🌐 Note that the global testConfig.workers limit applies to the total number of worker processes. However, Playwright will limit the number of workers used for this project by the value of testProject.workers.

默认情况下,每个项目没有限制。请参阅 testConfig.workers 了解总工作进程限制的默认值。

🌐 By default, there is no limit per project. See testConfig.workers for the default of the total worker limit.

用法

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

export default defineConfig({
workers: 10, // total workers limit

projects: [
{
name: 'runs in parallel',
},
{
name: 'one at a time',
workers: 1, // workers limit for this project
},
],
});

类型

  • [数字] | [字符串]