测试 use 选项
简介
除了配置测试运行器,您还可以为浏览器或浏览器上下文配置模拟、网络和录制。这些选项被传递到 Playwright 配置中的 use: {}
对象。
基本选项
为所有测试设置基本 URL 和存储状态
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// Base URL to use in actions like `await page.goto('/')`.
baseURL: 'https://:3000',
// Populates context with given storage state.
storageState: 'state.json',
},
});
选项 | 描述 |
---|---|
testOptions.baseURL | 上下文中所有页面使用的基本 URL。允许仅使用路径进行导航,例如 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 },
},
});
选项 | 描述 |
---|---|
testOptions.colorScheme | 模拟 'prefers-colors-scheme' 媒体特性,支持的值为 'light' 和 'dark' |
testOptions.geolocation | 上下文地理位置。 |
testOptions.locale | 模拟用户区域设置,例如 en-GB 、de-DE 等。 |
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',
},
},
});
选项 | 描述 |
---|---|
testOptions.acceptDownloads | 是否自动下载所有附件,默认为 true 。了解更多关于处理下载的信息。 |
testOptions.extraHTTPHeaders | 一个包含要随每个请求发送的额外 HTTP 标头的对象。所有标头值必须是字符串。 |
testOptions.httpCredentials | HTTP 身份验证的凭据。 |
testOptions.ignoreHTTPSErrors | 导航期间是否忽略 HTTPS 错误。 |
testOptions.offline | 是否模拟网络处于离线状态。 |
testOptions.proxy | 用于测试中所有页面的代理设置。 |
录制选项
使用 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'
},
});
选项 | 描述 |
---|---|
testOptions.screenshot | 捕获测试的屏幕截图。选项包括 'off' 、'on' 和 'only-on-failure' |
testOptions.trace | Playwright 可以在运行测试时生成测试跟踪。之后,您可以通过打开跟踪查看器来查看跟踪并获取有关 Playwright 执行的详细信息。选项包括:'off' 、'on' 、'retain-on-failure' 和 'on-first-retry' |
testOptions.video | Playwright 可以为您的测试录制视频。选项包括:'off' 、'on' 、'retain-on-failure' 和 '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',
},
});
选项 | 描述 |
---|---|
testOptions.actionTimeout | 每个 Playwright 操作的超时时间(毫秒)。默认为 0 (无超时)。了解有关超时以及如何为单个测试设置超时的更多信息。 |
testOptions.browserName | 运行测试的浏览器名称。默认为 'chromium'。选项包括 chromium 、firefox 或 webkit 。 |
testOptions.bypassCSP | 切换是否绕过内容安全策略 (Content-Security-Policy)。当 CSP 包含生产来源时非常有用。默认为 false 。 |
testOptions.channel | 要使用的浏览器渠道。了解更多关于不同浏览器和渠道的信息。 |
testOptions.headless | 是否在无头模式下运行浏览器,这意味着在运行测试时不显示浏览器。默认为 true 。 |
testOptions.testIdAttribute | 更改 Playwright 定位器使用的默认data-testid 属性。 |
更多浏览器和上下文选项
任何被 browserType.launch()、browser.newContext() 或 browserType.connect() 接受的选项,都可以分别放入 use
部分的 launchOptions
、contextOptions
或 connectOptions
中。
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 }) => {
// ...
});
});
重置选项
您可以将选项重置为配置文件中定义的值。考虑以下设置 baseURL
的配置
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'https://playwright.net.cn',
},
});
现在您可以为一个文件配置 baseURL
,也可以选择为单个测试禁用。
import { test } from '@playwright/test';
// Configure baseURL for this file.
test.use({ baseURL: 'https://playwright.net.cn/docs/intro' });
test('check intro contents', async ({ page }) => {
// This test will use "https://playwright.net.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.net.cn" base url as defined in the config.
});
});
如果您想将值完全重置为 undefined
,请使用长格式的夹具表示法。
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.
});