跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

TestOptions ​

Added in: v1.10

Playwright Test provides many options to configure test environment, Browser, BrowserContext and more.

These options are usually provided in the configuration file through testConfig.use and testProject.use.

js
import { defineConfig } from '@playwright/test';
export default defineConfig({
  use: {
    headless: false,
    viewport: { width: 1280, height: 720 },
    ignoreHTTPSErrors: true,
    video: 'on-first-retry',
  },
});

Alternatively, with test.use() you can override some options for a file.

js
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 }) => {
  // ...
});

Properties ​

testOptions.acceptDownloads ​

Added in: v1.10

Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.

Usage

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

export default defineConfig({
  use: {
    acceptDownloads: false,
  },
});

Type

  • boolean

testOptions.actionTimeout ​

Added in: v1.10

Default timeout for each Playwright action in milliseconds, defaults to 0 (no timeout).

This is a default timeout for all Playwright actions, same as configured via page.setDefaultTimeout().

Usage

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

export default defineConfig({
  use: {
    /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
    actionTimeout: 0,
  },
});

Learn more about various timeouts.

Type

  • int

testOptions.baseURL ​

Added in: v1.10

When using page.goto(), page.route(), page.waitForURL(), page.waitForRequest(), or page.waitForResponse() it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples:

  • baseURL: http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html
  • baseURL: http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html
  • baseURL: http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html

Usage

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

export default defineConfig({
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    baseURL: 'http://localhost:3000',
  },
});

Type

  • string

testOptions.browserName ​

Added in: v1.10

Name of the browser that runs tests. Defaults to 'chromium'. Most of the time you should set browserName in your TestConfig:

Usage

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

export default defineConfig({
  use: {
    browserName: 'firefox',
  },
});

Type

  • "chromium" | "firefox" | "webkit"

testOptions.bypassCSP ​

Added in: v1.10

Toggles bypassing page's Content-Security-Policy. Defaults to false.

Usage

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

export default defineConfig({
  use: {
    bypassCSP: true,
  }
});

Type

  • boolean

testOptions.channel ​

Added in: v1.10

Browser distribution channel.

Use "chromium" to opt in to new headless mode.

Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded Google Chrome and Microsoft Edge.

Usage

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

export default defineConfig({
  projects: [
    {
      name: 'Microsoft Edge',
      use: {
        ...devices['Desktop Edge'],
        channel: 'msedge'
      },
    },
  ]
});

Type

  • string

testOptions.clientCertificates ​

Added in: v1.46

TLS Client Authentication allows the server to request a client certificate and verify it.

Details

An array of client certificates to be used. Each certificate object must have either both certPath and keyPath, a single pfxPath, or their corresponding direct value equivalents (cert and key, or pfx). Optionally, passphrase property should be provided if the certificate is encrypted. The origin property should be provided with an exact match to the request origin that the certificate is valid for.

Client certificate authentication is only active when at least one client certificate is provided. If you want to reject all client certificates sent by the server, you need to provide a client certificate with an origin that does not match any of the domains you plan to visit.

INFO

When using WebKit on macOS, accessing localhost will not pick up client certificates. You can make it work by replacing localhost with local.playwright.

Usage

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

export default defineConfig({
  use: {
    clientCertificates: [{
      origin: 'https://example.com',
      certPath: './cert.pem',
      keyPath: './key.pem',
      passphrase: 'mysecretpassword',
    }],
  },
});

Type

  • Array<Object>

testOptions.colorScheme ​

Added in: v1.10

Emulates prefers-colors-scheme media feature, supported values are 'light' and 'dark'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'light'.

Usage

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

export default defineConfig({
  use: {
    colorScheme: 'dark',
  },
});

Type

  • null | "light" | "dark" | "no-preference"

testOptions.connectOptions ​

Added in: v1.10

Usage

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

export default defineConfig({
  use: {
    connectOptions: {
      wsEndpoint: 'ws://localhost:5678',
    },
  },
});

When connect options are specified, default fixtures.browser, fixtures.context and fixtures.page use the remote browser instead of launching a browser locally.

Type

  • void | Object

testOptions.contextOptions ​

Added in: v1.10

Options used to create the context, as passed to browser.newContext(). Specific options like testOptions.viewport take priority over this.

Usage

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

export default defineConfig({
  use: {
    contextOptions: {
      reducedMotion: 'reduce',
    },
  },
});

Type

  • Object

testOptions.contrast ​

Added in: v1.50

Emulates 'prefers-contrast' media feature, supported values are 'no-preference', 'more'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'no-preference'.

Usage

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

