Skip to main content

TestConfig

Playwright Test 提供了许多选项来配置测试的收集和执行方式,例如 timeouttestDir。这些选项在 配置文件 中的 TestConfig 对象中进行了描述。

Playwright Test provides many options to configure how your tests are collected and executed, for example timeout or testDir. These options are described in the TestConfig object in the configuration file.

Playwright Test 支持同时运行多个测试项目。项目特定的选项应放在 testConfig.projects 中,但顶层 TestConfig 也可以定义所有项目之间共享的基本选项。

Playwright Test supports running multiple test projects at the same time. Project-specific options should be put to testConfig.projects, but top-level TestConfig can also define base options shared between all projects.

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

export default defineConfig({
timeout: 30000,
globalTimeout: 600000,
reporter: 'list',
testDir: './tests',
});

属性

Properties

build

Added in: v1.35 testConfig.build

Playwright 转译器配置。

Playwright transpiler configuration.

用法

Usage

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

export default defineConfig({
build: {
external: ['**/*bundle.js'],
},
});

类型

Type

要从转译中排除的路径,表示为通配符模式列表。此处列出了你的测试使用的典型重型 JS 包。

Paths to exclude from the transpilation expressed as a list of glob patterns. Typically heavy JS bundles that your test uses are listed here.


expect

Added in: v1.10 testConfig.expect

expect 断言库的配置。了解有关 各种超时 的更多信息。

Configuration for the expect assertion library. Learn more about various timeouts.

用法

Usage

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

export default defineConfig({
expect: {
timeout: 10000,
toMatchSnapshot: {
maxDiffPixels: 10,
},
},
});

类型

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.


forbidOnly

Added in: v1.10 testConfig.forbidOnly

如果任何测试或组标记为 test.only()test.describe.only(),是否退出并出错。对 CI 很有用。

Whether to exit with an error if any tests or groups are marked as test.only() or test.describe.only(). Useful on CI.

用法

Usage

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

export default defineConfig({
forbidOnly: !!process.env.CI,
});

类型

Type


fullyParallel

Added in: v1.20 testConfig.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 run to concurrently execute all tests in all files using this option.

用法

Usage

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

export default defineConfig({
fullyParallel: true,
});

类型

Type


globalSetup

Added in: v1.10 testConfig.globalSetup

全局安装文件的路径。在所有测试之前将需要并运行该文件。它必须导出一个带有 [TestConfig] 参数的函数。

Path to the global setup file. This file will be required and run before all the tests. It must export a single function that takes a [TestConfig] argument.

了解有关 全局设置和拆卸 的更多信息。

Learn more about global setup and teardown.

用法

Usage

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

export default defineConfig({
globalSetup: './global-setup',
});

类型

Type


globalTeardown

Added in: v1.10 testConfig.globalTeardown

全局拆卸文件的路径。在所有测试之后将需要并运行该文件。它必须导出单个函数。另见 testConfig.globalSetup

Path to the global teardown file. This file will be required and run after all the tests. It must export a single function. See also testConfig.globalSetup.

了解有关 全局设置和拆卸 的更多信息。

Learn more about global setup and teardown.

用法

Usage

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

export default defineConfig({
globalTeardown: './global-teardown',
});

类型

Type


globalTimeout

Added in: v1.10 testConfig.globalTimeout

整个测试套件可以运行的最长时间(以毫秒为单位)。零超时(默认)禁用此行为。在 CI 上很有用,可以防止损坏的设置运行太长时间并浪费资源。了解有关 各种超时 的更多信息。

Maximum time in milliseconds the whole test suite can run. Zero timeout (default) disables this behavior. Useful on CI to prevent broken setup from running too long and wasting resources. Learn more about various timeouts.

用法

Usage

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

export default defineConfig({
globalTimeout: process.env.CI ? 60 * 60 * 1000 : undefined,
});

类型

Type


grep

Added in: v1.10 testConfig.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 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

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

export default defineConfig({
grep: /smoke/,
});

类型

Type


grepInvert

Added in: v1.10 testConfig.grepInvert

过滤以仅运行标题与其中一种模式不匹配的测试。这与 testConfig.grep 相反。命令行 也提供 --grep-invert 选项。

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

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

grepInvert option is also useful for tagging tests.

用法

Usage

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

export default defineConfig({
grepInvert: /manual/,
});

类型

Type


ignoreSnapshots

Added in: v1.26 testConfig.ignoreSnapshots

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

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

用法

Usage

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

export default defineConfig({
ignoreSnapshots: !process.env.CI,
});

类型

Type


maxFailures

