テスト使用オプション
はじめに
テストランナーの設定に加えて、エミュレーション、ネットワーク、記録のオプションをブラウザまたはブラウザコンテキストに対して設定することもできます。これらのオプションは、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-colors-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はテストの実行中にテストトレースを生成できます。後で、Trace Viewerを開くことで、トレースを表示し、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() が受け入れる任意のオプションは、use
セクションの launchOptions
または contextOptions
にそれぞれ配置できます。
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 }) => {
// ...
});
});