Skip to main content

配置(使用)

介绍

🌐 Introduction

除了配置测试运行器之外,你还可以为 BrowserBrowserContext 配置 模拟网络录制。这些选项会传递给 Playwright 配置中的 use: {} 对象。

🌐 In addition to configuring the test runner you can also configure Emulation, Network and Recording for the Browser or BrowserContext. These options are passed to the use: {} object in the Playwright config.

基本选项

🌐 Basic Options

设置所有测试的基本 URL 和存储状态:

🌐 Set the base URL and storage state for all tests:

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

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

// Populates context with given storage state.
storageState: 'state.json',
},
});
选项描述
testOptions.baseURL用于上下文中所有页面的基础 URL。允许仅使用路径进行导航,例如 page.goto('/settings')
testOptions.storageState使用给定的存储状态填充上下文。便于轻松进行认证,了解更多

模拟选项

🌐 Emulation Options

使用 Playwright,你可以模拟真实设备,例如手机或平板电脑。有关模拟设备的更多信息,请参阅我们的项目指南。你还可以模拟所有测试或特定测试的"geolocation""locale""timezone",以及设置"permissions"以显示通知或更改"colorScheme"。请参阅我们的模拟指南以了解更多信息。

🌐 With Playwright you can emulate a real device such as a mobile phone or tablet. See our guide on projects for more info on emulating devices. You can also emulate the "geolocation", "locale" and "timezone" for all tests or for a specific test as well as set the "permissions" to show notifications or change the "colorScheme". See our Emulation guide to learn more.

playwright.config.ts
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上下文的 地理位置
testOptions.locale模拟 用户语言环境,例如 en-GBde-DE 等。
testOptions.permissions给予上下文中所有页面的 权限 列表。
testOptions.timezoneId更改上下文的 时区
testOptions.viewport上下文中所有页面使用的 视口

网络选项

🌐 Network Options

配置网络的可用选项:

🌐 Available options to configure networking:

playwright.config.ts
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.httpCredentialsHTTP 认证 的凭证。
testOptions.ignoreHTTPSErrors导航过程中是否忽略 HTTPS 错误。
testOptions.offline是否模拟网络离线状态。
testOptions.proxy测试中所有页面使用的 代理设置
note

你不需要配置任何内容就可以模拟网络请求。只需定义一个自定义的 Route 来为浏览器上下文模拟网络。查看更多信息,请参阅我们的 网络模拟指南

🌐 You don't have to configure anything to mock network requests. Just define a custom Route that mocks the network for a browser context. See our network mocking guide to learn more. :::

录音选项

🌐 Recording Options

使用 Playwright,你可以捕捉截图、录制视频以及记录测试的跟踪信息。默认情况下,这些功能是关闭的,但你可以通过在你的 playwright.config.js 文件中设置 screenshotvideotrace 选项来启用它们。

🌐 With Playwright you can capture screenshots, record videos as well as traces of your test. By default these are turned off but you can enable them by setting the screenshot, video and trace options in your playwright.config.js file.

跟踪文件、截图和视频将出现在测试输出目录中,通常为 test-results

🌐 Trace files, screenshots and videos will appear in the test output directory, typically test-results.

playwright.config.ts
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.tracePlaywright 可以在运行测试时生成测试跟踪。稍后,你可以通过打开 Trace Viewer 查看跟踪并获取关于 Playwright 执行的详细信息。选项包括:'off''on''retain-on-failure''on-first-retry'
testOptions.videoPlaywright 可以为你的测试录制视频。选项包括:'off''on''retain-on-failure''on-first-retry'

其他选项

🌐 Other Options

