Skip to main content

配置

Playwright Test 提供了配置默认 browsercontextpage fixtures 的选项。例如,有 headlessviewportignoreHTTPSErrors 等选项。您还可以为测试录制视频或跟踪,或在结束时捕获截图。

有很多测试选项,如 timeouttestDir,用于配置如何收集和执行测试。

您可以在配置文件中全局指定任何选项,并且大多数选项可以在测试文件中局部指定。

查看完整的测试选项列表和所有配置属性

全局配置

创建一个 playwright.config.js(或 playwright.config.ts)并在 testConfig.use 部分指定选项。

import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
headless: false,
viewport: { width: 1280, height: 720 },
ignoreHTTPSErrors: true,
video: 'on-first-retry',
},
};
export default config;

现在像平常一样运行测试,Playwright Test 将自动选取配置文件。

npx playwright test

如果您将配置文件放在不同的位置,请使用 --config 选项传递它。

npx playwright test --config=tests/my.config.js

局部配置

您可以为文件或 describe 块覆盖某些选项。

// example.spec.ts
import { test, expect } from '@playwright/test';
// Run tests in this file with portrait-like viewport.
test.use({ viewport: { width: 600, height: 900 } });
test('my portrait test', async ({ page }) => {
// ...
});

在 describe 内部也是如此。

// example.spec.ts
import { test, expect } from '@playwright/test';
test.describe('locale block', () => {
// Run tests in this describe block with portrait-like viewport.
test.use({ viewport: { width: 600, height: 900 } });
test('my portrait test', async ({ page }) => {
// ...
});
});

基本选项

通常您会从模拟设备开始,例如 Desktop Chromium。请参阅我们的模拟指南以了解更多信息。

以下是各种场景下一些常用的选项。您通常在配置文件中全局设置它们。

  • actionTimeout - 每个 Playwright 操作的超时时间(以毫秒为单位)。默认为 0(无超时)。了解更多关于各种超时的信息。
  • baseURL - 用于上下文中所有页面的基本 URL。允许仅使用路径进行导航,例如 page.goto('/settings')
  • browserName - 将运行测试的浏览器名称,chromiumfirefoxwebkit 之一。
  • bypassCSP - 切换绕过内容安全策略。当 CSP 包含生产源时很有用。
  • channel - 要使用的浏览器通道。了解更多关于不同浏览器和通道的信息。
  • headless - 是否在无头模式下运行浏览器。
  • viewport - 用于上下文中所有页面的视口。
  • storageState - 使用给定的存储状态填充上下文。对于简单的身份验证很有用,了解更多
  • colorScheme - 模拟 'prefers-colors-scheme' 媒体功能,支持的值为 'light''dark''no-preference'
  • geolocation - 上下文地理位置。
  • locale - 模拟用户区域设置,例如 en-GBde-DE 等。
  • permissions - 要授予上下文中所有页面的权限列表。
  • timezoneId - 更改上下文的时区。
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
baseURL: 'http://localhost:3000',
browserName: 'firefox',
headless: true,
},
};
export default config;

多个浏览器

Playwright Test 支持多个"项目",可以在多个浏览器和配置中运行测试。以下是一个示例,通过为每个浏览器创建一个项目,在 Chromium、Firefox 和 WebKit 中运行每个测试。

// playwright.config.ts
import { type PlaywrightTestConfig, devices } from '@playwright/test';

const config: PlaywrightTestConfig = {
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
};
export default config;

您可以为每个项目指定不同的选项,例如为 Chromium 设置特定的命令行参数。

Playwright Test 默认运行所有项目。

npx playwright test

Running 5 tests using 5 workers

[chromium] › example.spec.ts:3:1 › basic test (2s)
[firefox] › example.spec.ts:3:1 › basic test (2s)
[webkit] › example.spec.ts:3:1 › basic test (2s)

使用 --project 命令行选项运行单个项目。

npx playwright test --project=firefox

Running 1 test using 1 worker

[firefox] › example.spec.ts:3:1 › basic test (2s)

网络

可用于配置网络的选项:

  • acceptDownloads - 是否自动下载所有附件,默认为 true了解更多关于使用下载的信息。
  • extraHTTPHeaders - 包含要随每个请求发送的附加 HTTP 标头的对象。所有标头值必须是字符串。
  • httpCredentials - HTTP 身份验证的凭据。
  • ignoreHTTPSErrors - 是否在导航期间忽略 HTTPS 错误。
  • offline - 是否模拟网络离线。
  • proxy - 测试中所有页面使用的代理设置

网络模拟

您无需配置任何内容即可模拟网络请求。只需定义一个自定义 Route 来模拟浏览器上下文的网络。

// example.spec.ts
import { test, expect } from '@playwright/test';

test.beforeEach(async ({ context }) => {
// Block any css requests for each test in this file.
await context.route(/.css/, route => route.abort());
});

test('loads page without css', async ({ page }) => {
await page.goto('https://playwright.dev');
// ... test goes here
});

或者,您可以使用 page.route(url, handler[, options]) 在单个测试中模拟网络。

