テスト使用オプション
はじめに
テストランナーの設定に加えて、エミュレーション、ネットワーク、録画をBrowserまたはBrowserContextで設定することもできます。これらのオプションは、Playwrightの設定ファイルでuse: {}オブジェクトに渡されます。
基本オプション
すべてのテストのベースURLとストレージの状態を設定する
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"を変更したりすることもできます。エミュレーションガイドで詳細を確認してください。
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-GB、de-DEなど)をエミュレートします。 |
| testOptions.permissions | コンテキスト内のすべてのページに付与するパーミッションのリスト。 |
| testOptions.timezoneId | コンテキストのタイムゾーンを変更します。 |
| testOptions.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 | テスト内のすべてのページで使用されるプロキシ設定。 |
ネットワークリクエストをモックするために何も設定する必要はありません。ブラウザコンテキストのネットワークをモックするカスタムのRouteを定義するだけです。ネットワークモックのガイドで詳細を確認してください。
録画オプション
Playwrightを使用すると、スクリーンショットをキャプチャしたり、ビデオやテストのトレースを記録したりできます。デフォルトではこれらはオフになっていますが、playwright.config.jsファイルでscreenshot、video、traceオプションを設定することで有効にできます。
トレースファイル、スクリーンショット、ビデオは、通常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 | テストのスクリーンショットをキャプチャします。オプションには'off'、'on'、'only-on-failure'があります。 |
| testOptions.trace | Playwrightはテスト実行中にテストトレースを生成できます。後でトレースビューアを開くことで、トレースを表示し、Playwrightの実行に関する詳細情報を取得できます。オプションには、'off'、'on'、'retain-on-failure'、'on-first-retry'があります。 |
| testOptions.video | Playwrightはテストのビデオを記録できます。オプションには、'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(タイムアウトなし)です。タイムアウトと、単一のテストに対してそれらを設定する方法について詳しくはこちら。 |
| testOptions.browserName | テストを実行するブラウザの名前。デフォルトは「chromium」です。オプションにはchromium、firefox、またはwebkitがあります。 |
| testOptions.bypassCSP | Content-Security-Policyをバイパスするかどうかを切り替えます。CSPに本番環境のオリジンが含まれている場合に便利です。デフォルトはfalseです。 |
| testOptions.channel | 使用するブラウザチャネル。異なるブラウザとチャネルについて詳しくはこちら。 |
| testOptions.headless | テスト実行時にブラウザをヘッドレスモードで実行するかどうか。つまり、ブラウザは表示されません。デフォルトはtrueです。 |
| testOptions.testIdAttribute | Playwrightロケーターが使用するデフォルトのdata-testid属性を変更します。 |
その他のブラウザおよびコンテキストオプション
browserType.launch()、browser.newContext()、またはbrowserType.connect()で受け入れられるすべてのオプションは、それぞれuseセクションのlaunchOptions、contextOptions、またはconnectOptionsに含めることができます。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
launchOptions: {
slowMo: 50,
},
},
});
ただし、headlessやviewportのような最も一般的なものは、useセクションで直接利用できます。基本オプション、エミュレーション、またはネットワークを参照してください。
明示的なコンテキスト作成とオプションの継承
組み込みのbrowserフィクスチャを使用している場合、browser.newContext()を呼び出すと、設定から継承されたオプションを持つコンテキストが作成されます。
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({})を追加し、オプションを渡すことで、特定のテストに対してオーバーライドすることもできます。
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を設定する以下の設定を考えてみましょう。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'https://playwright.dokyumento.jp',
},
});
これで、ファイルごとにbaseURLを設定し、単一のテストではそれを無効にすることもできます。
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にリセットしたい場合は、ロングフォームのフィクスチャ記法を使用してください。
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.
});