Skip to main content

TestOptions

Playwright Test 提供了很多配置测试环境的选项,BrowserBrowserContext 等等。

¥Playwright Test provides many options to configure test environment, Browser, BrowserContext and more.

这些选项通常在 配置文件testConfig.usetestProject.use 中提供。

¥These options are usually provided in the configuration file through testConfig.use and testProject.use.

playwright.config.ts
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.

example.spec.ts
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 testOptions.acceptDownloads

是否自动下载所有附件。默认为 true,接受所有下载。

¥Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.

用法

¥Usage

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

export default defineConfig({
use: {
acceptDownloads: false,
},
});

类型

¥Type


actionTimeout

Added in: v1.10 testOptions.actionTimeout

每个 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().

用法

¥Usage

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.

类型

¥Type


baseURL

Added in: v1.10 testOptions.baseURL

当使用 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 and navigating to /bar.html results in http://localhost:3000/bar.html

  • baseURL:http://localhost:3000/foo/ 并导航至 ./bar.html 结果为 http://localhost:3000/foo/bar.html

    ¥baseURL: http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html

  • baseURL:http://localhost:3000/foo(无尾部斜杠)并导航至 ./bar.html 将导致 http://localhost:3000/bar.html

    ¥baseURL: http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html

用法

¥Usage

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

export default defineConfig({
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:3000',
},
});

类型

¥Type


browserName

Added in: v1.10 testOptions.browserName

运行测试的浏览器的名称。默认为 'chromium'。大多数时候你应该在 TestConfig 中设置 browserName

¥Name of the browser that runs tests. Defaults to 'chromium'. Most of the time you should set browserName in your TestConfig:

用法

¥Usage

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

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

类型

¥Type

  • "chromium" | "firefox" | "webkit"

bypassCSP

Added in: v1.10 testOptions.bypassCSP

切换绕过页面的内容安全策略。默认为 false

¥Toggles bypassing page's Content-Security-Policy. Defaults to false.

用法

¥Usage

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

export default defineConfig({
use: {
bypassCSP: true,
}
});

类型

¥Type


channel

Added in: v1.10 testOptions.channel

浏览器分发渠道。

¥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" 来使用品牌 谷歌浏览器和微软 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.

用法

¥Usage

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

export default defineConfig({
projects: [
{
name: 'Microsoft Edge',
use: {
...devices['Desktop Edge'],
channel: 'msedge'
},
},
]
});

类型

¥Type


clientCertificates

Added in: 1.46 testOptions.clientCertificates

TLS 客户端身份验证允许服务器请求客户端证书并对其进行验证。

¥TLS Client Authentication allows the server to request a client certificate and verify it.

用法

¥Usage

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

export default defineConfig({
use: {
clientCertificates: [{
origin: 'https://example.com',
certPath: './cert.pem',
keyPath: './key.pem',
passphrase: 'mysecretpassword',
}],
},
});

类型

¥Type

证书有效的确切来源。Origin 包括 https 协议、主机名和可选的端口。

¥Exact origin that the certificate is valid for. Origin includes https protocol, a hostname and optionally a port.

PEM 格式的证书文件路径。

¥Path to the file with the certificate in PEM format.

PEM 格式的证书的直接值。

¥Direct value of the certificate in PEM format.

PEM 格式的私钥文件路径。

¥Path to the file with the private key in PEM format.

PEM 格式的私钥的直接值。

¥Direct value of the private key in PEM format.

PFX 或 PKCS12 编码的私钥和证书链的路径。

¥Path to the PFX or PKCS12 encoded private key and certificate chain.

PFX 或 PKCS12 编码的私钥和证书链的直接值。

¥Direct value of the PFX or PKCS12 encoded private key and certificate chain.

  • passphrase string (optional)

私钥的密码(PEM 或 PFX)。

¥Passphrase for the private key (PEM or PFX).

细节

¥Details

要使用的客户端证书数组。每个证书对象必须同时具有 certPathkeyPath、单个 pfxPath 或它们对应的直接值等价物(certkeypfx)。如果证书已加密,则可选地提供 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.

注意

在 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 testOptions.colorScheme

模拟 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'.

用法

¥Usage

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

