TestOptions
Playwright Test 提供了多种选项来配置测试环境、[浏览器]、[浏览器上下文]等。
🌐 Playwright Test provides many options to configure test environment, Browser, BrowserContext and more.
这些选项通常通过 testConfig.use 和 testProject.use 在 配置文件 中提供。
🌐 These options are usually provided in the configuration file through testConfig.use and testProject.use.
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
headless: false,
viewport: { width: 1280, height: 720 },
ignoreHTTPSErrors: true,
video: 'on-first-retry',
},
});
或者,通过 test.use() 你可以覆盖某个文件的一些选项。
🌐 Alternatively, with test.use() you can override some options for a file.
import { test, expect } from '@playwright/test';
// Run tests in this file with portrait-like viewport.
test.use({ viewport: { width: 600, height: 900 } });
test('my portrait test', async ({ page }) => {
// ...
});
属性
🌐 Properties
acceptDownloads
Added in: v1.10是否自动下载所有附件。默认值为 true,表示接受所有下载。
🌐 Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
acceptDownloads: false,
},
});
类型
actionTimeout
Added in: v1.10每个 Playwright 操作的默认超时(以毫秒为单位),默认为 0(无超时)。
🌐 Default timeout for each Playwright action in milliseconds, defaults to 0 (no timeout).
这是所有 Playwright 操作的默认超时,与通过 page.setDefaultTimeout() 配置的相同。
🌐 This is a default timeout for all Playwright actions, same as configured via page.setDefaultTimeout().
用法
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,
},
});
了解更多关于各种超时的信息。
🌐 Learn more about various timeouts.
类型
baseURL
Added in: v1.10在使用 page.goto()、page.route()、page.waitForURL()、page.waitForRequest() 或 page.waitForResponse() 时,会通过使用 URL() 构造函数构建相应的 URL 来考虑基础 URL。默认情况下未设置。示例:
🌐 When using page.goto(), page.route(), page.waitForURL(), page.waitForRequest(), or page.waitForResponse() it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples:
- baseURL:
http://localhost:3000,然后导航到/bar.html会得到http://localhost:3000/bar.html - baseURL:
http://localhost:3000/foo/,然后导航到./bar.html会得到http://localhost:3000/foo/bar.html - baseURL:
http://localhost:3000/foo(不带末尾斜杠),然后导航到./bar.html会得到http://localhost:3000/bar.html
用法
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:3000',
},
});
类型
browserName
Added in: v1.10运行测试的浏览器名称。默认为 'chromium'。大多数情况下,你应在你的 TestConfig 中设置 browserName:
🌐 Name of the browser that runs tests. Defaults to 'chromium'. Most of the time you should set browserName in your TestConfig:
用法
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
use: {
browserName: 'firefox',
},
});
类型
- "chromium" | "firefox" | "webkit"
bypassCSP
Added in: v1.10切换是否绕过页面的内容安全策略。默认值为 false。
🌐 Toggles bypassing page's Content-Security-Policy. Defaults to false.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
bypassCSP: true,
}
});
类型
channel
Added in: v1.10浏览器分发渠道。
🌐 Browser distribution channel.
使用“chromium”来选择使用新的无头模式。
🌐 Use "chromium" to opt in to new headless mode.
使用“chrome”、“chrome-beta”、“chrome-dev”、“chrome-canary”、“msedge”、“msedge-beta”、“msedge-dev”或“msedge-canary”来使用品牌化的 Google Chrome 和 Microsoft Edge。
🌐 Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded Google Chrome and Microsoft Edge.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'Microsoft Edge',
use: {
...devices['Desktop Edge'],
channel: 'msedge'
},
},
]
});
类型
clientCertificates
Added in: 1.46TLS 客户端身份验证允许服务器请求客户端证书并对其进行验证。
🌐 TLS Client Authentication allows the server to request a client certificate and verify it.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
clientCertificates: [{
origin: 'https://example.com',
certPath: './cert.pem',
keyPath: './key.pem',
passphrase: 'mysecretpassword',
}],
},
});
类型
- [数组]<[对象]>
-
originstring证书有效的确切来源。来源包括
https协议、主机名以及可选的端口。 -
certPathstring (optional)PEM 格式的证书文件路径。
-
certBuffer (optional)PEM 格式的证书的直接值。
-
keyPathstring (optional)PEM 格式的私钥文件路径。
-
keyBuffer (optional)PEM 格式的私钥的直接值。
-
pfxPathstring (optional)PFX 或 PKCS12 编码的私钥和证书链的路径。
-
pfxBuffer (optional)PFX 或 PKCS12 编码的私钥和证书链的直接值。
-
passphrasestring (optional)私钥的密码(PEM 或 PFX)。
-
详情
要使用的一组客户端证书。每个证书对象必须同时具有 certPath 和 keyPath,或者单独具有 pfxPath,或它们对应的直接值等效项(cert 和 key,或 pfx)。如果证书是加密的,则可选择提供 passphrase 属性。origin 属性应提供与证书有效的请求来源完全匹配的值。
🌐 An array of client certificates to be used. Each certificate object must have either both certPath and keyPath, a single pfxPath, or their corresponding direct value equivalents (cert and key, or pfx). Optionally, passphrase property should be provided if the certificate is encrypted. The origin property should be provided with an exact match to the request origin that the certificate is valid for.
客户端证书认证仅在提供至少一个客户端证书时才有效。如果你想拒绝服务器发送的所有客户端证书,你需要提供一个 origin 与你计划访问的任何域名都不匹配的客户端证书。
🌐 Client certificate authentication is only active when at least one client certificate is provided. If you want to reject all client certificates sent by the server, you need to provide a client certificate with an origin that does not match any of the domains you plan to visit.
在 macOS 上使用 WebKit 时,访问 localhost 不会使用客户端证书。你可以通过将 localhost 替换为 local.playwright 来使其正常工作。
🌐 When using WebKit on macOS, accessing localhost will not pick up client certificates. You can make it work by replacing localhost with local.playwright.
colorScheme
Added in: v1.10模拟 prefers-colors-scheme 媒体特性,支持的值为 'light' 和 'dark'。更多详情请参见 page.emulateMedia()。传入 null 可将模拟重置为系统默认值。默认值为 'light'。
🌐 Emulates prefers-colors-scheme media feature, supported values are 'light' and 'dark'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'light'.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
colorScheme: 'dark',
},
});
类型
- [空] | “浅色” | “深色” | “无偏好”
connectOptions
Added in: v1.10用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
connectOptions: {
wsEndpoint: 'ws://localhost:5678',
},
},
});
当指定连接选项时,默认的 fixtures.browser、fixtures.context 和 fixtures.page 将使用远程浏览器,而不是本地启动浏览器,并且任何启动选项,如 testOptions.headless 或 testOptions.channel 都会被忽略。
🌐 When connect options are specified, default fixtures.browser, fixtures.context and fixtures.page use the remote browser instead of launching a browser locally, and any launch options like testOptions.headless or testOptions.channel are ignored.
类型
- [空] | [对象]
contextOptions
Added in: v1.10用于创建上下文的选项,作为传递给 browser.newContext() 的参数。像 testOptions.viewport 这样的特定选项优先于此选项。
🌐 Options used to create the context, as passed to browser.newContext(). Specific options like testOptions.viewport take priority over this.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
contextOptions: {
reducedMotion: 'reduce',
},
},
});
类型
deviceScaleFactor
Added in: v1.10指定设备缩放因子(可以理解为 DPR)。默认值为 1。了解有关使用设备缩放因子模拟设备的更多信息。
🌐 Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
viewport: { width: 2560, height: 1440 },
deviceScaleFactor: 2,
},
});
类型
extraHTTPHeaders
Added in: v1.10一个包含附加 HTTP 头的对象,这些头将随每个请求发送。默认为无。
🌐 An object containing additional HTTP headers to be sent with every request. Defaults to none.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
extraHTTPHeaders: {
'X-My-Header': 'value',
},
},
});
类型
- [对象]<[字符串], [字符串]>
geolocation
Added in: v1.10用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
geolocation: { longitude: 12.492507, latitude: 41.889938 },
},
});
了解更多关于地理定位的信息。
🌐 Learn more about geolocation.
类型
hasTouch
Added in: v1.10指定视口是否支持触摸事件。默认值为 false。了解更多关于 移动模拟 的信息。
🌐 Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
hasTouch: true
},
});
类型
headless
Added in: v1.10是否以无头模式运行浏览器。更多详情请参见 Chromium 和 Firefox。默认值为 true。
🌐 Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to true.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
headless: false
},
});
类型
httpCredentials
Added in: v1.10HTTP 认证 的凭据。如果未指定来源,用户名和密码将在收到未授权响应时发送到任何服务器。
🌐 Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
httpCredentials: {
username: 'user',
password: 'pass',
},
},
});
类型
- Object
-
usernamestring -
passwordstring -
originstring (optional)限制在特定来源 (scheme://host:port) 上发送 http 凭据。
-
send"unauthorized" | "always" (optional)此选项仅适用于从对应的 APIRequestContext 发送的请求,并不影响从浏览器发送的请求。
'always'-Authorization头信息会随每个 API 请求发送基本认证凭据。'unauthorized- 凭据仅在收到带有WWW-Authenticate头的 401(未授权)响应时发送。默认为'unauthorized'。
-
ignoreHTTPSErrors
Added in: v1.10发送网络请求时是否忽略 HTTPS 错误。默认值为 false。
🌐 Whether to ignore HTTPS errors when sending network requests. Defaults to false.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
ignoreHTTPSErrors: true,
},
});
类型
isMobile
Added in: v1.10是否考虑 meta viewport 标签并启用触摸事件。isMobile 是 device 的一部分,因此你实际上不需要手动设置它。默认值为 false,并且在 Firefox 中不受支持。了解更多关于 移动端模拟 的信息。
🌐 Whether the meta viewport tag is taken into account and touch events are enabled. isMobile is a part of device, so you don't actually need to set it manually. Defaults to false and is not supported in Firefox. Learn more about mobile emulation.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
isMobile: false,
},
});
类型
javaScriptEnabled
Added in: v1.10是否在此环境中启用 JavaScript。默认为 true。了解更多关于禁用 JavaScript的信息。
🌐 Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
javaScriptEnabled: false,
},
});
类型
launchOptions
Added in: v1.10用于启动浏览器的选项,传递给 browserType.launch()。特定选项 testOptions.headless 和 testOptions.channel 优先于此使用。
🌐 Options used to launch the browser, as passed to browserType.launch(). Specific options testOptions.headless and testOptions.channel take priority over this.
使用自定义浏览器参数需自行承担风险,因为其中一些可能会破坏 Playwright 的功能。
🌐 Use custom browser args at your own risk, as some of them may break Playwright functionality.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
launchOptions: {
args: ['--start-maximized']
}
}
}
]
});
类型
locale
Added in: v1.10指定用户区域设置,例如 en-GB、de-DE 等。区域设置会影响 navigator.language 的值、Accept-Language 请求头的值以及数字和日期的格式规则。默认值为 en-US。在我们的模拟指南中了解更多关于模拟的信息。
🌐 Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. Defaults to en-US. Learn more about emulation in our emulation guide.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
locale: 'it-IT',
},
});
类型
navigationTimeout
Added in: v1.10每个导航操作的超时时间(毫秒)。默认值为0(无限超时)。
🌐 Timeout for each navigation action in milliseconds. Defaults to 0 (no timeout).
这是默认的导航超时,与通过 page.setDefaultNavigationTimeout() 配置的相同。
🌐 This is a default navigation timeout, same as configured via page.setDefaultNavigationTimeout().
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
navigationTimeout: 3000,
},
});
了解更多关于各种超时的信息。
🌐 Learn more about various timeouts.
类型
offline
Added in: v1.10是否模拟网络离线。默认为 false。了解更多关于 网络模拟 的信息。
🌐 Whether to emulate network being offline. Defaults to false. Learn more about network emulation.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
offline: true
},
});
类型
permissions
Added in: v1.10在此上下文中授予所有页面的权限列表。有关更多详细信息,请参阅 browserContext.grantPermissions()。默认情况下无权限。
🌐 A list of permissions to grant to all pages in this context. See browserContext.grantPermissions() for more details. Defaults to none.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
permissions: ['notifications'],
},
});
类型
- [数组]<[字符串]>
proxy
Added in: v1.10网络代理设置。
🌐 Network proxy settings.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
proxy: {
server: 'http://myproxy.com:3128',
bypass: 'localhost',
},
},
});
类型
- Object
-
serverstring用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如
http://myproxy.com:3128或socks5://myproxy.com:3128。简写myproxy.com:3128被视为 HTTP 代理。 -
bypassstring (optional)可选的以逗号分隔的域名,用于绕过代理,例如
".com, chromium.org, .domain.com"。 -
usernamestring (optional)如果 HTTP 代理需要身份验证,则使用可选的用户名。
-
passwordstring (optional)如果 HTTP 代理需要身份验证,则使用可选密码。
-
screenshot
Added in: v1.10是否在每次测试后自动捕获屏幕截图。默认值为 'off'。
🌐 Whether to automatically capture a screenshot after each test. Defaults to 'off'.
'off':不要捕获屏幕截图。'on':每次测试后捕获屏幕截图。'only-on-failure':每次测试失败后捕获屏幕截图。'on-first-failure':在每个测试第一次失败后捕获屏幕截图。
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
screenshot: 'only-on-failure',
},
});
了解有关自动截图的更多信息。
🌐 Learn more about automatic screenshots.
类型
- [对象] | “关闭” | “开启” | “仅在失败时” | “首次失败时”
serviceWorkers
Added in: v1.10是否允许网站注册服务工作进程。默认值为 'allow'。
🌐 Whether to allow sites to register Service workers. Defaults to 'allow'.
'allow':服务工作者 可以被注册。'block':Playwright 将阻止所有服务工作进程的注册。
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
serviceWorkers: 'allow'
},
});
类型
- “允许” | “阻止”
storageState
Added in: v1.10了解更多关于存储状态和身份验证的信息。
🌐 Learn more about storage state and auth.
使用给定的存储状态填充上下文。此选项可用于使用通过 browserContext.storageState() 获取的登录信息初始化上下文。
🌐 Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via browserContext.storageState().
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
storageState: 'storage-state.json',
},
});
类型
- [字符串] | [对象]
详情
当在配置中设置存储状态时,可以重置文件的存储状态:
🌐 When storage state is set up in the config, it is possible to reset storage state for a file:
import { test } from '@playwright/test';
// Reset storage state for this file to avoid being authenticated
test.use({ storageState: { cookies: [], origins: [] } });
test('not signed in test', async ({ page }) => {
// ...
});
testIdAttribute
Added in: v1.27自定义属性,用于 page.getByTestId()。默认使用 data-testid。
🌐 Custom attribute to be used in page.getByTestId(). data-testid is used by default.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
testIdAttribute: 'pw-test-id',
},
});
timezoneId
Added in: v1.10更改上下文的时区。有关支持的时区 ID 列表,请参阅 ICU 的 metaZones.txt。默认使用系统时区。
🌐 Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
timezoneId: 'Europe/Rome',
},
});
类型
trace
Added in: v1.10是否为每个测试记录跟踪。默认值为 'off'。
🌐 Whether to record trace for each test. Defaults to 'off'.
'off':不记录痕迹。'on':记录每次测试的跟踪。'on-first-retry':仅在第一次重试测试时记录跟踪。'on-all-retries':仅在重试测试时记录跟踪。'retain-on-failure':记录每个测试的跟踪。当测试运行通过时,删除已记录的跟踪。'retain-on-first-failure':为每个测试的第一次运行记录跟踪,但重试时不记录。当测试运行成功时,删除已记录的跟踪。
若想获得更多控制,可传入一个指定 mode 和要启用的跟踪功能的对象。
🌐 For more control, pass an object that specifies mode and trace features to enable.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
trace: 'on-first-retry'
},
});
了解有关记录跟踪的更多信息。
🌐 Learn more about recording trace.
类型
- [对象] | “关闭” | “开启” | “失败时保留” | “首次重试时开启” | “首次失败时保留”
-
mode“关闭” | “开启” | “失败时保留开启” | “首次重试时开启” | “所有重试时开启” | “首次失败时保留开启”轨迹记录模式。
-
attachmentsboolean (optional)是否包含测试附件。默认值为 true。可选。
-
screenshotsboolean (optional)在追踪过程中是否捕获截图。截图用于构建时间线预览。默认值为 true,可选。
-
snapshotsboolean (optional)是否在每个操作时捕获 DOM 快照。默认值为 true。可选。
-
sourcesboolean (optional)是否包含跟踪操作的源文件。默认值为 true。可选。
-
userAgent
Added in: v1.10在此上下文中使用的特定用户代理。
🌐 Specific user agent to use in this context.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
userAgent: 'some custom ua',
},
});
类型
video
Added in: v1.10是否为每个测试录制视频。默认值为 'off'。
🌐 Whether to record video for each test. Defaults to 'off'.
'off':不要录制视频。'on':为每次测试录制视频。'retain-on-failure':为每个测试录制视频,但从成功的测试运行中删除所有视频。'on-first-retry':仅在第一次重试测试时录制视频。
要控制视频大小,请传入一个包含 mode 和 size 属性的对象。如果未指定视频大小,则默认与 testOptions.viewport 相同,并缩小以适应 800x800。如果未明确配置 viewport,视频大小默认为 800x450。每个页面的实际画面将在必要时缩小以适应指定的大小。
🌐 To control video size, pass an object with mode and size properties. If video size is not specified, it will be equal to testOptions.viewport scaled down to fit into 800x800. If viewport is not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
video: 'on-first-retry',
},
});
了解有关录制视频的更多信息。
🌐 Learn more about recording video.
类型
- [对象] | “关闭” | “开启” | “失败时保留” | “首次重试时开启”
viewport
Added in: v1.10为每个页面模拟一致的视口。默认视口为 1280x720。使用 null 可禁用一致视口模拟。了解更多关于视口模拟的信息。
🌐 Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use null to disable the consistent viewport emulation. Learn more about viewport emulation.
null 值选择不使用默认预设,使视口依赖于操作系统定义的主机窗口大小。这会导致测试执行结果不确定。:::
🌐 The null value opts out from the default presets, makes viewport depend on the host window size defined by the operating system. It makes the execution of the tests non-deterministic.
用法
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
viewport: { width: 100, height: 100 },
},
});
类型