Added in: v1.10 testConfig.maxFailures

整个测试套件运行的最大测试失败次数。达到此数字后,测试将停止并退出并出现错误。设置为零(默认)会禁用此行为。

The maximum number of test failures for the whole test suite run. After reaching this number, testing will stop and exit with an error. Setting to zero (default) disables this behavior.

还提供 命令行 以及 --max-failures-x 选项。

Also available in the command line with the --max-failures and -x options.

用法

Usage

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

export default defineConfig({
maxFailures: process.env.CI ? 1 : 0,
});

类型

Type


metadata

Added in: v1.10 testConfig.metadata

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

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

用法

Usage

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

export default defineConfig({
metadata: 'acceptance tests',
});

类型

Type

  • [元数据]

    [Metadata]


name

Added in: v1.10 testConfig.name

配置名称在报告中和测试执行期间可见,除非被 testProject.name 覆盖。

Config name is visible in the report and during test execution, unless overridden by testProject.name.

用法

Usage

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

export default defineConfig({
name: 'acceptance tests',
});

类型

Type


outputDir

Added in: v1.10 testConfig.outputDir

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

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

用法

Usage

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

export default defineConfig({
outputDir: './test-results',
});

类型

Type

细节

Details

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

This directory is cleaned at the start. When running a test, a unique subdirectory inside the testConfig.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');
});

preserveOutput

Added in: v1.10 testConfig.preserveOutput

是否将测试输出保存在 testConfig.outputDir。默认为 'always'

Whether to preserve test output in the testConfig.outputDir. Defaults to 'always'.

  • 'always' - 保留所有测试的输出;

    'always' - preserve output for all tests;

  • 'never' - 不保留任何测试的输出;

    'never' - do not preserve output for any tests;

  • 'failures-only' - 只保留失败测试的输出。

    'failures-only' - only preserve output for failed tests.

用法

Usage

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

export default defineConfig({
preserveOutput: 'always',
});

类型

Type

  • "always"|"never"|"failures-only"

projects

Added in: v1.10 testConfig.projects

Playwright Test 支持同时运行多个测试项目。请参阅 TestProject 了解更多信息。

Playwright Test supports running multiple test projects at the same time. See TestProject for more information.

用法

Usage

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

export default defineConfig({
projects: [
{ name: 'chromium', use: devices['Desktop Chrome'] }
]
});

类型

Type


quiet

Added in: v1.10 testConfig.quiet

是否抑制测试中的 stdio 和 stderr 输出。

Whether to suppress stdio and stderr output from the tests.

用法

Usage

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

export default defineConfig({
quiet: !!process.env.CI,
});

类型

Type


repeatEach

Added in: v1.10 testConfig.repeatEach

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

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

用法

Usage

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

export default defineConfig({
repeatEach: 3,
});

类型

Type


reportSlowTests

Added in: v1.10 testConfig.reportSlowTests

是否报告慢速测试文件。通过 null 禁用此功能。

Whether to report slow test files. Pass null to disable this feature.

用法

Usage

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

export default defineConfig({
reportSlowTests: null,
});

类型

Type

要报告的慢速测试文件的最大数量。默认为 5

The maximum number of slow test files to report. Defaults to 5.

测试持续时间(以毫秒为单位)被认为是缓慢的。默认为 15 秒。

Test duration in milliseconds that is considered slow. Defaults to 15 seconds.

细节

Details

花费超过 threshold 毫秒的测试文件被认为是慢的,并且报告最慢的文件,不超过 max 个。传递零作为 max 报告超过阈值的所有测试文件。

Test files that took more than threshold milliseconds are considered slow, and the slowest ones are reported, no more than max number of them. Passing zero as max reports all test files that exceed the threshold.


reporter

Added in: v1.10 testConfig.reporter

使用的报告器名单。每个报告器可以是:

The list of reporters to use. Each reporter can be:

  • 内置报告者名称,例如 'list''json'

    A builtin reporter name like 'list' or 'json'.

  • 模块名称如 'my-awesome-reporter'

    A module name like 'my-awesome-reporter'.

  • 报告器的相对路径,如 './reporters/my-awesome-reporter.js'

    A relative path to the reporter like './reporters/my-awesome-reporter.js'.

你可以通过像 ['json', { outputFile: './report.json' }] 这样的元组将选项传递给报告者。

You can pass options to the reporter in a tuple like ['json', { outputFile: './report.json' }].

报告器指南 中了解更多信息。

Learn more in the reporters guide.

用法

Usage

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

export default defineConfig({
reporter: 'line',
});

类型

Type