export default defineConfig({
use: {
colorScheme: 'dark',
},
});

类型

¥Type

  • null | "light" | "dark" | "no-preference"

connectOptions

Added in: v1.10 testOptions.connectOptions

用法

¥Usage

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

export default defineConfig({
use: {
connectOptions: {
wsEndpoint: 'ws://localhost:5678',
},
},
});

指定连接选项时,默认 fixtures.browserfixtures.contextfixtures.page 使用远程浏览器而不是在本地启动浏览器,并且忽略任何启动选项(如 testOptions.headlesstestOptions.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.

类型

¥Type

要连接的浏览器 Websocket 端点。

¥A browser websocket endpoint to connect to.

与 Web 套接字连接请求一起发送的附加 HTTP 标头。可选的。

¥Additional HTTP headers to be sent with web socket connect request. Optional.

建立连接的超时时间(以毫秒为单位)。可选,默认不超时。

¥Timeout in milliseconds for the connection to be established. Optional, defaults to no timeout.

  • exposeNetwork string (optional)

将连接客户端上可用的网络公开给所连接的浏览器的选项。详细信息请参见 browserType.connect()

¥Option to expose network available on the connecting client to the browser being connected to. See browserType.connect() for more details.


contextOptions

Added in: v1.10 testOptions.contextOptions

用于创建上下文的选项,传递给 browser.newContext()。像 testOptions.viewport 这样的特定选项优先于此。

¥Options used to create the context, as passed to browser.newContext(). Specific options like testOptions.viewport take priority over this.

用法

¥Usage

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

export default defineConfig({
use: {
contextOptions: {
reducedMotion: 'reduce',
},
},
});

类型

¥Type


deviceScaleFactor

Added in: v1.10 testOptions.deviceScaleFactor

指定设备比例因子(可以视为 dpr)。默认为 1。了解有关 使用设备比例因子模拟设备 的更多信息。

¥Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.

用法

¥Usage

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

export default defineConfig({
use: {
viewport: { width: 2560, height: 1440 },
deviceScaleFactor: 2,
},
});

类型

¥Type


extraHTTPHeaders

Added in: v1.10 testOptions.extraHTTPHeaders

包含随每个请求发送的附加 HTTP 标头的对象。默认为无。

¥An object containing additional HTTP headers to be sent with every request. Defaults to none.

用法

¥Usage

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

export default defineConfig({
use: {
extraHTTPHeaders: {
'X-My-Header': 'value',
},
},
});

类型

¥Type


geolocation

Added in: v1.10 testOptions.geolocation

用法

¥Usage

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

export default defineConfig({
use: {
geolocation: { longitude: 12.492507, latitude: 41.889938 },
},
});

了解有关 geolocation 的更多信息。

¥Learn more about geolocation.

类型

¥Type

纬度在 -90 到 90 之间。

¥Latitude between -90 and 90.

经度在 -180 到 180 之间。

¥Longitude between -180 and 180.

非负精度值。默认为 0

¥Non-negative accuracy value. Defaults to 0.


hasTouch

Added in: v1.10 testOptions.hasTouch

指定视口是否支持触摸事件。默认为 false。了解有关 移动模拟 的更多信息。

¥Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.

用法

¥Usage

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

export default defineConfig({
use: {
hasTouch: true
},
});

类型

¥Type


headless

Added in: v1.10 testOptions.headless

是否以无头模式运行浏览器。Chromium火狐浏览器 的更多详细信息。默认为 true,除非 devtools 选项为 true

¥Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to true unless the devtools option is true.

用法

¥Usage

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

export default defineConfig({
use: {
headless: false
},
});

类型

¥Type


httpCredentials

Added in: v1.10 testOptions.httpCredentials

HTTP 认证 的凭证。如果未指定来源,则用户名和密码将在未经授权的响应时发送到任何服务器。

¥Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

用法

¥Usage

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

export default defineConfig({
use: {
httpCredentials: {
username: 'user',
password: 'pass',
},
},
});

类型

¥Type

限制在特定来源 (scheme://host:port) 上发送 http 凭据。

¥Restrain sending http credentials on specific origin (scheme://host:port).

  • send "unauthorized" | "always"(可选)

    ¥send "unauthorized" | "always" (optional)

    此选项仅适用于从相应 APIRequestContext 发送的请求,不影响从浏览器发送的请求。'always' - 带有基本身份验证凭据的 Authorization 标头将随每个 API 请求一起发送。'unauthorized - 仅当收到带有 WWW-Authenticate 标头的 401(未授权)响应时才会发送凭据。默认为 'unauthorized'

    ¥This option only applies to the requests sent from corresponding APIRequestContext and does not affect requests sent from the browser. 'always' - Authorization header with basic authentication credentials will be sent with the each API request. 'unauthorized - the credentials are only sent when 401 (Unauthorized) response with WWW-Authenticate header is received. Defaults to 'unauthorized'.


ignoreHTTPSErrors

Added in: v1.10 testOptions.ignoreHTTPSErrors

发送网络请求时是否忽略 HTTPS 错误。默认为 false

¥Whether to ignore HTTPS errors when sending network requests. Defaults to false.

用法

¥Usage

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

export default defineConfig({
use: {
ignoreHTTPSErrors: true,
},
});

类型

¥Type


isMobile

Added in: v1.10 testOptions.isMobile

是否考虑 meta viewport 标签并启用触摸事件。isMobile 是设备的一部分,因此你实际上不需要手动设置它。默认为 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.

用法

¥Usage

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

export default defineConfig({
use: {
isMobile: false,
},
});

类型

¥Type


javaScriptEnabled

Added in: v1.10 testOptions.javaScriptEnabled

是否在上下文中启用 JavaScript。默认为 true。了解有关 禁用 JavaScript 的更多信息。

¥Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.

用法

¥Usage

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

export default defineConfig({
use: {
javaScriptEnabled: false,
},
});

类型

¥Type


launchOptions

Added in: v1.10 testOptions.launchOptions

用于启动浏览器的选项,传递给 browserType.launch()。特定选项 testOptions.headlesstestOptions.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.

用法

¥Usage

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

export default defineConfig({
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
launchOptions: {
args: ['--start-maximized']
}
}
}
]
});

