介绍
除了配置测试运行器之外,你还可以为 Browser 或 BrowserContext 配置 模拟、网络 和 记录。这些选项被传递到 Playwright 配置中的 use: {} 对象。
基本选项
设置所有测试的基本 URL 和存储状态:
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',
},
});
模拟选项
使用 Playwright,你可以模拟真实的设备,例如手机或平板电脑。有关模拟设备的更多信息,请参阅我们的 项目指导。你还可以为所有测试或特定测试模拟 "geolocation"、"locale" 和 "timezone",以及设置 "permissions" 以显示通知或更改 "colorScheme"。请参阅我们的 模拟 指南以了解更多信息。
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 },
},
});
网络选项
配置网络的可用选项:
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',
},
},
});
录音选项
使用 Playwright,你可以捕获屏幕截图、录制视频以及测试痕迹。默认情况下,这些功能是关闭的,但你可以通过在 playwright.config.js 文件中设置 screenshot、video 和 trace 选项来启用它们。
跟踪文件、屏幕截图和视频将出现在测试输出目录中,通常为 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'
},
});
其他选项
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',
},
});
更多浏览器和上下文选项
任何被 browserType.launch() 或 browser.newContext() 接受的选项都可以分别放入 use 部分的 launchOptions 或 contextOptions 中。
playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});
显式上下文创建和选项继承
如果使用内置的 browser 夹具,调用 browser.newContext() 将创建一个带有从配置继承的选项的上下文:
playwright.config.ts
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({}) 并传入选项来覆盖特定测试。
playwright.config.ts
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 }) => {
// ...
});
描述块内的工作原理相同。例如,要在具有法语语言环境的描述块中运行测试:
import { test, expect } from '@playwright/test';
test.describe('french language block', () => {
test.use({ locale: 'fr-FR' });
test('example', async ({ page }) => {
// ...
});
});