跳到主要内容

TestProject

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

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

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

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

属性

dependencies

新增于:v1.31 testProject.dependencies

在此项目中的任何测试运行之前需要运行的项目列表。依赖项可用于以测试形式配置全局 setup 操作。传递 --no-deps 参数将忽略依赖项,并表现得如同未指定一样。

使用依赖项允许全局 setup 生成 traces 和其他 artifacts,在测试报告中查看 setup 步骤等。

用法

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

新增于:v1.10 testProject.expect

expect 断言库的配置。

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

用法

testProject.expect

类型

  • Object
    • timeout number (可选)

      异步 expect matchers 的默认超时时间(毫秒),默认为 5000 毫秒。

    • toHaveScreenshot Object (可选)

      • threshold number (可选)

        比较图像中同一像素可接受的感知颜色差异,范围从 0(严格)到 1(宽松)。"pixelmatch" 比较器计算 YIQ 颜色空间 的颜色差异,并默认为 threshold0.2

      • maxDiffPixels number (可选)

        可接受的不同像素数量,默认为未设置。

      • maxDiffPixelRatio number (可选)

        不同像素数量占总像素数量的可接受比例,介于 01 之间,默认为未设置。

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

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

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

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

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

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

      • stylePath string | Array<string> (可选)

        参见 page.screenshot() 中的 style

      • pathTemplate string (可选)

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

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

    • toMatchAriaSnapshot Object (可选)

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

    • toMatchSnapshot Object (可选)

      • threshold number (可选)

        比较图像中同一像素可接受的感知颜色差异,范围从 0(严格)到 1(宽松)。"pixelmatch" 比较器计算 YIQ 颜色空间 的颜色差异,并默认为 threshold0.2

      • maxDiffPixels number (可选)

        可接受的不同像素数量,默认为未设置。

      • maxDiffPixelRatio number (可选)

        不同像素数量占总像素数量的可接受比例,介于 01 之间,默认为未设置。

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

    • toPass Object (可选)

      • timeout number (可选)

        toPass 方法的超时时间(毫秒)。

      • intervals Array<number> (可选)

        toPass 方法的探测间隔(毫秒)。

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


fullyParallel

新增于:v1.10 testProject.fullyParallel

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

您可以使用此选项配置整个测试项目,以并发运行所有文件中的所有测试。

用法

testProject.fullyParallel

类型


grep

新增于:v1.10 testProject.grep

过滤,只运行标题匹配其中一个模式的测试。例如,传入 grep: /cart/ 应仅运行标题中包含“cart”的测试。也可通过全局设置和命令行中的 -g 选项使用。正则表达式将针对由项目名称、测试文件名称、test.describe 名称(如果存在)、测试名称和测试标签组成的字符串进行测试,这些名称和标签用空格分隔,例如 chromium my-test.spec.ts my-suite my-test

grep 选项也适用于 标记测试

用法

testProject.grep

类型


grepInvert

新增于:v1.10 testProject.grepInvert

过滤,只运行标题匹配其中一个模式的测试。这与 testProject.grep 相反。也可通过全局设置和命令行中的 --grep-invert 选项使用。

grepInvert 选项也适用于 标记测试

用法

testProject.grepInvert

类型


ignoreSnapshots

新增于:v1.44 testProject.ignoreSnapshots

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

用法

以下示例将只在 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

新增于:v1.10 testProject.metadata

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

用法

testProject.metadata

类型


name

新增于:v1.10 testProject.name

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

警告

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

用法

testProject.name

类型


outputDir

新增于:v1.10 testProject.outputDir

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

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

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

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 更改所有项目的此选项。

用法

testProject.outputDir

类型


repeatEach

新增于:v1.10 testProject.repeatEach

重复每个测试的次数,对于调试不稳定测试很有用。

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

用法

testProject.repeatEach

类型


respectGitIgnore

新增于:v1.45 testProject.respectGitIgnore

搜索测试文件时是否跳过 .gitignore 中的条目。默认情况下,如果既未显式指定 testConfig.testDir 也未显式指定 testProject.testDir,Playwright 将忽略任何与 .gitignore 条目匹配的测试文件。此选项允许覆盖该行为。