// example.spec.ts
import { test, expect } from '@playwright/test';

test('loads page without images', async ({ page }) => {
// Block png and jpeg images.
await page.route(/(png|jpeg)$/, route => route.abort());

await page.goto('https://playwright.dev');
// ... test goes here
});

自动截图

您可以让 Playwright Test 为您捕获截图 - 使用 screenshot 选项控制它。默认情况下截图是关闭的。

  • 'off' - 不捕获截图。
  • 'on' - 在每个测试后捕获截图。
  • 'only-on-failure' - 仅在每个测试失败后捕获截图。

截图将出现在测试输出目录中,通常是 test-results

import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
screenshot: 'only-on-failure',
},
};
export default config;

录制视频

Playwright Test 可以为您的测试录制视频,由 video 选项控制。默认情况下视频是关闭的。

  • 'off' - 不录制视频。
  • 'on' - 为每个测试录制视频。
  • 'retain-on-failure' - 为每个测试录制视频,但从成功的测试运行中删除所有视频。
  • 'on-first-retry' - 仅在首次重试测试时录制视频。

视频文件将出现在测试输出目录中,通常是 test-results。有关高级视频配置,请参阅 testOptions.video

import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
video: 'on-first-retry',
},
};
export default config;

录制测试跟踪

Playwright Test 可以在运行测试时生成测试跟踪。稍后,您可以通过打开 Trace Viewer 查看跟踪并获取有关 Playwright 执行的详细信息。默认情况下跟踪是关闭的,由 trace 选项控制。

  • 'off' - 不录制跟踪。
  • 'on' - 为每个测试录制跟踪。
  • 'retain-on-failure' - 为每个测试录制跟踪,但从成功的测试运行中删除它。
  • 'on-first-retry' - 仅在首次重试测试时录制跟踪。

跟踪文件将出现在测试输出目录中,通常是 test-results。有关高级配置,请参阅 testOptions.trace

import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
trace: 'retain-on-failure',
},
};
export default config;

更多浏览器和上下文选项

browserType.launch([options])browser.newContext([options]) 接受的任何选项都可以分别放入 use 部分的 launchOptionscontextOptions 中。查看可用选项的完整列表

import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
use: {
launchOptions: {
slowMo: 50,
},
},
};
export default config;

但是,最常见的选项如 headlessviewport 可以直接在 use 部分中使用 - 请参阅基本选项模拟网络

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

如果使用内置的 browser fixture,调用 browser.newContext([options]) 将创建一个从配置继承选项的上下文:

// playwright.config.ts
import type { PlaywrightTestConfig } from "@playwright/test";

const config: PlaywrightTestConfig = {
use: {
userAgent: 'some custom ua',
viewport: { width: 100, height: 100 },
},
};

export default config;

一个示例测试,说明初始上下文选项已设置:

// example.spec.ts
import { test, expect } from "@playwright/test";

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();
});

测试选项

除了配置 BrowserBrowserContext、视频或截图之外,Playwright Test 还有许多选项来配置测试的运行方式。以下是最常见的选项,完整列表请参阅 TestConfig

  • forbidOnly: 如果任何测试标记为 test.only,是否以错误退出。在 CI 上很有用。
  • globalSetup: 全局设置文件的路径。此文件将在所有测试之前被引入并运行。它必须导出单个函数。
  • globalTeardown: 全局拆卸文件的路径。此文件将在所有测试之后被引入并运行。它必须导出单个函数。
  • retries: 每个测试的最大重试次数。
  • testDir: 包含测试文件的目录。
  • testIgnore: 在查找测试文件时应忽略的 Glob 模式或正则表达式。例如,'**/test-assets'
  • testMatch: 匹配测试文件的 Glob 模式或正则表达式。例如,'**/todo-tests/*.spec.ts'。默认情况下,Playwright Test 运行 .*(test|spec)\\.(js|ts|mjs) 文件。
  • timeout: 给予每个测试的时间(以毫秒为单位)。了解更多关于各种超时的信息。
  • webServer: { command: string, port?: number, url?: string, ignoreHTTPSErrors?: boolean, timeout?: number, reuseExistingServer?: boolean, cwd?: string, env?: object } - 启动一个进程并等待它准备好后再开始测试。有关示例,请参阅启动 Web 服务器配置。
  • workers: 用于并行化测试的最大并发工作进程数。也可以设置为逻辑 CPU 核心的百分比,例如 '50%'

您可以在配置文件中指定这些选项。请注意,测试选项是顶级的,不要将它们放入 use 部分。

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

const config: PlaywrightTestConfig = {
// Look for test files in the "tests" directory, relative to this configuration file
testDir: 'tests',

// Each test is given 30 seconds
timeout: 30000,

// Forbid test.only on CI
forbidOnly: !!process.env.CI,

// Two retries for each test
retries: 2,

// Limit the number of workers on CI, use default locally
workers: process.env.CI ? 2 : undefined,

use: {
// Configure browser and context here
},
};
export default config;