export default defineConfig({
  use: {
    contrast: 'more',
  },
});

Type

  • null | "no-preference" | "more"

testOptions.deviceScaleFactor ​

Added in: v1.10

Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.

Usage

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

export default defineConfig({
  use: {
    viewport: { width: 2560, height: 1440 },
    deviceScaleFactor: 2,
  },
});

Type

  • float

testOptions.extraHTTPHeaders ​

Added in: v1.10

An object containing additional HTTP headers to be sent with every request. Defaults to none.

Usage

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

export default defineConfig({
  use: {
    extraHTTPHeaders: {
      'X-My-Header': 'value',
    },
  },
});

Type

  • Object<string, string>

testOptions.forcedColors ​

Added in: v1.50

Emulates 'forced-colors' media feature, supported values are 'active', 'none'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'none'.

Usage

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

export default defineConfig({
  use: {
    forcedColors: 'active',
  },
});

Type

  • null | "active" | "none"

testOptions.geolocation ​

Added in: v1.10

Usage

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

export default defineConfig({
  use: {
    geolocation: { longitude: 12.492507, latitude: 41.889938 },
  },
});

Learn more about geolocation.

Type

  • Object

testOptions.hasTouch ​

Added in: v1.10

Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.

Usage

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

export default defineConfig({
  use: {
    hasTouch: true
  },
});

Type

  • boolean

testOptions.headless ​

Added in: v1.10

Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to true.

Usage

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

export default defineConfig({
  use: {
    headless: false
  },
});

Type

  • boolean

testOptions.httpCredentials ​

Added in: v1.10

Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request.

Usage

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

export default defineConfig({
  use: {
    httpCredentials: {
      username: 'user',
      password: 'pass',
    },
  },
});

When passing an array of credentials to test.use(), wrap it into an extra array, see fixture options.

js
test.use({
  httpCredentials: [[
    { username: 'alice', password: 'alice-pass', origin: 'https://a.example.com' },
    { username: 'bob', password: 'bob-pass', origin: 'https://b.example.com' },
  ], { scope: 'test' }],
});

Type

  • Object | Array<Object>

testOptions.ignoreHTTPSErrors ​

Added in: v1.10

Whether to ignore HTTPS errors when sending network requests. Defaults to false.

Usage

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

export default defineConfig({
  use: {
    ignoreHTTPSErrors: true,
  },
});

Type

  • boolean

testOptions.isMobile ​

Added in: v1.10

Whether the meta viewport tag is taken into account and touch events are enabled. isMobile is a part of device, so you don't actually need to set it manually. Defaults to false. Learn more about mobile emulation.

Usage

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

export default defineConfig({
  use: {
    isMobile: false,
  },
});

Type

  • boolean

testOptions.javaScriptEnabled ​

Added in: v1.10

Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.

Usage

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

export default defineConfig({
  use: {
    javaScriptEnabled: false,
  },
});

Type

  • boolean

testOptions.launchOptions ​

Added in: v1.10

Options used to launch the browser, as passed to browserType.launch(). Specific options testOptions.headless and testOptions.channel take priority over this.

WARNING

Use custom browser args at your own risk, as some of them may break Playwright functionality.

Usage

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

export default defineConfig({
  projects: [
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        launchOptions: {
          args: ['--start-maximized']
        }
      }
    }
  ]
});

Type

  • Object

testOptions.locale ​

Added in: v1.10

Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. Defaults to en-US. Learn more about emulation in our emulation guide.

Usage

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

export default defineConfig({
  use: {
    locale: 'it-IT',
  },
});

Type

  • string

testOptions.locateOnlyVisible ​

Added in: v1.66

Whether locators in this context find only visible elements. Defaults to false.

When enabled, Playwright applies two rules:

  1. The element that a locator finds must be visible. Actions, assertions and queries behave as if locator.visible() was called at the end of the locator chain.
  2. locator.first(), locator.last() and locator.nth() select among visible elements. They behave as if locator.visible() was called immediately before them.
js
// <div hidden>One</div> <div>Two</div> <div>Three</div>
await expect(page.locator('div')).toHaveCount(2);
await expect(page.locator('div').first()).toHaveText('Two');
await expect(page.locator('div').last()).toHaveText('Three');

An explicit visibility filter always has priority. Playwright does not add its own filter in a position that already has one. For example, page.locator('div').filter({ visible: false }).first() finds the first hidden element.

All other parts of the locator chain are not filtered. In page.locator('section').getByRole('button'), the button must be visible, but the section can be hidden by the visibility rules, for example because it has zero size. The same applies to the inner locators of locator.filter(),