用法

testProject.respectGitIgnore

类型


retries

新增于:v1.10 testProject.retries

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

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

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

用法

testProject.retries

类型


snapshotDir

新增于:v1.10 testProject.snapshotDir

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

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

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

用法

testProject.snapshotDir

类型


snapshotPathTemplate

新增于:v1.28 testProject.snapshotPathTemplate

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

您可以在 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}',
},
},
});

类型

详情

该值可能包含一些“token”,这些 token 将在测试执行期间被实际值替换。

考虑以下文件结构

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

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

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

支持的 token 列表

  • {arg} - 相对快照路径,不带扩展名。这来自传递给 toHaveScreenshot()toMatchAriaSnapshot()toMatchSnapshot() 的参数;如果调用时不带参数,这将是一个自动生成的快照名称。
    • 值: foo/bar/baz
  • {ext} - 快照扩展名(带前导点)。
    • 值: .png
  • {platform} - process.platform 的值。
  • {projectName} - 项目的文件系统净化名称(如果存在)。
    • 值: ''(空字符串)。
  • {snapshotDir} - 项目的 testProject.snapshotDir
    • 值: /home/playwright/tests(由于 config 中未提供 snapshotDir,因此默认为 testDir
  • {testDir} - 项目的 testProject.testDir
    • 值: /home/playwright/tests(绝对路径,因为 testDir 是相对于 config 文件所在的目录解析的)
  • {testFileDir} - 从 testDir测试文件的相对路径中的目录。
    • 值: page
  • {testFileName} - 带扩展名的测试文件名。
    • 值: page-click.spec.ts
  • {testFilePath} - 从 testDir测试文件的相对路径。
    • 值: page/page-click.spec.ts
  • {testName} - 文件系统净化后的测试标题,包含父 describes 但不包含文件名。
    • 值: suite-test-should-work

每个 token 前面可以带有一个字符,该字符仅在此 token 具有非空值时使用。

考虑以下配置

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

在此配置中

  1. 第一个项目没有名称,因此其快照将存储在 <configDir>/__screenshots__/example.spec.ts/... 中。
  2. 第二个项目有名称,因此其快照将存储在 <configDir>/__screenshots__/chromium/example.spec.ts/.. 中。
  3. 由于 snapshotPathTemplate 解析为相对路径,它将相对于 configDir 解析。
  4. 正斜杠 "/" 可在任何平台上用作路径分隔符。

teardown

新增于:v1.34 testProject.teardown

在此项目和所有依赖项目完成后需要运行的项目的名称。Teardown 可用于清理此项目获取的任何资源。

传入 --no-deps 参数会忽略 testProject.teardown,并表现得如同未指定一样。

用法

一种常见的模式是具有对应“teardown”的“setup”依赖项

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

新增于:v1.10 testProject.testDir

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

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

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 更改所有项目的此选项。

用法

testProject.testDir

类型


testIgnore

新增于:v1.10 testProject.testIgnore

匹配其中一个模式的文件不会作为测试文件执行。匹配是针对绝对文件路径执行的。字符串被视为 glob 模式。

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

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

用法

testProject.testIgnore

类型


testMatch

新增于:v1.10 testProject.testMatch

只有匹配其中一个模式的文件才会作为测试文件执行。匹配是针对绝对文件路径执行的。字符串被视为 glob 模式。

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

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

用法

testProject.testMatch

类型


timeout

新增于:v1.10 testProject.timeout

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

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

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

用法

testProject.timeout

类型


use

新增于:v1.10 testProject.use

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

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

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

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

用法

testProject.use

类型


workers

新增于:v1.52 testProject.workers

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

这可能很有用,例如,当项目中的所有测试共享一个资源(如测试账户),因此无法并行执行时。

请注意,全局 testConfig.workers 限制适用于 worker 进程的总数。但是,Playwright 会将此项目使用的 worker 数量限制为 testProject.workers 的值。

默认情况下,每个项目没有限制。请参见 testConfig.workers 了解总 worker 限制的默认值。

用法

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

类型