TestConfig
Playwright Test 提供了许多选项来配置测试的收集和执行方式,例如 timeout 或 testDir。这些选项在 配置文件 中的 TestConfig 对象中进行了描述。该类型描述了配置文件的格式,要在运行时访问已解析的配置参数,请使用 FullConfig。
🌐 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. This type describes format of the configuration file, to access resolved configuration parameters at run time use FullConfig.
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.
import { defineConfig } from '@playwright/test';
export default defineConfig({
timeout: 30000,
globalTimeout: 600000,
reporter: 'list',
testDir: './tests',
});
属性
🌐 Properties
build
Added in: v1.35Playwright 转译器配置。
🌐 Playwright transpiler configuration.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
build: {
external: ['**/*bundle.js'],
},
});
类型
captureGitInfo
Added in: v1.51这些设置控制是否捕获并存储 git 信息到配置 testConfig.metadata 中。
🌐 These settings control whether git information is captured and stored in the config testConfig.metadata.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
captureGitInfo: { commit: true, diff: true }
});
类型
详情
- 在你希望在 HTML(或第三方)报告中查看
commit信息时,捕获它是非常有用的。 - 获取
diff信息有助于用实际的源差异丰富报告。这些信息可以用于提供有关如何修复测试的智能建议。
这些设置的默认值取决于环境。当测试作为 CI 的一部分运行且可以安全获取 git 信息时,默认值为 true,否则为 false。
🌐 Default values for these settings depend on the environment. When tests run as a part of CI where it is safe to obtain git information, the default value is true, false otherwise.
:::
git 提交元数据的结构可能会发生变化。
expect
Added in: v1.10expect 断言库的配置。了解有关各种超时的更多信息。
🌐 Configuration for the expect assertion library. Learn more about various timeouts.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
expect: {
timeout: 10000,
toMatchSnapshot: {
maxDiffPixels: 10,
},
},
});
类型
- Object
-
timeoutnumber (optional)异步期望匹配器的默认超时(以毫秒为单位),默认为 5000 毫秒。
-
toHaveScreenshotObject (optional)-
animations"allow" | "disabled" (optional)请参见 animations 在 page.screenshot() 中。默认值为
"disabled"。 -
caret"hide" | "initial" (optional)请参见 caret 在 page.screenshot() 中。默认值为
"hide"。 -
maxDiffPixelsnumber (optional)可接受的像素数量,可能不同,默认情况下未设置。
-
maxDiffPixelRationumber (optional)可接受的像素差异比例,即不同像素数与总像素数的比值,介于
0和1之间,默认未设置。 -
scale"css" | "device" (optional)请参见 page.screenshot() 中的 scale。默认值为
"css"。 -
stylePathstring | Array<string> (optional)请参见 style 在 page.screenshot() 中。
-
thresholdnumber (optional)在比较图片中同一像素之间可接受的感知颜色差异,范围从
0(严格)到1(宽松)。"pixelmatch"比较器在 YIQ 颜色空间 中计算颜色差异,并将threshold值默认设置为0.2。 -
pathTemplatestring (optional)一个控制截图位置的模板。详情请参见 testConfig.snapshotPathTemplate。
[expect(page).toHaveScreenshot()] 方法的配置。
-
-
toMatchAriaSnapshotObject (optional)-
pathTemplatestring (optional)一个控制 aria 快照位置的模板。详情请参见 testConfig.snapshotPathTemplate。
-
-
toMatchSnapshotObject (optional) -
toPassObject (optional)-
intervalsArray<number> (optional)以毫秒为单位探测 toPass 方法的间隔。
-
timeoutnumber (optional)toPass 方法的超时时间(以毫秒为单位)。
expect(value).toPass() 方法的配置。
-
-
failOnFlakyTests
Added in: v1.52如果有任何测试被标记为不稳定,是否退出并报错。在持续集成中很有用。
🌐 Whether to exit with an error if any tests are marked as flaky. Useful on CI.
也可以在命令行中使用 --fail-on-flaky-tests 选项。
🌐 Also available in the command line with the --fail-on-flaky-tests option.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
failOnFlakyTests: !!process.env.CI,
});
类型
forbidOnly
Added in: v1.10如果有任何测试或分组被标记为 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
forbidOnly: !!process.env.CI,
});
类型
fullyParallel
Added in: v1.20Playwright 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
fullyParallel: true,
});
类型
globalSetup
Added in: v1.10全局设置文件的路径。此文件将在所有测试之前被调用并运行。它必须导出一个接收 FullConfig 参数的单一函数。传入路径数组可以指定多个全局设置文件。
🌐 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 FullConfig argument. Pass an array of paths to specify multiple global setup files.
了解更多关于全局设置和拆解的信息。
🌐 Learn more about global setup and teardown.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
globalSetup: './global-setup',
});
类型
- [字符串] | [数组]<[字符串]>
globalTeardown
Added in: v1.10全局清理文件的路径。该文件将在所有测试完成后被引入并执行。它必须导出一个函数。另请参见 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. Pass an array of paths to specify multiple global teardown files.
了解更多关于全局设置和拆解的信息。
🌐 Learn more about global setup and teardown.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
globalTeardown: './global-teardown',
});
类型
- [字符串] | [数组]<[字符串]>
globalTimeout
Added in: v1.10整个测试套件可以运行的最长时间(以毫秒为单位)。零超时(默认值)会禁用此行为。在持续集成(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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
globalTimeout: process.env.CI ? 60 * 60 * 1000 : undefined,
});
类型
grep
Added in: v1.10筛选以仅运行标题与某个模式匹配的测试。例如,传入 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 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 选项对于 标记测试 也很有用。
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
grep: /smoke/,
});
类型
- [正则表达式] | [数组]<[正则表达式]>
grepInvert
Added in: v1.10仅筛选运行标题不符合某个模式的测试。这与 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 选项对于 标记测试 也很有用。
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
grepInvert: /manual/,
});
类型
- [正则表达式] | [数组]<[正则表达式]>
ignoreSnapshots
Added in: v1.26是否跳过快照期望,例如 expect(value).toMatchSnapshot() 和 await expect(page).toHaveScreenshot()。
🌐 Whether to skip snapshot expectations, such as expect(value).toMatchSnapshot() and await expect(page).toHaveScreenshot().
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
ignoreSnapshots: !process.env.CI,
});
类型
maxFailures
Added in: v1.10整个测试套件运行时允许的最大测试失败次数。达到此次数后,测试将停止并以错误退出。设置为零(默认值)则禁用此行为。
🌐 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
maxFailures: process.env.CI ? 1 : 0,
});
类型
metadata
Added in: v1.10元数据包含要包含在报告中的键值对。例如,JSON 报告将包含序列化为 JSON 的元数据。
🌐 Metadata contains key-value pairs to be included in the report. For example, the JSON report will include metadata serialized as JSON.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
metadata: { title: 'acceptance tests' },
});
类型
name
Added in: v1.10配置名称在报告和测试执行过程中可见,除非被 testProject.name 覆盖。
🌐 Config name is visible in the report and during test execution, unless overridden by testProject.name.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
name: 'acceptance tests',
});
类型
outputDir
Added in: v1.10测试执行过程中创建的文件的输出目录。默认值为 <package.json-directory>/test-results。
🌐 The output directory for files created during test execution. Defaults to <package.json-directory>/test-results.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
outputDir: './test-results',
});
类型
详情
该目录在开始时会被清理。运行测试时,会在 testConfig.outputDir 内创建一个唯一的子目录,以确保并行运行的测试不会互相冲突。可以通过 testInfo.outputDir 和 testInfo.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.outputDir 中保留测试输出。默认值为 'always'。
🌐 Whether to preserve test output in the testConfig.outputDir. Defaults to 'always'.
'always'- 保留所有测试的输出;'never'- 不要为任何测试保存输出;'failures-only'- 仅保存失败测试的输出。
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
preserveOutput: 'always',
});
类型
- “总是” | “从不” | “仅失败”
projects
Added in: v1.10Playwright Test 支持同时运行多个测试项目。有关更多信息,请参阅 TestProject。
🌐 Playwright Test supports running multiple test projects at the same time. See TestProject for more information.
用法
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
projects: [
{ name: 'chromium', use: devices['Desktop Chrome'] }
]
});
类型
- [数组]<[测试项目]>
quiet
Added in: v1.10是否抑制测试中的 stdio 和 stderr 输出。
🌐 Whether to suppress stdio and stderr output from the tests.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
quiet: !!process.env.CI,
});
类型
repeatEach
Added in: v1.10重复每个测试的次数,对于调试片状测试很有用。
🌐 The number of times to repeat each test, useful for debugging flaky tests.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
repeatEach: 3,
});
类型
reportSlowTests
Added in: v1.10是否报告运行缓慢的测试文件。传入 null 可禁用此功能。
🌐 Whether to report slow test files. Pass null to disable this feature.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
reportSlowTests: null,
});
类型
详情
耗时超过 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要使用的报表生成器列表。每个报表生成器可以是:
🌐 The list of reporters to use. Each reporter can be:
- 一个内置的报告器名称,如
'list'或'json'。 - 一个像
'my-awesome-reporter'这样的模块名。 - 指向报告器的相对路径,例如
'./reporters/my-awesome-reporter.js'。
你可以像 ['json', { outputFile: './report.json' }] 那样将选项传递给报告器。如果未指定该属性,当 CI 环境变量被设置时,Playwright 会使用 'dot' 报告器,否则会使用 'list' 报告器。
🌐 You can pass options to the reporter in a tuple like ['json', { outputFile: './report.json' }]. If the property is not specified, Playwright uses the 'dot' reporter when the CI environment variable is set, and the 'list' reporter otherwise.
在报告器指南中了解更多信息。
🌐 Learn more in the reporters guide.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
reporter: 'line',
});
类型
- [字符串] | [数组]<[对象]> | "列表" | "点" | "线" | "GitHub" | "JSON" | "JUnit" | "空" | "HTML"
respectGitIgnore
Added in: v1.45在搜索测试文件时是否跳过来自 .gitignore 的条目。默认情况下,如果未明确指定 testConfig.testDir 或 testProject.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.
用法
testConfig.respectGitIgnore
类型
retries
Added in: v1.10给失败测试的最大重试次数。默认情况下,失败的测试不会被重试。了解更多关于 测试重试 的信息。
🌐 The maximum number of retry attempts given to failed tests. By default failing tests are not retried. Learn more about test retries.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
retries: 2,
});
类型
shard
Added in: v1.10分片只测试并执行选定的分片。用一基形式,比如 { 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
shard: { total: 10, current: 3 },
});
类型
snapshotPathTemplate
Added in: v1.28此选项配置一个模板,用于控制由 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.
用法
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:
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:
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:
- 第一个项目没有名称,因此其快照将存储在
<configDir>/__screenshots__/example.spec.ts/...中。 - 第二个项目确实有一个名字,因此它的快照将存储在
<configDir>/__screenshots__/chromium/example.spec.ts/..。 - 由于
snapshotPathTemplate解析为相对路径,它将相对于configDir进行解析。 - 正斜杠
"/"可以在任何平台上用作路径分隔符。
tag
Added in: v1.57报告中每个测试前添加的标签。可用于标记你的测试运行,以区分不同的CI环境。
🌐 Tag or tags prepended to each test in the report. Useful for tagging your test run to differentiate between CI environments.
请注意,每个标签必须以 @ 符号开头。了解更多关于标签的信息。
🌐 Note that each tag must start with @ symbol. Learn more about tagging.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
tag: process.env.CI_ENVIRONMENT_NAME, // for example "@APIv2"
});
类型
- [字符串] | [数组]<[字符串]>
testDir
Added in: v1.10将递归扫描以查找测试文件的目录。默认是配置文件所在的目录。
🌐 Directory that will be recursively scanned for test files. Defaults to the directory of the configuration file.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests/playwright',
});
类型
testIgnore
Added in: v1.10与这些模式之一匹配的文件不会作为测试文件执行。匹配是针对绝对文件路径进行的。字符串被视为通配符模式。
🌐 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
testIgnore: '**/test-assets/**',
});
类型
- [字符串] | [正则表达式] | [数组]<[字符串] | [正则表达式]>
testMatch
Added in: v1.10只有与这些模式之一匹配的文件才会被作为测试文件执行。匹配是针对绝对文件路径进行的。字符串被视为通配符模式。
🌐 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
testMatch: /.*\.e2e\.js/,
});
类型
- [字符串] | [正则表达式] | [数组]<[字符串] | [正则表达式]>
timeout
Added in: v1.10每个测试的超时时间,以毫秒为单位。默认值为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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
timeout: 5 * 60 * 1000,
});
类型
tsconfig
Added in: v1.49适用于所有导入文件的单个 tsconfig 的路径。默认情况下,每个导入文件的 tsconfig 会单独查找。请注意,当配置文件或其任何依赖正在加载时,tsconfig 属性没有效果。当指定 --tsconfig 命令行选项时将被忽略。
🌐 Path to a single tsconfig applicable to all imported files. By default, tsconfig for each imported file is looked up separately. Note that tsconfig property has no effect while the configuration file or any of its dependencies are loaded. Ignored when --tsconfig command line option is specified.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
tsconfig: './tsconfig.test.json',
});
类型
updateSnapshots
Added in: v1.10是否将预期快照更新为测试运行产生的实际结果。默认值为 'missing'。
🌐 Whether to update expected snapshots with the actual results produced by the test run. Defaults to 'missing'.
'all'- 所有执行的测试都会更新快照。'changed'- 所有执行的测试将更新不匹配的快照。匹配的快照将不会被更新。同时会创建缺失的快照。'missing'- 缺失的快照会被创建,例如在编写新测试并第一次运行时。这是默认设置。'none'- 没有更新快照。
了解有关 快照 的更多信息。
🌐 Learn more about snapshots.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
updateSnapshots: 'missing',
});
类型
- “全部” | “已更改” | “缺失” | “无”
updateSourceMethod
Added in: v1.50定义如何更新源代码中的快照。
🌐 Defines how to update snapshots in the source code.
'patch'- 创建一个统一的差异文件,以便稍后用于更新源代码。这是默认选项。'3way'- 在源代码中生成合并冲突标记。这允许用户手动选择相关更改,就像在IDE中解决合并冲突一样。'overwrite'- 用新的快照值覆盖源代码。
用法
testConfig.updateSourceMethod
类型
- "覆盖" | "三方" | "补丁"
use
Added in: v1.10所有测试的全局选项,例如 testOptions.browserName。了解更多关于 配置 的信息,并查看 可用选项。
🌐 Global options for all tests, for example testOptions.browserName. Learn more about configuration and see available options.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
browserName: 'chromium',
},
});
类型
webServer
Added in: v1.10在测试期间启动一个(或多个)开发 Web 服务器。
🌐 Launch a development web server (or multiple) during the tests.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start',
url: 'http://localhost:3000',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
use: {
baseURL: 'http://localhost:3000/',
},
});
现在你可以在导航页面时使用相对路径:
🌐 Now you can use a relative path when navigating the page:
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:
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: [
{
command: 'npm run start',
url: 'http://localhost:3000',
name: 'Frontend',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
},
{
command: 'npm run backend',
url: 'http://localhost:3333',
name: 'Backend',
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
}
],
use: {
baseURL: 'http://localhost:3000',
},
});
如果你的网络服务器在不同端口上运行,请使用 wait 来捕获端口:
🌐 If your webserver runs on varying ports, use wait to capture the port:
import { defineConfig } from '@playwright/test';
export default defineConfig({
webServer: {
command: 'npm run start',
wait: {
stdout: /Listening on port (?<my_server_port>\d+)/
},
},
});
import { test, expect } from '@playwright/test';
test.use({ baseUrl: `http://localhost:${process.env.MY_SERVER_PORT ?? 3000}` });
test('homepage', async ({ page }) => {
await page.goto('/');
});
类型
- [对象] | [数组]<[对象]>
-
commandstring启动的 Shell 命令。例如
npm run start.. -
cwdstring (optional)生成进程的当前工作目录,默认为配置文件的目录。
-
envObject<string, string> (optional)要为命令设置的环境变量,默认值为
process.env。 -
gracefulShutdownObject (optional)-
signal“SIGINT” | “SIGTERM” -
timeoutnumber
如何关闭进程。如果未指定,进程组将被强制
SIGKILL。如果设置为{ signal: 'SIGTERM', timeout: 500 },则会向进程组发送SIGTERM信号,如果在 500 毫秒内未退出,则发送SIGKILL。你也可以用SIGINT作为信号。0超时意味着不会发送SIGKILL。Windows 不支持SIGTERM和SIGINT信号,因此在 Windows 上会忽略此选项。请注意,关闭 Docker 容器需要SIGTERM。 -
-
ignoreHTTPSErrorsboolean (optional)在获取
url时是否忽略 HTTPS 错误。默认为false。 -
namestring (optional)指定 Web 服务器的自定义名称。此名称将作为前缀添加到日志消息中。默认值为
[WebServer]。 -
portnumber (optional)你的 HTTP 服务器预计会出现的端口。它会等待直到接收连接。应指定
port或url。 -
reuseExistingServerboolean (optional)如果为真,它将在可用时重用
port或url上现有的服务器。如果在port或url上没有正在运行的服务器,它将执行命令以启动一个新服务器。如果false,当在port或url上已有进程监听时,它将抛出错误。通常应设置为!process.env.CI,以允许在本地运行测试时使用本地开发服务器。 -
stderr"pipe" | "ignore" (optional)是否将命令的标准错误输出(stderr)重定向到进程的标准错误输出,或忽略它。默认值为
"pipe"。 -
stdout"pipe" | "ignore" (optional)如果是
"pipe",它会将命令的标准输出传递到进程的标准输出。如果是"ignore",它会忽略命令的标准输出。默认值是"ignore"。 -
waitObject (optional)-
stdoutRegExp (optional)正则表达式用于等待命令输出中的
stdout。命名捕获组会存储在环境中,例如/Listening on port (?<my_server_port>\d+)/会将端口号存储在process.env['MY_SERVER_PORT']中。 -
stderrRegExp (optional)正则表达式用于等待命令输出中的
stderr。命名捕获组会存储在环境中,例如/Listening on port (?<my_server_port>\d+)/会将端口号存储在process.env['MY_SERVER_PORT']中。
只有在产生输出时才考虑命令已启动。
-
-
timeoutnumber (optional)等待进程启动并可用的时间,单位为毫秒。默认值为60000。
-
urlstring (optional)在你的 HTTP 服务器上,期望返回 2xx、3xx、400、401、402 或 403 状态码的 URL,当服务器准备好接受连接时会返回这些状态码。重定向(3xx 状态码)会被跟随,并检查新位置。应该指定
port或url中的一个。
-
详情
如果指定了端口,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.
对于持续集成,你可能想使用不在 CI 上使用现有服务器的 reuseExistingServer: !process.env.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用于并行化测试的最大并发工作进程数。也可以设置为逻辑 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
workers: 3,
});
类型
- [数字] | [字符串]
已弃用
🌐 Deprecated
snapshotDir
Added in: v1.10使用 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.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
snapshotDir: './snapshots',
});
类型
详情
每个测试的目录可以通过 testInfo.snapshotDir 和 testInfo.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.