类型

¥Type


locale

Added in: v1.10 testOptions.locale

指定用户区域设置,例如 en-GBde-DE 等。区域设置会影响 navigator.language 值、Accept-Language 请求标头值以及数字和日期格式规则。默认为系统默认区域设置。在我们的 模拟指南 中了解有关模拟的更多信息。

¥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 the system default locale. Learn more about emulation in our emulation guide.

用法

¥Usage

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

export default defineConfig({
use: {
locale: 'it-IT',
},
});

类型

¥Type


Added in: v1.10 testOptions.navigationTimeout

每个导航操作的超时时间(以毫秒为单位)。默认为 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().

用法

¥Usage

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

export default defineConfig({
use: {
navigationTimeout: 3000,
},
});

了解有关 各种超时 的更多信息。

¥Learn more about various timeouts.

类型

¥Type


offline

Added in: v1.10 testOptions.offline

是否模拟网络离线。默认为 false。了解有关 网络模拟 的更多信息。

¥Whether to emulate network being offline. Defaults to false. Learn more about network emulation.

用法

¥Usage

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

export default defineConfig({
use: {
offline: true
},
});

类型

¥Type


permissions

Added in: v1.10 testOptions.permissions

授予此上下文中所有页面的权限列表。详细信息请参见 browserContext.grantPermissions()。默认为无。

¥A list of permissions to grant to all pages in this context. See browserContext.grantPermissions() for more details. Defaults to none.

用法

¥Usage

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

export default defineConfig({
use: {
permissions: ['notifications'],
},
});

类型

¥Type


proxy

Added in: v1.10 testOptions.proxy

网络代理设置。

¥Network proxy settings.

用法

¥Usage

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

export default defineConfig({
use: {
proxy: {
server: 'http://myproxy.com:3128',
bypass: 'localhost',
},
},
});

类型

¥Type

用于所有请求的代理。支持 HTTP 和 SOCKS 代理,例如 http://myproxy.com:3128socks5://myproxy.com:3128。缩写形式 myproxy.com:3128 被视为 HTTP 代理。

¥Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.

用于绕过代理的可选逗号分隔域,例如 ".com, chromium.org, .domain.com"