|"list"|"dot"|"line"|"github"|"json"|"junit"|"null"|"html"

报告器名称或模块或文件路径

Reporter name or module or file path

具有报告器选项的对象(如果有)

An object with reporter options if any


retries

Added in: v1.10 testConfig.retries

失败测试的最大重试次数。默认情况下,不会重试失败的测试。了解有关 测试重试 的更多信息。

The maximum number of retry attempts given to failed tests. By default failing tests are not retried. Learn more about test retries.

用法

Usage

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

export default defineConfig({
retries: 2,
});

类型

Type


shard

Added in: v1.10 testConfig.shard

分片测试并仅执行选定的分片。以基于 1 的形式指定,例如 { total: 5, current: 2 }

Shard tests and execute only the selected shard. Specify in the one-based form like { total: 5, current: 2 }.

通过 Playwright 测试了解有关 并行性和分片 的更多信息。

Learn more about parallelism and sharding with Playwright Test.

用法

Usage

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

export default defineConfig({
shard: { total: 10, current: 3 },
});

类型

Type

分片总数。

The total number of shards.

要执行的分片的索引,从一开始。

The index of the shard to execute, one-based.


snapshotPathTemplate

Added in: v1.28 testConfig.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.


testDir

Added in: v1.10 testConfig.testDir

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

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

用法

Usage

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

export default defineConfig({
testDir: './tests/playwright',
});

类型

Type


testIgnore

Added in: v1.10 testConfig.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.

用法

Usage

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

export default defineConfig({
testIgnore: '**/test-assets/**',
});

类型

Type


testMatch

Added in: v1.10 testConfig.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.

用法

Usage

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

export default defineConfig({
testMatch: /.*\.e2e\.js/,
});

类型

Type


timeout

Added in: v1.10 testConfig.timeout

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

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

这是所有测试的基本超时。此外,每个测试都可以使用 test.setTimeout() 配置自己的超时。了解有关 各种超时 的更多信息。

This is a base timeout for all tests. In addition, each test can configure its own timeout with test.setTimeout(). Learn more about various timeouts.

用法

Usage

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

export default defineConfig({
timeout: 5 * 60 * 1000,
});

类型

Type


updateSnapshots

Added in: v1.10 testConfig.updateSnapshots

是否用测试运行产生的实际结果更新预期快照。默认为 'missing'

Whether to update expected snapshots with the actual results produced by the test run. Defaults to 'missing'.

  • 'all' - 执行的所有测试都将更新不匹配的快照。匹配的快照将不会更新。

    'all' - All tests that are executed will update snapshots that did not match. Matching snapshots will not be updated.

  • 'none' - 没有更新任何快照。

    'none' - No snapshots are updated.

  • 'missing' - 例如,在编写新测试并首次运行它时,会创建丢失的快照。这是默认设置。

    'missing' - Missing snapshots are created, for example when authoring a new test and running it for the first time. This is the default.

了解有关 snapshots 的更多信息。

Learn more about snapshots.

用法

Usage

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

export default defineConfig({
updateSnapshots: 'missing',
});

类型

Type

  • "all"|"none"|"missing"

use

Added in: v1.10 testConfig.use

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

Global options for all tests, for example testOptions.browserName. Learn more about configuration and see available options.

用法

Usage

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

export default defineConfig({
use: {
browserName: 'chromium',
},
});

类型

Type


webServer

Added in: v1.10 testConfig.webServer

在测试期间启动一个(或多个)开发 Web 服务器。

Launch a development web server (or multiple) during the tests.

用法

Usage

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
use: {
baseURL: 'http://localhost:3000/',
},
});

现在你可以在导航页面时使用相对路径:

Now you can use a relative path when navigating the page:

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

test('test', async ({ page }) => {
// This will result in http://localhost:3000/foo
await page.goto('/foo');
});

可以启动多个 Web 服务器(或后台进程):

Multiple web servers (or background processes) can be launched:

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://127.0.0.1:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://127.0.0.1:3333',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://127.0.0.1:3000',
},
});

类型

Type

Shell 命令启动。例如 npm run start..

Shell command to start. For example npm run start..

你的 http 服务器预计出现的端口。它会等待直到接受连接。应指定 porturl

The port that your http server is expected to appear on. It does wait until it accepts connections. Either port or url should be specified.

当服务器准备好接受连接时,http 服务器上的 url 预计会返回 2xx、3xx、400、401、402 或 403 状态代码。正在遵循重定向(3xx 状态代码)并检查新位置。应指定 porturl

