测试使用选项
介绍
除了配置测试运行器,您还可以配置 Emulation、Network 和 Recording 用于 Browser 或 BrowserContext。这些选项通过 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',
},
});
选项 | 描述 |
---|---|
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 | 上下文 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() 接受的任何选项都可以分别放在 use
部分的 launchOptions
或 contextOptions
中。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});
然而,大多数常用选项(如 headless
或 viewport
)可直接在 use
部分中获得 - 请参阅基本选项、模拟 或 网络。
显式上下文创建和选项继承
如果使用内置的 browser
夹具,调用 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 }) => {
// ...
});
});