Skip to main content

测试使用选项

介绍

Introduction

除了配置测试运行器之外,你还可以为 浏览器BrowserContext 配置 模拟网络记录。这些选项被传递到 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://127.0.0.1:3000',

// Populates context with given storage state.
storageState: 'state.json',
},
});
OptionDescription
testOptions.baseURLBase URL used for all pages in the context. Allows navigating by using just the path, for example page.goto('/settings').
testOptions.storageStatePopulates context with given storage state. Useful for easy authentication, learn more.

模拟选项

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 },
},
});
OptionDescription
testOptions.colorSchemeEmulates 'prefers-colors-scheme' media feature, supported values are 'light', 'dark', 'no-preference'
testOptions.geolocationContext geolocation.
testOptions.localeEmulates the user locale, for example en-GB, de-DE, etc.
testOptions.permissionsA list of permissions to grant to all pages in the context.
testOptions.timezoneIdChanges the timezone of the context.
testOptions.viewportViewport used for all pages in the context.

网络选项

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',
},
},
});
OptionDescription
testOptions.acceptDownloadsWhether to automatically download all the attachments, defaults to true. Learn more about working with downloads.
testOptions.extraHTTPHeadersAn object containing additional HTTP headers to be sent with every request. All header values must be strings.
testOptions.httpCredentialsCredentials for HTTP authentication.
testOptions.ignoreHTTPSErrorsWhether to ignore HTTPS errors during navigation.
testOptions.offlineWhether to emulate network being offline.
testOptions.proxyProxy settings used for all pages in the test.
注意

你无需配置任何内容即可模拟网络请求。只需定义一个自定义 路由 来模拟浏览器上下文的网络即可。请参阅我们的 网络模拟指南 了解更多信息。

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'
},
});
OptionDescription
testOptions.screenshotCapture screenshots of your test. Options include 'off', 'on' and 'only-on-failure'
testOptions.tracePlaywright can produce test traces while running the tests. Later on, you can view the trace and get detailed information about Playwright execution by opening Trace Viewer. Options include: 'off', 'on', 'retain-on-failure' and 'on-first-retry'
testOptions.videoPlaywright can record videos for your tests. Options include: 'off', 'on', 'retain-on-failure' and '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',
},
});
OptionDescription
testOptions.actionTimeoutTimeout for each Playwright action in milliseconds. Defaults to 0 (no timeout). Learn more about timeouts and how to set them for a single test.
testOptions.browserNameName of the browser that runs tests. Defaults to 'chromium'. Options include chromium, firefox, or webkit.
testOptions.bypassCSPToggles bypassing Content-Security-Policy. Useful when CSP includes the production origin. Defaults to false.
testOptions.channelBrowser channel to use. Learn more about different browsers and channels.
testOptions.headlessWhether to run the browser in headless mode meaning no browser is shown when running tests. Defaults to true.
testOptions.testIdAttributeChanges the default data-testid attribute used by Playwright locators.

更多浏览器和上下文选项

More browser and context options

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

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

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

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

但是,最常见的如 headlessviewport 可以直接在 use 部分中找到 - 参见 基本选项emulationnetwork

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。例如,你可以通过将 locale 添加到 Playwright 配置的 use 选项来设置全局使用的区域设置,然后使用配置中的 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 }) => {
// ...
});

描述块内的工作原理相同。例如,要在具有法语语言环境的描述块中运行测试:

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 }) => {
// ...
});
});