The url on your http server that is expected to return a 2xx, 3xx, 400, 401, 402, or 403 status code when the server is ready to accept connections. Redirects (3xx status codes) are being followed and the new location is checked. Either port or url should be specified.

  • ignoreHTTPSErrors boolean (optional)

获取 url 时是否忽略 HTTPS 错误。默认为 false

Whether to ignore HTTPS errors when fetching the url. Defaults to false.

等待进程启动并可用的时间(以毫秒为单位)。默认为 60000。

How long to wait for the process to start up and be available in milliseconds. Defaults to 60000.

  • reuseExistingServer boolean (optional)

如果为 true,它将重新使用 porturl 上的现有服务器(如果可用)。如果该 porturl 上没有运行服务器,它将运行命令来启动新服务器。如果是 false,如果现有进程正在监听 porturl,则会抛出异常。通常应将其设置为 !process.env.CI,以在本地运行测试时允许本地开发服务器。

If true, it will re-use an existing server on the port or url when available. If no server is running on that port or url, it will run the command to start a new server. If false, it will throw if an existing process is listening on the port or url. This should be commonly set to !process.env.CI to allow the local dev server when running tests locally.

  • stdout "pipe"|"ignore"(可选)

    stdout "pipe"|"ignore" (optional)

    如果是 "pipe",它将通过管道将命令的标准输出传输到进程标准输出。如果是 "ignore",它将忽略命令的标准输出。默认为 "ignore"

    If "pipe", it will pipe the stdout of the command to the process stdout. If "ignore", it will ignore the stdout of the command. Default to "ignore".

  • stderr "pipe"|"ignore"(可选)

    stderr "pipe"|"ignore" (optional)

    是否将命令的 stderr 通过管道传输到进程 stderr 或忽略它。默认为 "pipe"

    Whether to pipe the stderr of the command to the process stderr or ignore it. Defaults to "pipe".

生成进程的当前工作目录,默认为配置文件的目录。

Current working directory of the spawned process, defaults to the directory of the configuration file.

为命令设置的环境变量,默认为 process.env

Environment variables to set for the command, process.env by default.

细节

Details

如果指定了端口,Playwright Test 将等待该端口在 127.0.0.1::1 上可用,然后再运行测试。如果指定了 url,Playwright Test 将等待该 URL 返回 2xx、3xx、400、401、402 或 403 状态代码,然后再运行测试。

If the port is specified, Playwright Test will wait for it to be available on 127.0.0.1 or ::1, before running the tests. If the url is specified, Playwright Test will wait for the URL to return a 2xx, 3xx, 400, 401, 402, or 403 status code before running the tests.

对于持续集成,你可能需要使用 reuseExistingServer: !process.env.CI 选项,该选项不使用 CI 上的现有服务器。要查看标准输出,你可以设置 DEBUG=pw:webserver 环境变量。

For continuous integration, you may want to use the reuseExistingServer: !process.env.CI option which does not use an existing server on the CI. To see the stdout, you can set the DEBUG=pw:webserver environment variable.

port(但不是 url)作为 testOptions.baseURL 传递给 Playwright。例如,端口 8080 产生的 baseURL 等于 http://localhost:8080。如果 webServer 指定为数组,则必须显式配置 baseURL(即使它只有一个条目)。

The port (but not the url) gets passed over to Playwright as a testOptions.baseURL. For example port 8080 produces baseURL equal http://localhost:8080. If webServer is specified as an array, you must explicitly configure the baseURL (even if it only has one entry).

注意

还建议在配置中指定 testOptions.baseURL,以便测试可以使用相对 url。

It is also recommended to specify testOptions.baseURL in the config, so that tests could use relative urls.


workers

Added in: v1.10 testConfig.workers

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

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

Playwright Test 使用工作进程来运行测试。始终至少有一个工作进程,但可以使用更多工作进程来加快测试执行速度。

Playwright Test uses worker processes to run tests. There is always at least one worker process, but more can be used to speed up test execution.

默认为逻辑 CPU 核心数的一半。通过 Playwright 测试了解有关 并行性和分片 的更多信息。

Defaults to half of the number of logical CPU cores. Learn more about parallelism and sharding with Playwright Test.

用法

Usage

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

export default defineConfig({
workers: 3,
});

类型

Type


已弃用

Deprecated

snapshotDir

Added in: v1.10 testConfig.snapshotDir
劝阻

使用 testConfig.snapshotPathTemplate 配置快照路径。

Use testConfig.snapshotPathTemplate to configure snapshot paths.

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

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

用法

Usage

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

export default defineConfig({
snapshotDir: './snapshots',
});

类型

Type

细节

Details

每个测试的目录可由 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.