跳到正文

配置 (use) ​

介绍 ​

除了配置测试运行器外,你还可以为 Browser 或 BrowserContext 配置模拟、网络和录制选项。这些选项通过 Playwright 配置中的 use: {} 对象传递。

基本选项 ​

为所有测试设置基础 URL 和存储状态:

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // 在 `await page.goto('/')` 等操作中使用的基础 URL。
    baseURL: 'http://localhost:3000',

    // 使用给定的存储状态填充上下文。
    storageState: 'state.json',
  },
});
选项描述
testOptions.baseURL上下文中所有页面使用的基础 URL。允许仅使用路径导航,例如 page.goto('/settings')。
testOptions.storageState使用给定的存储状态填充上下文。对于简单认证很有用,了解更多。

模拟选项 ​

使用 Playwright 你可以模拟真实设备,如手机或平板电脑。有关模拟设备的更多信息,请参阅我们的项目指南。你还可以为所有测试或特定测试模拟 "geolocation"、"locale" 和 "timezone",以及设置 "permissions" 来显示通知或更改 "colorScheme"。请参阅我们的模拟指南了解更多。

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // 模拟 `'prefers-colors-scheme'` 媒体特性。
    colorScheme: 'dark',

    // 上下文地理位置。
    geolocation: { longitude: 12.492507, latitude: 41.889938 },

    // 模拟用户区域设置。
    locale: 'en-GB',

    // 授予浏览器上下文指定的权限。
    permissions: ['geolocation'],

    // 模拟用户时区。
    timezoneId: 'Europe/Paris',

    // 上下文中所有页面使用的视口。
    viewport: { width: 1280, height: 720 },
  },
});
选项描述
testOptions.colorScheme模拟 'prefers-colors-scheme' 媒体特性,支持的值为 'light' 和 'dark'
testOptions.contrast模拟 'prefers-contrast' 媒体特性,支持的值为 'no-preference' 和 'more'
testOptions.forcedColors模拟 'forced-colors' 媒体特性,支持的值为 'active' 和 'none'
testOptions.geolocation上下文地理位置。
testOptions.locale模拟用户区域设置,例如 en-GB、de-DE 等。
testOptions.permissions授予上下文中所有页面的权限列表。
testOptions.reducedMotion模拟 'prefers-reduced-motion' 媒体特性,支持的值为 'reduce' 和 'no-preference'
testOptions.timezoneId更改上下文的时区。
testOptions.viewport上下文中所有页面使用的视口。

网络选项 ​

可用于配置网络的选项:

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // 是否自动下载所有附件。
    acceptDownloads: false,

    // 包含要随每个请求发送的额外 HTTP 头的对象。
    extraHTTPHeaders: {
      'X-My-Header': 'value',
    },

    // HTTP 认证的凭据。
    httpCredentials: {
      username: 'user',
      password: 'pass',
    },

    // 是否在导航期间忽略 HTTPS 错误。
    ignoreHTTPSErrors: true,

    // 是否模拟网络离线。
    offline: true,

    // 测试中所有页面使用的代理设置。
    proxy: {
      server: 'http://myproxy.com:3128',
      bypass: 'localhost',
    },
  },
});
选项描述
testOptions.acceptDownloads是否自动下载所有附件,默认为 true。了解更多关于处理下载。
testOptions.clientCertificatesTLS 客户端认证允许服务器请求客户端证书并验证它。
testOptions.extraHTTPHeaders包含要随每个请求发送的额外 HTTP 头的对象。所有头值必须是字符串。
testOptions.httpCredentialsHTTP 认证的凭据。
testOptions.ignoreHTTPSErrors是否在导航期间忽略 HTTPS 错误。
testOptions.offline是否模拟网络离线。
testOptions.proxy测试中所有页面使用的代理设置。
testOptions.serviceWorkers是否允许站点注册 Service workers,默认为 'allow'。了解更多关于 Service Workers 和网络模拟。

INFO

你不需要配置任何东西来模拟网络请求。只需定义一个自定义 Route 来为浏览器上下文模拟网络。请参阅我们的网络模拟指南了解更多。

录制选项 ​

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

跟踪文件、截图和视频将出现在测试输出目录中,通常是 test-results。

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // 在每次测试失败后捕获截图。
    screenshot: 'only-on-failure',

    // 仅在首次重试测试时录制跟踪。
    trace: 'on-first-retry',

    // 仅在首次重试测试时录制视频。
    video: 'on-first-retry'
  },
});
选项描述
testOptions.screenshot捕获测试的截图。选项包括 'off'、'on' 和 'only-on-failure'
testOptions.tracePlaywright 可以在运行测试时生成测试跟踪。之后,你可以查看跟踪并通过打开跟踪查看器获取有关 Playwright 执行的详细信息。选项包括:'off'、'on'、'retain-on-failure' 和 'on-first-retry'
testOptions.videoPlaywright 可以为你的测试录制视频。选项包括:'off'、'on'、'retain-on-failure' 和 'on-first-retry'

跟踪模式 ​

trace 选项支持多种模式,它们在哪些运行被录制和哪些录制在测试结束后被保留方面有所不同。测试的初始运行是"首次运行";由重试引起的后续运行是"重试"。

模式在以下情况录制跟踪在以下情况保留跟踪
'off'从不—
'on'每次运行总是
'retain-on-failure'每次运行该运行失败
'retain-on-first-failure'仅首次运行首次运行失败
'retain-on-failure-and-retries'每次运行该运行失败,或者是重试
'on-first-retry'仅首次重试总是
'on-all-retries'每次重试总是

