测试使用选项
介绍
除了配置测试运行器,你还可以为 Browser 或 BrowserContext 配置 模拟 (Emulation)、网络 (Network) 和 录制 (Recording)。这些选项通过 use: {}
对象在 Playwright 配置文件中传递。
基本选项
为所有测试设置基础 URL 和存储状态
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',
},
});
选项 | 描述 |
---|---|
testOptions.baseURL | 上下文 (context) 中所有页面使用的基础 URL。允许仅使用路径进行导航,例如 page.goto('/settings') 。 |
testOptions.storageState | 使用给定的存储状态填充上下文 (context)。对于简单的身份验证非常有用,了解更多。 |
模拟选项
使用 Playwright,你可以模拟真实设备,例如手机或平板电脑。有关模拟设备的更多信息,请参阅我们的 项目 (projects) 指南。你还可以为所有测试或特定测试模拟 “geolocation”、“locale” 和 “timezone”,以及设置 “permissions” 以显示通知或更改 “colorScheme”。请参阅我们的 模拟 (Emulation) 指南以了解更多信息。
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 | 上下文 (context) 地理位置 (geolocation)。 |
testOptions.locale | 模拟用户区域设置 (locale),例如 en-GB 、de-DE 等。 |
testOptions.permissions | 要授予上下文 (context) 中所有页面的 权限 (permissions) 列表。 |
testOptions.timezoneId | 更改上下文 (context) 的 时区 (timezone)。 |
testOptions.viewport | 上下文 (context) 中所有页面使用的 视口 (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 | 测试中所有页面使用的 代理 (Proxy) 设置。 |
你无需配置任何内容即可模拟网络请求。只需定义一个自定义的 Route,为浏览器上下文 (browser context) 模拟网络。请参阅我们的 网络模拟 (network mocking) 指南以了解更多信息。
录制选项
使用 Playwright,你可以捕获 屏幕截图 (screenshots)、录制 视频 (videos) 以及测试的 跟踪 (traces)。默认情况下,这些功能是关闭的,但你可以在 playwright.config.js
文件中设置 screenshot
、video
和 trace
选项来启用它们。
跟踪 (Trace) 文件、屏幕截图 (screenshots) 和 视频 (videos) 将出现在测试输出目录中,通常是 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 | 捕获测试的 屏幕截图 (screenshots)。选项包括 'off' 、'on' 和 'only-on-failure' |
testOptions.trace | Playwright 可以在运行测试时生成测试 跟踪 (traces)。稍后,你可以通过打开 跟踪查看器 (Trace Viewer) 查看跟踪 (trace) 并获取有关 Playwright 执行的详细信息。选项包括:'off' 、'on' 、'retain-on-failure' 和 'on-first-retry' |
testOptions.video | Playwright 可以为你的测试录制 视频 (videos)。选项包括:'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 (无超时)。了解更多关于 超时 (timeouts) 以及如何为单个测试设置它们的信息。 |
testOptions.browserName | 运行测试的浏览器名称。默认为 'chromium' 。选项包括 chromium 、firefox 或 webkit 。 |
testOptions.bypassCSP | 切换绕过 内容安全策略 (Content-Security-Policy)。当 CSP 包含生产来源时很有用。默认为 false 。 |
testOptions.channel | 要使用的浏览器通道 (channel)。了解更多关于不同浏览器和通道的信息。 |
testOptions.headless | 是否在 无头 (headless) 模式下运行浏览器,这意味着在运行测试时不会显示浏览器。默认为 true 。 |
testOptions.testIdAttribute | 更改 Playwright 定位器 (locators) 使用的默认 data-testid 属性。 |
更多浏览器和上下文选项
browserType.launch()
或 browser.newContext()
接受的任何选项都可以分别放入 use
部分的 launchOptions
或 contextOptions
中。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});
但是,大多数常见的选项,如 无头 (headless) 或 视口 (viewport),可以直接在 use
部分中使用 - 请参阅 基本选项 (basic options)、模拟 (emulation) 或 网络 (network)。
显式上下文创建和选项继承
如果使用内置的 browser
测试装置 (fixture),调用 browser.newContext()
将创建一个从配置 (config) 继承选项的上下文 (context)
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
userAgent: 'some custom ua',
viewport: { width: 100, height: 100 },
},
});
一个示例测试,说明了初始上下文 (context) 选项的设置
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。例如,你可以通过在 Playwright 配置 (config) 的 use
选项中添加 locale
来全局设置要使用的区域设置 (locale),然后使用配置 (config) 中的 project
选项为特定项目覆盖它。你还可以通过在测试文件中添加 test.use({})
并传入选项来为特定测试覆盖它。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
locale: 'en-GB'
},
});
你可以使用 Playwright 配置 (config) 中的 project
选项覆盖特定项目的选项。
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
locale: 'de-DE',
},
},
],
});
你可以通过使用 test.use()
方法并传入选项来覆盖特定测试文件的选项。例如,要使用法语区域设置 (locale) 运行特定测试
import { test, expect } from '@playwright/test';
test.use({ locale: 'fr-FR' });
test('example', async ({ page }) => {
// ...
});
同样的方法也适用于 describe
代码块内。例如,要在 describe
代码块中使用法语区域设置 (locale) 运行测试
import { test, expect } from '@playwright/test';
test.describe('french language block', () => {
test.use({ locale: 'fr-FR' });
test('example', async ({ page }) => {
// ...
});
});