playwright.config.ts
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'。可选值包括 chromiumfirefoxwebkit
testOptions.bypassCSP切换是否绕过内容安全策略 (CSP)。当 CSP 包含生产源时很有用。默认值为 false
testOptions.channel要使用的浏览器通道。了解更多关于不同浏览器和通道的信息,请点击 这里
testOptions.headless是否以无界面模式运行浏览器,也就是运行测试时不显示浏览器。默认值为 true
testOptions.testIdAttribute更改 Playwright 定位器使用的默认 data-testid 属性

更多浏览器和上下文选项

🌐 More browser and context options

任何被 browserType.launch()browser.newContext()browserType.connect() 接受的选项,都可以分别放入 use 部分的 launchOptionscontextOptionsconnectOptions

🌐 Any options accepted by browserType.launch(), browser.newContext() or browserType.connect() can be put into launchOptions, contextOptions or connectOptions respectively in the use section.

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

export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});

然而,大多数常见的选项,如 headlessviewport,可以直接在 use 部分找到——请参阅 基本选项模拟网络

🌐 However, most common ones like headless or viewport are available directly in the use section - see basic options, emulation or network.

显式上下文创建和选项继承

🌐 Explicit Context Creation and Option Inheritance

如果使用内置的 browser 夹具,调用 browser.newContext() 将创建一个从配置继承选项的上下文:

🌐 If using the built-in browser fixture, calling browser.newContext() will create a context with options inherited from the config:

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

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

说明设置初始上下文选项的示例测试:

🌐 An example test illustrating the initial context options are set:

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();
});

配置范围

🌐 Configuration Scopes

你可以在全局、每个项目或每个测试中配置 Playwright。例如,你可以通过在 Playwright 配置的 use 选项中添加 locale 来设置全局使用的语言环境,然后使用配置中的 project 选项为特定项目覆盖它。你也可以通过在测试文件中添加 test.use({}) 并传入选项,为特定测试覆盖它。

🌐 You can configure Playwright globally, per project, or per test. For example, you can set the locale to be used globally by adding locale to the use option of the Playwright config, and then override it for a specific project using the project option in the config. You can also override it for a specific test by adding test.use({}) in the test file and passing in the options.

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

export default defineConfig({
use: {
locale: 'en-GB'
},
});

你可以在 Playwright 配置中使用 project 选项覆盖特定项目的设置。

🌐 You can override options for a specific project using the project option in the Playwright config.

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

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

你可以通过使用 test.use() 方法并传入选项来覆盖特定测试文件的选项。例如,要对特定测试使用法语地区运行测试:

🌐 You can override options for a specific test file by using the test.use() method and passing in the options. For example to run tests with the French locale for a specific test:

import { test, expect } from '@playwright/test';

test.use({ locale: 'fr-FR' });

test('example', async ({ page }) => {
// ...
});

在 describe 块中同样适用。例如,要在带有法语区域设置的 describe 块中运行测试:

🌐 The same works inside a describe block. For example to run tests in a describe block with the French locale:

import { test, expect } from '@playwright/test';

test.describe('french language block', () => {

test.use({ locale: 'fr-FR' });

test('example', async ({ page }) => {
// ...
});
});

重置选项

🌐 Reset an option

你可以将某个选项重置为配置文件中定义的值。请考虑以下设置了 baseURL 的配置:

🌐 You can reset an option to the value defined in the config file. Consider the following config that sets a baseURL:

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

export default defineConfig({
use: {
baseURL: 'https://playwright.nodejs.cn',
},
});

你现在可以为一个文件配置 baseURL,也可以选择对单个测试退出。

🌐 You can now configure baseURL for a file, and also opt-out for a single test.

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

// Configure baseURL for this file.
test.use({ baseURL: 'https://playwright.nodejs.cn/docs/intro' });

test('check intro contents', async ({ page }) => {
// This test will use "https://playwright.nodejs.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.nodejs.cn" base url as defined in the config.
});
});

如果你想将值完全重置为 undefined,请使用长格式夹具表示法。

🌐 If you would like to completely reset the value to undefined, use a long-form fixture notation.

intro.spec.ts
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.
});