¥Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".

如果 HTTP 代理需要身份验证,则使用可选的用户名。

¥Optional username to use if HTTP proxy requires authentication.

如果 HTTP 代理需要身份验证,则使用可选密码。

¥Optional password to use if HTTP proxy requires authentication.


screenshot

Added in: v1.10 testOptions.screenshot

每次测试后是否自动截图。默认为 'off'

¥Whether to automatically capture a screenshot after each test. Defaults to 'off'.

  • 'off':不要捕获屏幕截图。

    ¥'off': Do not capture screenshots.

  • 'on':每次测试后捕获屏幕截图。

    ¥'on': Capture screenshot after each test.

  • 'only-on-failure':每次测试失败后捕获屏幕截图。

    ¥'only-on-failure': Capture screenshot after each test failure.

  • 'on-first-failure':在每个测试第一次失败后捕获屏幕截图。

    ¥'on-first-failure': Capture screenshot after each test's first failure.

用法

¥Usage

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

export default defineConfig({
use: {
screenshot: 'only-on-failure',
},
});

了解有关 自动截图 的更多信息。

¥Learn more about automatic screenshots.

类型

¥Type

  • 对象 | "off" | "on" | "only-on-failure" | "on-first-failure"

    ¥Object | "off" | "on" | "only-on-failure" | "on-first-failure"

    • mode "off" | "on" | "only-on-failure" | "on-first-failure"

      自动截图模式。

      ¥Automatic screenshot mode.

如果为 true,则截取完整可滚动页面的屏幕截图,而不是当前可见的视口。默认为 false

¥When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Defaults to false.

  • omitBackground boolean (optional)

隐藏默认的白色背景并允许捕获透明的屏幕截图。不适用于 jpeg 图片。默认为 false

¥Hides default white background and allows capturing screenshots with transparency. Not applicable to jpeg images. Defaults to false.


serviceWorkers

Added in: v1.10 testOptions.serviceWorkers

是否允许站点注册 Service Worker。默认为 'allow'

¥Whether to allow sites to register Service workers. Defaults to 'allow'.

  • 'allow'服务工作进程 可以注册。

    ¥'allow': Service Workers can be registered.

  • 'block':Playwright 将阻止所有服务工作进程的注册。

    ¥'block': Playwright will block all registration of Service Workers.

用法

¥Usage

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

export default defineConfig({
use: {
serviceWorkers: 'allow'
},
});

类型

¥Type

  • "allow" | "block"

storageState

Added in: v1.10 testOptions.storageState

了解有关 存储状态和授权 的更多信息。

¥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().

用法

¥Usage

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

export default defineConfig({
use: {
storageState: 'storage-state.json',
},
});

类型

¥Type

需要域和路径。为了使 cookie 也适用于所有子域,请在域前添加一个点,如下所示:".example.com"

¥Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com"

域名和路径为必填项

¥Domain and path are required

Unix 时间以秒为单位。

¥Unix time in seconds.

  • sameSite "严格的" | "Lax" | "没有任何"

    ¥sameSite "Strict" | "Lax" | "None"

    同一站点标志

    ¥sameSite flag

为上下文设置的 Cookie

¥Cookies to set for context

localStorage 设置上下文

¥localStorage to set for context

细节

¥Details

当在配置中设置存储状态时,可以重置文件的存储状态:

¥When storage state is set up in the config, it is possible to reset storage state for a file:

not-signed-in.spec.ts
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 testOptions.testIdAttribute

要在 page.getByTestId() 中使用的自定义属性。默认使用 data-testid

¥Custom attribute to be used in page.getByTestId(). data-testid is used by default.

用法

¥Usage

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

export default defineConfig({
use: {
testIdAttribute: 'pw-test-id',
},
});

timezoneId

Added in: v1.10 testOptions.timezoneId

更改上下文的时区。有关支持的时区 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.

用法

¥Usage

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

export default defineConfig({
use: {
timezoneId: 'Europe/Rome',
},
});

类型

¥Type


trace

Added in: v1.10 testOptions.trace

是否记录每个测试的跟踪。默认为 'off'

