配置 (使用)
简介
除了配置测试运行器之外,您还可以为 Browser 或 BrowserContext 配置 仿真、网络和 录制。这些选项会传递到 Playwright 配置中的 use: {} 对象。
基本选项
为所有测试设置基本 URL 和存储状态
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: 'https://:3000',
// Populates context with given storage state.
storageState: 'state.json',
},
});
| 选项 | 描述 |
|---|---|
| testOptions.baseURL | Context 中所有页面的基本 URL。允许使用仅路径进行导航,例如 page.goto('/settings')。 |
| testOptions.storageState | 使用给定的存储状态填充 Context。对于便捷的身份验证非常有用,了解更多。 |
仿真选项
使用 Playwright,您可以仿真真实设备,例如手机或平板电脑。有关仿真设备的更多信息,请参阅我们的 项目指南。您还可以为所有测试或特定测试仿真 "geolocation"、"locale" 和 "timezone",以及设置 "permissions" 以显示通知或更改 "colorScheme"。要了解更多信息,请参阅我们的 仿真 指南。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Emulates `'prefers-colors-scheme'` media feature.
colorScheme: 'dark',
// Context geolocation.
geolocation: { longitude: 12.492507, latitude: 41.889938 },
// Emulates the user locale.
locale: 'en-GB',
// Grants specified permissions to the browser context.
permissions: ['geolocation'],
// Emulates the user timezone.
timezoneId: 'Europe/Paris',
// Viewport used for all pages in the context.
viewport: { width: 1280, height: 720 },
},
});
| 选项 | 描述 |
|---|---|
| testOptions.colorScheme | 仿真 'prefers-colors-scheme' 媒体功能,支持的值为 'light' 和 'dark' |
| testOptions.geolocation | Context 的 地理位置。 |
| testOptions.locale | 仿真 用户区域设置,例如 en-GB、de-DE 等。 |
| testOptions.permissions | 要授予 Context 中所有页面的 权限 列表。 |
| testOptions.timezoneId | 更改 Context 的 时区。 |
| testOptions.viewport | Context 中所有页面的 视口。 |
网络选项
配置网络的可用选项
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Whether to automatically download all the attachments.
acceptDownloads: false,
// An object containing additional HTTP headers to be sent with every request.
extraHTTPHeaders: {
'X-My-Header': 'value',
},
// Credentials for HTTP authentication.
httpCredentials: {
username: 'user',
password: 'pass',
},
// Whether to ignore HTTPS errors during navigation.
ignoreHTTPSErrors: true,
// Whether to emulate network being offline.
offline: true,
// Proxy settings used for all pages in the test.
proxy: {
server: 'http://myproxy.com:3128',
bypass: 'localhost',
},
},
});
| 选项 | 描述 |
|---|---|
| testOptions.acceptDownloads | 是否自动下载所有附件,默认为 true。有关处理下载的更多信息。 |
| testOptions.extraHTTPHeaders | 一个包含要随每个请求发送的额外 HTTP 标头的对象。所有标头值必须是字符串。 |
| testOptions.httpCredentials | 用于 HTTP 身份验证 的凭据。 |
| testOptions.ignoreHTTPSErrors | 导航期间是否忽略 HTTPS 错误。 |
| testOptions.offline | 是否仿真网络离线。 |
| testOptions.proxy | 测试中所有页面使用的 代理设置。 |
录制选项
使用 Playwright,您可以捕获屏幕截图、录制视频以及测试的跟踪。默认情况下,这些是关闭的,但您可以通过在 playwright.config.js 文件中设置 screenshot、video 和 trace 选项来启用它们。
Trace 文件、屏幕截图和视频将出现在测试输出目录中,通常是 test-results。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Capture screenshot after each test failure.
screenshot: 'only-on-failure',
// Record trace only when retrying a test for the first time.
trace: 'on-first-retry',
// Record video only when retrying a test for the first time.
video: 'on-first-retry'
},
});
| 选项 | 描述 |
|---|---|
| testOptions.screenshot | 捕获测试的 屏幕截图。选项包括 'off'、'on' 和 'only-on-failure' |
| testOptions.trace | Playwright 在运行测试时可以生成测试跟踪。稍后,您可以打开 Trace Viewer 来查看跟踪并获取有关 Playwright 执行的详细信息。选项包括:'off'、'on'、'retain-on-failure' 和 'on-first-retry' |
| testOptions.video | Playwright 可以为您的测试录制 视频。选项包括:'off'、'on'、'retain-on-failure' 和 'on-first-retry' |
其他选项
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Maximum time each action such as `click()` can take. Defaults to 0 (no limit).
actionTimeout: 0,
// Name of the browser that runs tests. For example `chromium`, `firefox`, `webkit`.
browserName: 'chromium',
// Toggles bypassing Content-Security-Policy.
bypassCSP: true,
// Channel to use, for example "chrome", "chrome-beta", "msedge", "msedge-beta".
channel: 'chrome',
// Run browser in headless mode.
headless: false,
// Change the default data-testid attribute.
testIdAttribute: 'pw-test-id',
},
});
| 选项 | 描述 |
|---|---|
| testOptions.actionTimeout | 每次 Playwright 操作的超时时间(以毫秒为单位)。默认为 0(无超时)。有关 超时以及如何为单个测试设置超时的更多信息。 |
| testOptions.browserName | 运行测试的浏览器名称。默认为 'chromium'。选项包括 chromium、firefox 或 webkit。 |
| testOptions.bypassCSP | 切换是否绕过内容安全策略。当 CSP 包含生产源时很有用。默认为 false。 |
| testOptions.channel | 要使用的浏览器通道。有关不同浏览器和通道的更多信息。 |
| testOptions.headless | 是否以无头模式运行浏览器,这意味着在运行测试时不会显示浏览器。默认为 true。 |
| testOptions.testIdAttribute | 更改 Playwright 定位器使用的默认 data-testid 属性。 |
更多浏览器和 Context 选项
browserType.launch()、browser.newContext() 或 browserType.connect() 接受的任何选项都可以分别放入 use 部分的 launchOptions、contextOptions 或 connectOptions 中。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});
然而,最常见的选项,如 headless 或 viewport,可以直接在 use 部分中使用,请参阅 基本选项、仿真 或 网络。
显式 Context 创建和选项继承
如果使用内置的 browser fixture,调用 browser.newContext() 将创建一个继承自配置的选项的 Context。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
userAgent: 'some custom ua',
viewport: { width: 100, height: 100 },
},
});
一个说明初始 Context 选项设置的示例测试
test('should inherit use options on context when using built-in browser fixture', async ({
browser,
}) => {
const context = await browser.newContext();
const page = await context.newPage();
expect(await page.evaluate(() => navigator.userAgent)).toBe('some custom ua');
expect(await page.evaluate(() => window.innerWidth)).toBe(100);
await context.close();
});
配置范围
您可以全局、按项目或按测试配置 Playwright。例如,您可以通过在 Playwright 配置的 use 选项中添加 locale 来设置全局使用的区域设置,然后使用配置中的 project 选项为特定项目覆盖它。您还可以通过在测试文件中添加 test.use({}) 并传入选项来为特定测试覆盖它。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
locale: 'en-GB'
},
});
您可以使用 Playwright 配置中的 project 选项为特定项目覆盖选项。
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
locale: 'de-DE',
},
},
],
});
您可以使用 test.use() 方法并传入选项来为特定测试文件覆盖选项。例如,为特定测试运行使用法语区域设置的测试
import { test, expect } from '@playwright/test';
test.use({ locale: 'fr-FR' });
test('example', async ({ page }) => {
// ...
});
在 describe 块中也同样适用。例如,在 describe 块中运行使用法语区域设置的测试
import { test, expect } from '@playwright/test';
test.describe('french language block', () => {
test.use({ locale: 'fr-FR' });
test('example', async ({ page }) => {
// ...
});
});
重置选项
您可以将选项重置为在配置文件中定义的值。考虑以下设置了 baseURL 的配置
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'https://playwright.net.cn',
},
});
现在您可以为一个文件配置 baseURL,也可以为单个测试选择退出。
import { test } from '@playwright/test';
// Configure baseURL for this file.
test.use({ baseURL: 'https://playwright.net.cn/docs/intro' });
test('check intro contents', async ({ page }) => {
// This test will use "https://playwright.net.cn/docs/intro" base url as defined above.
});
test.describe(() => {
// Reset the value to a config-defined one.
test.use({ baseURL: undefined });
test('can navigate to intro from the home page', async ({ page }) => {
// This test will use "https://playwright.net.cn" base url as defined in the config.
});
});
如果您想将值完全重置为 undefined,请使用长格式 fixture 表示法。
import { test } from '@playwright/test';
// Completely unset baseURL for this file.
test.use({
baseURL: [async ({}, use) => use(undefined), { scope: 'test' }],
});
test('no base url', async ({ page }) => {
// This test will not have a base url.
});