locator.and() and locator.or(): only the second rule applies to them.

This option does not change the accessibility rules of page.getByRole() or the behavior of selector-based methods such as page.$().

Usage

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

export default defineConfig({
  use: {
    locateOnlyVisible: true,
  },
});

Type

  • boolean

testOptions.navigationTimeout ​

Added in: v1.10

Timeout for each navigation action in milliseconds. Defaults to 0 (no timeout).

This is a default navigation timeout, same as configured via page.setDefaultNavigationTimeout().

Usage

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

export default defineConfig({
  use: {
    navigationTimeout: 3000,
  },
});

Learn more about various timeouts.

Type

  • int

testOptions.offline ​

Added in: v1.10

Whether to emulate network being offline. Defaults to false. Learn more about network emulation.

Usage

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

export default defineConfig({
  use: {
    offline: true
  },
});

Type

  • boolean

testOptions.permissions ​

Added in: v1.10

A list of permissions to grant to all pages in this context. See browserContext.grantPermissions() for more details. Defaults to none.

Usage

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

export default defineConfig({
  use: {
    permissions: ['notifications'],
  },
});

Type

  • Array<string>

testOptions.proxy ​

Added in: v1.10

Network proxy settings.

Usage

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

export default defineConfig({
  use: {
    proxy: {
      server: 'http://myproxy.com:3128',
      bypass: 'localhost',
    },
  },
});

Type

  • Object

testOptions.reducedMotion ​

Added in: v1.50

Emulates 'prefers-reduced-motion' media feature, supported values are 'reduce', 'no-preference'. See page.emulateMedia() for more details. Passing null resets emulation to system defaults. Defaults to 'no-preference'.

Usage

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

export default defineConfig({
  use: {
    reducedMotion: 'reduce',
  },
});

Type

  • null | "reduce" | "no-preference"

testOptions.reuseContext ​

Added in: v1.62

Discouraged

This option trades test isolation for speed and is intended for component tests that drive a story gallery. Leave it unset for end-to-end tests - a fresh browser context per test is one of the core guarantees of Playwright Test.

Experimental. When set to true, all tests in a worker process run in a single browser context that is reused between tests, instead of getting a brand new context per test. Defaults to false.

Between tests, Playwright resets the state that component tests typically touch: it clears cookies, cache, local storage and IndexedDB of visited origins, unregisters service workers, closes extra pages, removes routes, bindings and init scripts, and re-applies the configured storage state, viewport and emulation options.

This reset is best-effort, not a guarantee of isolation. State that is not reset includes:

Additional restrictions:

  • The option is ignored when testOptions.video recording is enabled.
  • Only a few context options may differ between consecutive tests: colorScheme, forcedColors, reducedMotion, contrast, screen, userAgent, viewport and testIdAttribute. Changing any other option in test.use(), for example locale or storageState, silently forces a fresh context and negates the speedup.
  • Do not combine with testOptions.connectOptions pointing multiple workers at a shared browser - workers would compete for the single reusable context.
  • recordHar in testOptions.contextOptions is not supported and produces no HAR file.

Usage

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

export default defineConfig({
  projects: [
    {
      name: 'components',
      testDir: './tests/components',
      use: { reuseContext: true },
    },
  ],
});

Type

  • boolean

testOptions.screen ​

Added in: v1.64

Emulates consistent window screen size available inside web page via window.screen. Is only used when the testOptions.viewport is set.

Usage

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

export default defineConfig({
  use: {
    viewport: { width: 390, height: 664 },
    screen: { width: 390, height: 844 },
  },
});

Type

  • Object

testOptions.screenshot ​

Added in: v1.10

Whether to automatically capture a screenshot after each test. Defaults to 'off'.

  • 'off': Do not capture screenshots.
  • 'on': Capture screenshot after each test.
  • 'only-on-failure': Capture screenshot after each test failure.
  • 'on-first-failure': Capture screenshot after each test's first failure.

Usage

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

export default defineConfig({
  use: {
    screenshot: 'only-on-failure',
  },
});

Learn more about automatic screenshots.

Type

  • Object | "off" | "on" | "only-on-failure" | "on-first-failure"

testOptions.serviceWorkers ​

Added in: v1.10

Whether to allow sites to register Service workers. Defaults to 'allow'.

  • 'allow': Service Workers can be registered.
  • 'block': Playwright will block all registration of Service Workers.

Usage

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

export default defineConfig({
  use: {
    serviceWorkers: 'allow'
  },
});

Type

  • "allow" | "block"

testOptions.storageState ​