¥Whether to record trace for each test. Defaults to 'off'.

  • 'off':不记录痕迹。

    ¥'off': Do not record trace.

  • 'on':记录每次测试的跟踪。

    ¥'on': Record trace for each test.

  • 'on-first-retry':仅在第一次重试测试时记录跟踪。

    ¥'on-first-retry': Record trace only when retrying a test for the first time.

  • 'on-all-retries':仅在重试测试时记录跟踪。

    ¥'on-all-retries': Record trace only when retrying a test.

  • 'retain-on-failure':记录每次测试的跟踪。当测试运行通过后,删除记录的跟踪。

    ¥'retain-on-failure': Record trace for each test. When test run passes, remove the recorded trace.

  • 'retain-on-first-failure':记录每个测试首次运行的跟踪,但不记录重试。当测试运行通过后,删除记录的跟踪。

    ¥'retain-on-first-failure': Record trace for the first run of each test, but not for retries. When test run passes, remove the recorded trace.

要获得更多控制,请传递指定 mode 和要启用的跟踪功能的对象。

¥For more control, pass an object that specifies mode and trace features to enable.

用法

¥Usage

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

export default defineConfig({
use: {
trace: 'on-first-retry'
},
});

了解有关 记录痕迹 的更多信息。

¥Learn more about recording trace.

类型

¥Type

  • 对象 | "off" | "on" | "retain-on-failure" | "on-first-retry" | "retain-on-first-failure"

    ¥Object | "off" | "on" | "retain-on-failure" | "on-first-retry" | "retain-on-first-failure"

    • mode "off" | "on" | "retain-on-failure" | "on-first-retry" | "on-all-retries" | "retain-on-first-failure"

      轨迹记录模式。

      ¥Trace recording mode.

是否包含测试附件。默认为 true。可选的。

¥Whether to include test attachments. Defaults to true. Optional.

追踪过程中是否截屏。屏幕截图用于构建时间线预览。默认为 true。可选的。

¥Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview. Defaults to true. Optional.

是否在每个操作上捕获 DOM 快照。默认为 true。可选的。

¥Whether to capture DOM snapshot on every action. Defaults to true. Optional.

是否包含跟踪操作的源文件。默认为 true。可选的。

¥Whether to include source files for trace actions. Defaults to true. Optional.


userAgent

Added in: v1.10 testOptions.userAgent

在此上下文中使用的特定用户代理。

¥Specific user agent to use in this context.

用法

¥Usage

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

export default defineConfig({
use: {
userAgent: 'some custom ua',
},
});

类型

¥Type


video

Added in: v1.10 testOptions.video

是否为每次测试录制视频。默认为 'off'

¥Whether to record video for each test. Defaults to 'off'.

  • 'off':不要录制视频。

    ¥'off': Do not record video.

  • 'on':为每次测试录制视频。

    ¥'on': Record video for each test.

  • 'retain-on-failure':为每个测试录制视频,但从成功的测试运行中删除所有视频。

    ¥'retain-on-failure': Record video for each test, but remove all videos from successful test runs.

  • 'on-first-retry':仅在第一次重试测试时录制视频。

    ¥'on-first-retry': Record video only when retrying a test for the first time.

要控制视频大小,请传递具有 modesize 属性的对象。如果未指定视频大小,则它将等于缩小到 800x800 的 testOptions.viewport。如果未明确配置 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.

用法

¥Usage

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

export default defineConfig({
use: {
video: 'on-first-retry',
},
});

了解有关 录制视频 的更多信息。

¥Learn more about recording video.

类型

¥Type

  • 对象 | "off" | "on" | "retain-on-failure" | "on-first-retry"

    ¥Object | "off" | "on" | "retain-on-failure" | "on-first-retry"

    • mode "off" | "on" | "retain-on-failure" | "on-first-retry"

      视频录制模式。

      ¥Video recording mode.

录制视频的大小。可选的。

¥Size of the recorded video. Optional.


viewport

Added in: v1.10 testOptions.viewport

模拟每个页面的一致视口。默认为 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.

用法

¥Usage

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

export default defineConfig({
use: {
viewport: { width: 100, height: 100 },
},
});

类型

¥Type

页面宽度(以像素为单位)。

¥page width in pixels.

页面高度(以像素为单位)。

¥page height in pixels.