测试使用选项
简介
除了配置测试运行器外,您还可以为Browser或BrowserContext配置Emulation、Network和Recording。这些选项会被传递到Playwright配置中的use: {}
对象。
基本选项
为所有测试设置基础URL和存储状态:
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',
},
});
Option | Description |
---|---|
testOptions.baseURL | Base URL used for all pages in the context. Allows navigating by using just the path, for example page.goto('/settings') . |
testOptions.storageState | 使用给定的存储状态填充上下文。便于快速进行身份验证,了解更多。 |
模拟选项
使用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 },
},
});
Option | Description |
---|---|
testOptions.colorScheme | Emulates 'prefers-colors-scheme' media feature, supported values are 'light' and 'dark' |
testOptions.geolocation | Context geolocation. |
testOptions.locale | Emulates the user locale, for example en-GB , de-DE , etc. |
testOptions.permissions | 授予上下文中所有页面的权限列表。 |
testOptions.timezoneId | 更改上下文的时区。 |
testOptions.viewport | 用于上下文中所有页面的视口。 |
网络选项
可用的网络配置选项:
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',
},
},
});
Option | Description |
---|---|
testOptions.acceptDownloads | Whether to automatically download all the attachments, defaults to true . Learn more about working with downloads. |
testOptions.extraHTTPHeaders | 一个包含要随每个请求发送的额外HTTP头的对象。所有头值必须是字符串。 |
testOptions.httpCredentials | HTTP认证的凭证。 |
testOptions.ignoreHTTPSErrors | 是否在导航期间忽略HTTPS错误。 |
testOptions.offline | 是否模拟网络离线状态。 |
testOptions.proxy | 用于测试中所有页面的代理设置。 |
您无需配置任何内容即可模拟网络请求。只需定义一个自定义Route来为浏览器上下文模拟网络。查看我们的network mocking guide以了解更多信息。
录制选项
使用Playwright您可以捕获屏幕截图、录制视频以及测试的跟踪记录。默认情况下这些功能是关闭的,但您可以通过在playwright.config.js
文件中设置screenshot
、video
和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'
},
});
Option | Description |
---|---|
testOptions.screenshot | Capture screenshots of your test. Options include 'off' , 'on' and 'only-on-failure' |
testOptions.trace | Playwright 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.video | Playwright can record videos for your tests. Options include: 'off' , 'on' , 'retain-on-failure' and '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',
},
});
Option | Description |
---|---|
testOptions.actionTimeout | Timeout 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.browserName | Name of the browser that runs tests. Defaults to 'chromium'. Options include chromium , firefox , or webkit . |
testOptions.bypassCSP | Toggles bypassing Content-Security-Policy. Useful when CSP includes the production origin. Defaults to false . |
testOptions.channel | Browser channel to use. Learn more about different browsers and channels. |
testOptions.headless | Whether to run the browser in headless mode meaning no browser is shown when running tests. Defaults to true . |
testOptions.testIdAttribute | Changes the default data-testid attribute used by Playwright locators. |
更多浏览器和上下文选项
任何被browserType.launch()或browser.newContext()接受的选项都可以分别放入use
部分的launchOptions
或contextOptions
中。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});
然而,最常见的选项如headless
或viewport
都可以直接在use
部分找到 - 参见基本选项、模拟或网络。
显式上下文创建与选项继承
如果使用内置的browser
fixture,调用browser.newContext()将创建一个继承自配置选项的上下文:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
userAgent: 'some custom ua',
viewport: { width: 100, height: 100 },
},
});
一个示例测试,展示初始上下文选项的设置:
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,也可以按项目或按测试配置。例如,你可以通过将locale
添加到Playwright配置的use
选项中来全局设置要使用的区域设置,然后在配置中使用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 }) => {
// ...
});
});