跳至主要内容

测试使用选项

简介

除了配置测试运行器外,您还可以为BrowserBrowserContext配置EmulationNetworkRecording。这些选项会被传递到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://localhost: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.storageState使用给定的存储状态填充上下文。便于快速进行身份验证,了解更多

模拟选项

使用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 },
},
});
OptionDescription
testOptions.colorSchemeEmulates 'prefers-colors-scheme' media feature, supported values are 'light' and 'dark'
testOptions.geolocationContext geolocation.
testOptions.localeEmulates the user locale, for example en-GB, de-DE, etc.
testOptions.permissions授予上下文中所有页面的权限列表。
testOptions.timezoneId更改上下文的时区
testOptions.viewport用于上下文中所有页面的视口

网络选项

可用的网络配置选项:

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.extraHTTPHeaders一个包含要随每个请求发送的额外HTTP头的对象。所有头值必须是字符串。
testOptions.httpCredentialsHTTP认证的凭证。
testOptions.ignoreHTTPSErrors是否在导航期间忽略HTTPS错误。
testOptions.offline是否模拟网络离线状态。
testOptions.proxy用于测试中所有页面的代理设置
note

您无需配置任何内容即可模拟网络请求。只需定义一个自定义Route来为浏览器上下文模拟网络。查看我们的network mocking guide以了解更多信息。

录制选项

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

跟踪文件、截图和视频将出现在测试输出目录中,通常是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'

其他选项

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.

更多浏览器和上下文选项

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

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

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

然而,最常见的选项如headlessviewport都可以直接在use部分找到 - 参见基本选项模拟网络

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

如果使用内置的browser fixture,调用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 }) => {
// ...
});

同样的方法也适用于describe块内部。例如,要在describe块中以法语区域设置运行测试:

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

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

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

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