Added in: v1.10

Learn more about storage state and auth.

Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via browserContext.storageState().

Usage

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

export default defineConfig({
  use: {
    storageState: 'storage-state.json',
  },
});

Details

When storage state is set up in the config, it is possible to reset storage state for a file:

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

// Reset storage state for this file to avoid being authenticated
test.use({ storageState: { cookies: [], origins: [] } });

test('not signed in test', async ({ page }) => {
  // ...
});

Type

  • path | Object

testOptions.testIdAttribute ​

Added in: v1.27

Custom attribute to be used in page.getByTestId(). data-testid is used by default. To match elements with any of several attributes, pass them as a comma-separated list.

Usage

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

export default defineConfig({
  use: {
    testIdAttribute: 'pw-test-id',
  },
});

Multiple attributes:

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

export default defineConfig({
  use: {
    testIdAttribute: 'data-pw,data-ti',
  },
});

Type

  • void

testOptions.timezoneId ​

Added in: v1.10

Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.

Usage

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

export default defineConfig({
  use: {
    timezoneId: 'Europe/Rome',
  },
});

Type

  • string

testOptions.trace ​

Added in: v1.10

Whether to record trace for each test. Defaults to 'off'. The initial run of a test is the "first run"; subsequent runs caused by retries are "retries".

  • 'off': Do not record trace.
  • 'on': Record and keep a trace for every run.
  • 'on-first-retry': Record and keep a trace only for the first retry of a test.
  • 'on-all-retries': Record and keep a trace for every retry.
  • 'retain-on-failure': Record a trace for every run, but keep it only for runs that failed. A failed run's trace is kept even when a later retry passes.
  • 'retain-on-first-failure': Record a trace only for the first run of a test (not for retries), and keep it only if that run failed.
  • 'retain-on-failure-and-retries': Record a trace for every run, and keep it for any run that failed or that is a retry.

See trace modes for a side-by-side comparison of what each mode records and keeps.

For more control, pass an object that specifies mode and trace features to enable.

Usage

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

export default defineConfig({
  use: {
    trace: 'on-first-retry'
  },
});

Learn more about recording trace.

Type

  • Object | "off" | "on" | "on-first-retry" | "on-all-retries" | "retain-on-failure" | "retain-on-first-failure" | "retain-on-failure-and-retries"

testOptions.userAgent ​

Added in: v1.10

Specific user agent to use in this context.

Usage

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

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

Type

  • string

testOptions.video ​

Added in: v1.10

Whether to record video for each test. Defaults to 'off'. The initial run of a test is the "first run"; subsequent runs caused by retries are "retries".

  • 'off': Do not record video.
  • 'on': Record and keep a video for every run.
  • 'on-first-retry': Record and keep a video only for the first retry of a test.
  • 'on-all-retries': Record and keep a video for every retry.
  • 'retain-on-failure': Record a video for every run, but keep it only for runs that failed. A failed run's video is kept even when a later retry passes.
  • 'retain-on-first-failure': Record a video only for the first run of a test (not for retries), and keep it only if that run failed.
  • 'retain-on-failure-and-retries': Record a video for every run, and keep it for any run that failed or that is a retry.

See video modes for a side-by-side comparison of what each mode records and keeps.

To control video size, pass an object with mode and size properties. If video size is not specified, it will be equal to testOptions.viewport scaled down to fit into 800x800. If viewport is not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.

To record smoother video of animations and scrolling, pass fps, for example { mode: 'on', size: { width: 1920, height: 1080 }, fps: 60 }. Higher frame rates and sizes use more CPU for encoding. Firefox and WebKit currently capture up to 25 frames per second.

To annotate actions in the video, pass show with actions and/or test sub-options. The actions option controls visual highlights on interacted elements, each shown for an optional duration in milliseconds (defaults to 500). The test option controls which test information is displayed as a status overlay.

Usage

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

export default defineConfig({
  use: {
    video: 'on-first-retry',
  },
});

Learn more about recording video.

Type

  • Object | "off" | "on" | "retain-on-failure" | "on-first-retry" | "on-all-retries" | "retain-on-first-failure" | "retain-on-failure-and-retries"

testOptions.viewport ​

Added in: v1.10

Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use null to disable the consistent viewport emulation. Learn more about viewport emulation.

INFO

The null value opts out from the default presets, makes viewport depend on the host window size defined by the operating system. It makes the execution of the tests non-deterministic.

Usage

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

export default defineConfig({
  use: {
    viewport: { width: 100, height: 100 },
  },
});

Type

  • null | Object

基于 Apache 2.0 许可证发布。