メインコンテンツにスキップ

テスト使用オプション

はじめに

テストランナーの設定に加えて、エミュレーションネットワーク録画BrowserまたはBrowserContextで設定することもできます。これらのオプションは、Playwrightの設定ファイルでuse: {}オブジェクトに渡されます。

基本オプション

すべてのテストのベースURLとストレージの状態を設定する

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

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

// Populates context with given storage state.
storageState: 'state.json',
},
});
オプション説明
testOptions.baseURLコンテキスト内のすべてのページで使用されるベースURL。例えばpage.goto('/settings')のように、パスのみを使用してナビゲートできます。
testOptions.storageState指定されたストレージ状態をコンテキストに設定します。簡単な認証に便利です。詳細はこちら

エミュレーションオプション

Playwrightを使用すると、携帯電話やタブレットなどの実際のデバイスをエミュレートできます。デバイスのエミュレーションに関する詳細については、プロジェクトに関するガイドを参照してください。また、すべてのテストまたは特定のテストに対して"geolocation""locale""timezone"をエミュレートしたり、通知を表示するための"permissions"を設定したり、"colorScheme"を変更したりすることもできます。エミュレーションガイドで詳細を確認してください。

playwright.config.ts
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-color-scheme'メディア機能をエミュレートします。サポートされる値は'light''dark'です。
testOptions.geolocationコンテキストの地理位置情報
testOptions.localeユーザーのロケール(例: en-GBde-DEなど)をエミュレートします。
testOptions.permissionsコンテキスト内のすべてのページに付与するパーミッションのリスト。
testOptions.timezoneIdコンテキストのタイムゾーンを変更します。
testOptions.viewportコンテキスト内のすべてのページで使用されるビューポート

ネットワークオプション

ネットワークを設定するための利用可能なオプション

playwright.config.ts
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.httpCredentialsHTTP認証の認証情報。
testOptions.ignoreHTTPSErrorsナビゲーション中にHTTPSエラーを無視するかどうか。
testOptions.offlineネットワークがオフラインであることをエミュレートするかどうか。
testOptions.proxyテスト内のすべてのページで使用されるプロキシ設定

ネットワークリクエストをモックするために何も設定する必要はありません。ブラウザコンテキストのネットワークをモックするカスタムのRouteを定義するだけです。ネットワークモックのガイドで詳細を確認してください。

録画オプション

Playwrightを使用すると、スクリーンショットをキャプチャしたり、ビデオやテストのトレースを記録したりできます。デフォルトではこれらはオフになっていますが、playwright.config.jsファイルでscreenshotvideotraceオプションを設定することで有効にできます。

トレースファイル、スクリーンショット、ビデオは、通常test-resultsであるテスト出力ディレクトリに表示されます。

playwright.config.ts
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.tracePlaywrightはテスト実行中にテストトレースを生成できます。後でトレースビューアを開くことで、トレースを表示し、Playwrightの実行に関する詳細情報を取得できます。オプションには、'off''on''retain-on-failure''on-first-retry'があります。
testOptions.videoPlaywrightはテストのビデオを記録できます。オプションには、'off''on''retain-on-failure''on-first-retry'があります。

その他のオプション

playwright.config.ts
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.actionTimeoutPlaywrightの各アクションのタイムアウト(ミリ秒)。デフォルトは0(タイムアウトなし)です。タイムアウトと、単一のテストに対してそれらを設定する方法について詳しくはこちら。
testOptions.browserNameテストを実行するブラウザの名前。デフォルトは「chromium」です。オプションにはchromiumfirefox、またはwebkitがあります。
testOptions.bypassCSPContent-Security-Policyをバイパスするかどうかを切り替えます。CSPに本番環境のオリジンが含まれている場合に便利です。デフォルトはfalseです。
testOptions.channel使用するブラウザチャネル。異なるブラウザとチャネルについて詳しくはこちら
testOptions.headlessテスト実行時にブラウザをヘッドレスモードで実行するかどうか。つまり、ブラウザは表示されません。デフォルトはtrueです。
testOptions.testIdAttributePlaywrightロケーターが使用するデフォルトのdata-testid属性を変更します。

その他のブラウザおよびコンテキストオプション

browserType.launch()browser.newContext()、またはbrowserType.connect()で受け入れられるすべてのオプションは、それぞれuseセクションのlaunchOptionscontextOptions、またはconnectOptionsに含めることができます。

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

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

ただし、headlessviewportのような最も一般的なものは、useセクションで直接利用できます。基本オプションエミュレーション、またはネットワークを参照してください。

明示的なコンテキスト作成とオプションの継承

組み込みのbrowserフィクスチャを使用している場合、browser.newContext()を呼び出すと、設定から継承されたオプションを持つコンテキストが作成されます。

playwright.config.ts
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は、グローバルに、プロジェクトごとに、またはテストごとに設定できます。例えば、Playwrightの設定のuseオプションにlocaleを追加することで、グローバルに使用するロケールを設定し、その後、設定のprojectオプションを使用して特定のプロジェクトでそれをオーバーライドできます。また、テストファイルにtest.use({})を追加し、オプションを渡すことで、特定のテストに対してオーバーライドすることもできます。

playwright.config.ts
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 }) => {
// ...
});
});

オプションのリセット

オプションを設定ファイルで定義された値にリセットできます。baseURLを設定する以下の設定を考えてみましょう。

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

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

これで、ファイルごとにbaseURLを設定し、単一のテストではそれを無効にすることもできます。

intro.spec.ts
import { test } from '@playwright/test';

// Configure baseURL for this file.
test.use({ baseURL: 'https://playwright.dokyumento.jp/docs/intro' });

test('check intro contents', async ({ page }) => {
// This test will use "https://playwright.dokyumento.jp/docs/intro" base url as defined above.
});

test.describe(() => {
// Reset the value to a config-defined one.
test.use({ baseURL: undefined });

test('can navigate to intro from the home page', async ({ page }) => {
// This test will use "https://playwright.dokyumento.jp" base url as defined in the config.
});
});

値を完全にundefinedにリセットしたい場合は、ロングフォームのフィクスチャ記法を使用してください。

intro.spec.ts
import { test } from '@playwright/test';

// Completely unset baseURL for this file.
test.use({
baseURL: [async ({}, use) => use(undefined), { scope: 'test' }],
});

test('no base url', async ({ page }) => {
// This test will not have a base url.
});