下表显示了在一些常见场景中保留哪些跟踪,假设配置了 retries: 2:

模式首次运行通过失败,然后重试通过每次运行都失败
'off'———
'on'首次运行首次运行 + 重试所有三次运行
'retain-on-failure'—首次运行所有三次运行
'retain-on-first-failure'—首次运行首次运行
'retain-on-failure-and-retries'—首次运行 + 重试所有三次运行
'on-first-retry'—首次重试首次重试
'on-all-retries'—首次重试两次重试

视频模式 ​

video 选项支持与 trace 相同的模式集,它们使用相同的规则录制和保留录像。

模式在以下情况录制视频在以下情况保留视频
'off'从不—
'on'每次运行总是
'retain-on-failure'每次运行该运行失败
'retain-on-first-failure'仅首次运行首次运行失败
'retain-on-failure-and-retries'每次运行该运行失败,或者是重试
'on-first-retry'仅首次重试总是
'on-all-retries'每次重试总是

下表显示了在一些常见场景中保留哪些视频,假设配置了 retries: 2:

模式首次运行通过失败,然后重试通过每次运行都失败
'off'———
'on'首次运行首次运行 + 重试所有三次运行
'retain-on-failure'—首次运行所有三次运行
'retain-on-first-failure'—首次运行首次运行
'retain-on-failure-and-retries'—首次运行 + 重试所有三次运行
'on-first-retry'—首次重试首次重试
'on-all-retries'—首次重试两次重试

其他选项 ​

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // 每个操作(如 `click()`)可以花费的最长时间。默认为 0(无限制)。
    actionTimeout: 0,

    // 运行测试的浏览器名称。例如 `chromium`、`firefox`、`webkit`。
    browserName: 'chromium',

    // 切换绕过内容安全策略。
    bypassCSP: true,

    // 要使用的通道,例如 "chrome"、"chrome-beta"、"msedge"、"msedge-beta"。
    channel: 'chrome',

    // 在无界面模式下运行浏览器。
    headless: false,

    // 更改默认的 data-testid 属性。
    testIdAttribute: 'pw-test-id',
  },
});
选项描述
testOptions.actionTimeout每个 Playwright 操作的超时时间(毫秒)。默认为 0(无超时)。了解更多关于超时以及如何为单个测试设置它们。
testOptions.browserName运行测试的浏览器名称。默认为 'chromium'。选项包括 chromium、firefox 或 webkit。
testOptions.bypassCSP切换绕过内容安全策略。当 CSP 包含生产源时很有用。默认为 false。
testOptions.channel要使用的浏览器通道。了解更多关于不同浏览器和通道。
testOptions.headless是否在无界面模式下运行浏览器,意味着运行测试时不显示浏览器。默认为 true。
testOptions.navigationTimeout每个导航操作的超时时间(毫秒)。默认为 0(无超时)。了解更多关于超时。
testOptions.testIdAttribute更改 Playwright 定位器使用的默认 data-testid 属性。

更多浏览器和上下文选项 ​

browserType.launch()、browser.newContext() 或 browserType.connect() 接受的任何选项都可以分别放入 use 部分的 launchOptions、contextOptions 或 connectOptions 中。

js
import { defineConfig } from '@playwright/test';

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

然而,最常见的选项如 headless 或 viewport 可以直接在 use 部分中使用——参见基本选项、模拟或网络。

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

当测试或钩子运行时,通过测试运行器使用的 Playwright 实例创建的每个浏览器上下文都会继承 use 部分的上下文选项。这包括使用内置 browser 夹具创建的上下文、单独启动的浏览器、browserType.launchPersistentContext(),或解析到同一实例的直接 playwright-core 导入。显式上下文选项优先:

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    userAgent: 'some custom ua',
    viewport: { width: 100, height: 100 },
  },
});

一个示例测试说明了初始上下文选项是如何设置的:

js
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({}) 并传入选项来为特定测试覆盖它。

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    locale: 'en-GB'
  },
});

你可以使用 Playwright 配置中的 project 选项为特定项目覆盖选项。

js
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        locale: 'de-DE',
      },
    },
  ],
});

你可以使用 test.use() 方法并传入选项来为特定测试文件覆盖选项。例如,要使用法语区域设置运行特定测试:

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

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

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

这在 describe 块中同样有效。例如,要在 describe 块中使用法语区域设置运行测试:

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

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

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

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

重置选项 ​

你可以将选项重置为配置文件中定义的值。考虑以下设置 baseURL 的配置:

js
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    baseURL: 'https://playwright.dev',
  },
});

现在你可以为文件配置 baseURL,也可以为单个测试选择退出。

js
import { test } from '@playwright/test';

// 为此文件配置 baseURL。
test.use({ baseURL: 'https://playwright.dev/docs/intro' });

test('check intro contents', async ({ page }) => {
  // 此测试将使用上面定义的 "https://playwright.dev/docs/intro" 基础 url。
});

test.describe(() => {
  // 将值重置为配置中定义的值。
  test.use({ baseURL: undefined });

  test('can navigate to intro from the home page', async ({ page }) => {
    // 此测试将使用配置中定义的 "https://playwright.dev" 基础 url。
  });
});

如果你想将值完全重置为 undefined,请使用长形式夹具表示法。

js
import { test } from '@playwright/test';

// 完全取消此文件的 baseURL 设置。
test.use({
  baseURL: [async ({}, use) => use(undefined), { scope: 'test' }],
});

test('no base url', async ({ page }) => {
  // 此测试将没有基础 url。
});

基于 Apache 2.0 许可证发布。