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

フィクスチャ

はじめに

Playwright Testは、テストフィクスチャの概念に基づいています。テストフィクスチャは、各テストの環境を確立するために使用され、テストに必要なものだけを提供します。テストフィクスチャはテスト間で分離されています。フィクスチャを使用すると、共通のセットアップではなく、その意味に基づいてテストをグループ化できます。

組み込みフィクスチャ

最初のテストで既にテストフィクスチャを使用しました。

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

test('basic test', async ({ page }) => {
await page.goto('https://playwright.dokyumento.jp/');

await expect(page).toHaveTitle(/Playwright/);
});

{ page } 引数は、Playwright Testにpageフィクスチャをセットアップし、それをテスト関数に提供するように指示します。

以下は、ほとんどの場合に使用するであろう事前に定義されたフィクスチャのリストです。

フィクスチャタイプ説明
pagePageこのテスト実行のための分離されたページ。
contextBrowserContextこのテスト実行のための分離されたコンテキスト。pageフィクスチャもこのコンテキストに属します。コンテキストの設定方法についてはこちらをご覧ください。
browserBrowserブラウザはリソースを最適化するためにテスト間で共有されます。ブラウザの設定方法についてはこちらをご覧ください。
browserNamestring現在テストを実行しているブラウザの名前。chromiumfirefox、またはwebkitのいずれかです。
requestAPIRequestContextこのテスト実行のための分離されたAPIRequestContextインスタンス。

フィクスチャなし

ここでは、従来のテストスタイルとフィクスチャベースのテストスタイルで、一般的なテスト環境のセットアップがどのように異なるかを示します。

TodoPageは、ページオブジェクトモデルパターンに従って、Webアプリの「ToDoリスト」ページとやり取りするのに役立つクラスです。これは内部でPlaywrightのpageを使用します。

TodoPageのコードを展開するにはクリック
todo-page.ts
import type { Page, Locator } from '@playwright/test';

export class TodoPage {
private readonly inputBox: Locator;
private readonly todoItems: Locator;

constructor(public readonly page: Page) {
this.inputBox = this.page.locator('input.new-todo');
this.todoItems = this.page.getByTestId('todo-item');
}

async goto() {
await this.page.goto('https://demo.playwright.dev/todomvc/');
}

async addToDo(text: string) {
await this.inputBox.fill(text);
await this.inputBox.press('Enter');
}

async remove(text: string) {
const todo = this.todoItems.filter({ hasText: text });
await todo.hover();
await todo.getByLabel('Delete').click();
}

async removeAll() {
while ((await this.todoItems.count()) > 0) {
await this.todoItems.first().hover();
await this.todoItems.getByLabel('Delete').first().click();
}
}
}
todo.spec.ts
const { test } = require('@playwright/test');
const { TodoPage } = require('./todo-page');

test.describe('todo tests', () => {
let todoPage;

test.beforeEach(async ({ page }) => {
todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo('item1');
await todoPage.addToDo('item2');
});

test.afterEach(async () => {
await todoPage.removeAll();
});

test('should add an item', async () => {
await todoPage.addToDo('my item');
// ...
});

test('should remove an item', async () => {
await todoPage.remove('item1');
// ...
});
});

フィクスチャあり

フィクスチャは、before/afterフックに比べていくつかの利点があります。

  • フィクスチャは、セットアップとティアダウンを同じ場所に**カプセル化**するため、記述が容易になります。したがって、beforeフックで作成されたものをティアダウンするafterフックがある場合、それらをフィクスチャにすることを検討してください。
  • フィクスチャはテストファイル間で**再利用可能**です。一度定義すれば、すべてのテストで使用できます。これはPlaywrightの組み込みpageフィクスチャの動作と同じです。したがって、複数のテストで使用されるヘルパー関数がある場合は、それをフィクスチャにすることを検討してください。
  • フィクスチャは**オンデマンド**です。必要なだけ多くのフィクスチャを定義でき、Playwright Testはテストに必要なものだけをセットアップし、それ以外は何もセットアップしません。
  • フィクスチャは**構成可能**です。複雑な動作を提供するために互いに依存することができます。
  • フィクスチャは**柔軟**です。テストはフィクスチャの任意の組み合わせを使用して、他のテストに影響を与えることなく、必要な正確な環境を調整できます。
  • フィクスチャは**グループ化を簡素化**します。環境をセットアップするdescribeでテストを囲む必要がなくなり、代わりにテストをその意味によって自由にグループ化できます。
TodoPageのコードを展開するにはクリック
todo-page.ts
import type { Page, Locator } from '@playwright/test';

export class TodoPage {
private readonly inputBox: Locator;
private readonly todoItems: Locator;

constructor(public readonly page: Page) {
this.inputBox = this.page.locator('input.new-todo');
this.todoItems = this.page.getByTestId('todo-item');
}

async goto() {
await this.page.goto('https://demo.playwright.dev/todomvc/');
}

async addToDo(text: string) {
await this.inputBox.fill(text);
await this.inputBox.press('Enter');
}

async remove(text: string) {
const todo = this.todoItems.filter({ hasText: text });
await todo.hover();
await todo.getByLabel('Delete').click();
}

async removeAll() {
while ((await this.todoItems.count()) > 0) {
await this.todoItems.first().hover();
await this.todoItems.getByLabel('Delete').first().click();
}
}
}
example.spec.ts
import { test as base } from '@playwright/test';
import { TodoPage } from './todo-page';

// Extend basic test by providing a "todoPage" fixture.
const test = base.extend<{ todoPage: TodoPage }>({
todoPage: async ({ page }, use) => {
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo('item1');
await todoPage.addToDo('item2');
await use(todoPage);
await todoPage.removeAll();
},
});

test('should add an item', async ({ todoPage }) => {
await todoPage.addToDo('my item');
// ...
});

test('should remove an item', async ({ todoPage }) => {
await todoPage.remove('item1');
// ...
});

フィクスチャの作成

独自のフィクスチャを作成するには、test.extend() を使用して、それを含む新しいtestオブジェクトを作成します。

以下では、ページオブジェクトモデルパターンに従う2つのフィクスチャtodoPagesettingsPageを作成します。

TodoPageとSettingsPageのコードを展開するにはクリック
todo-page.ts
import type { Page, Locator } from '@playwright/test';

export class TodoPage {
private readonly inputBox: Locator;
private readonly todoItems: Locator;

constructor(public readonly page: Page) {
this.inputBox = this.page.locator('input.new-todo');
this.todoItems = this.page.getByTestId('todo-item');
}

async goto() {
await this.page.goto('https://demo.playwright.dev/todomvc/');
}

async addToDo(text: string) {
await this.inputBox.fill(text);
await this.inputBox.press('Enter');
}

async remove(text: string) {
const todo = this.todoItems.filter({ hasText: text });
await todo.hover();
await todo.getByLabel('Delete').click();
}

async removeAll() {
while ((await this.todoItems.count()) > 0) {
await this.todoItems.first().hover();
await this.todoItems.getByLabel('Delete').first().click();
}
}
}

SettingsPageも同様です

settings-page.ts
import type { Page } from '@playwright/test';

export class SettingsPage {
constructor(public readonly page: Page) {
}

async switchToDarkMode() {
// ...
}
}
my-test.ts
import { test as base } from '@playwright/test';
import { TodoPage } from './todo-page';
import { SettingsPage } from './settings-page';

// Declare the types of your fixtures.
type MyFixtures = {
todoPage: TodoPage;
settingsPage: SettingsPage;
};

// Extend base test by providing "todoPage" and "settingsPage".
// This new "test" can be used in multiple test files, and each of them will get the fixtures.
export const test = base.extend<MyFixtures>({
todoPage: async ({ page }, use) => {
// Set up the fixture.
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo('item1');
await todoPage.addToDo('item2');

// Use the fixture value in the test.
await use(todoPage);

// Clean up the fixture.
await todoPage.removeAll();
},

settingsPage: async ({ page }, use) => {
await use(new SettingsPage(page));
},
});
export { expect } from '@playwright/test';
注意

カスタムフィクスチャ名は、文字またはアンダースコアで始まる必要があり、文字、数字、アンダースコアのみを含めることができます。

フィクスチャの使用

テスト関数の引数にフィクスチャを指定するだけで、テストランナーが処理してくれます。フィクスチャはフックや他のフィクスチャでも利用できます。TypeScriptを使用している場合、フィクスチャは適切な型を持ちます。

以下では、上記で定義したtodoPageおよびsettingsPageフィクスチャを使用します。

import { test, expect } from './my-test';

test.beforeEach(async ({ settingsPage }) => {
await settingsPage.switchToDarkMode();
});

test('basic test', async ({ todoPage, page }) => {
await todoPage.addToDo('something nice');
await expect(page.getByTestId('todo-title')).toContainText(['something nice']);
});

フィクスチャのオーバーライド

独自のフィクスチャを作成するだけでなく、既存のフィクスチャをニーズに合わせてオーバーライドすることもできます。以下の例では、pageフィクスチャをオーバーライドして、自動的にbaseURLに移動させます。

import { test as base } from '@playwright/test';

export const test = base.extend({
page: async ({ baseURL, page }, use) => {
await page.goto(baseURL);
await use(page);
},
});

この例では、pageフィクスチャがtestOptions.baseURLなどの他の組み込みフィクスチャに依存できることに注目してください。これで、設定ファイルでbaseURLを構成するか、test.use()を使用してテストファイル内でローカルに設定できます。

example.spec.ts

test.use({ baseURL: 'https://playwright.dokyumento.jp' });

フィクスチャは、ベースフィクスチャが全く異なるものに完全に置き換えられるようにオーバーライドすることもできます。たとえば、testOptions.storageStateフィクスチャをオーバーライドして、独自のデータを提供することができます。

import { test as base } from '@playwright/test';

export const test = base.extend({
storageState: async ({}, use) => {
const cookie = await getAuthCookie();
await use({ cookies: [cookie] });
},
});

ワーカー・スコープのフィクスチャ

Playwright Testは、テストファイルを実行するためにワーカープロセスを使用します。個々のテスト実行のためにテストフィクスチャがセットアップされるのと同様に、ワーカーフィクスチャは各ワーカープロセスに対してセットアップされます。ここでサービスをセットアップしたり、サーバーを実行したりできます。Playwright Testは、ワーカーフィクスチャが一致し、環境が同一である限り、可能な限り多くのテストファイルにワーカープロセスを再利用します。

以下では、同じワーカー内のすべてのテストで共有されるaccountフィクスチャを作成し、各テストでこのアカウントにログインするようにpageフィクスチャをオーバーライドします。一意のアカウントを生成するために、任意のテストまたはフィクスチャで利用可能なworkerInfo.workerIndexを使用します。ワーカーフィクスチャのタプルライクな構文に注目してください。テストランナーがこのフィクスチャをワーカーごとに1回だけセットアップするように、{scope: 'worker'}を渡す必要があります。

my-test.ts
import { test as base } from '@playwright/test';

type Account = {
username: string;
password: string;
};

// Note that we pass worker fixture types as a second template parameter.
export const test = base.extend<{}, { account: Account }>({
account: [async ({ browser }, use, workerInfo) => {
// Unique username.
const username = 'user' + workerInfo.workerIndex;
const password = 'verysecure';

// Create the account with Playwright.
const page = await browser.newPage();
await page.goto('/signup');
await page.getByLabel('User Name').fill(username);
await page.getByLabel('Password').fill(password);
await page.getByText('Sign up').click();
// Make sure everything is ok.
await expect(page.getByTestId('result')).toHaveText('Success');
// Do not forget to cleanup.
await page.close();

// Use the account value.
await use({ username, password });
}, { scope: 'worker' }],

page: async ({ page, account }, use) => {
// Sign in with our account.
const { username, password } = account;
await page.goto('/signin');
await page.getByLabel('User Name').fill(username);
await page.getByLabel('Password').fill(password);
await page.getByText('Sign in').click();
await expect(page.getByTestId('userinfo')).toHaveText(username);

// Use signed-in page in the test.
await use(page);
},
});
export { expect } from '@playwright/test';

自動フィクスチャ

自動フィクスチャは、テストがそれらを直接リストしていなくても、各テスト/ワーカーに対してセットアップされます。自動フィクスチャを作成するには、タプル構文を使用し、{ auto: true }を渡します。

以下は、テストが失敗したときにデバッグログを自動的に添付するフィクスチャの例です。これにより、後でレポーターでログを確認できます。実行中のテストに関するメタデータを取得するために、各テスト/フィクスチャで利用可能なTestInfoオブジェクトをどのように使用しているかに注目してください。

my-test.ts
import debug from 'debug';
import fs from 'fs';
import { test as base } from '@playwright/test';

export const test = base.extend<{ saveLogs: void }>({
saveLogs: [async ({}, use, testInfo) => {
// Collecting logs during the test.
const logs = [];
debug.log = (...args) => logs.push(args.map(String).join(''));
debug.enable('myserver');

await use();

// After the test we can check whether the test passed or failed.
if (testInfo.status !== testInfo.expectedStatus) {
// outputPath() API guarantees a unique file name.
const logFile = testInfo.outputPath('logs.txt');
await fs.promises.writeFile(logFile, logs.join('\n'), 'utf8');
testInfo.attachments.push({ name: 'logs', contentType: 'text/plain', path: logFile });
}
}, { auto: true }],
});
export { expect } from '@playwright/test';

フィクスチャのタイムアウト

デフォルトでは、フィクスチャはテストとタイムアウトを共有します。ただし、遅いフィクスチャ、特にワーカー・スコープのフィクスチャの場合、個別のタイムアウトを設定すると便利です。これにより、全体のテストタイムアウトを短く保ち、遅いフィクスチャにより多くの時間を与えることができます。

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

const test = base.extend<{ slowFixture: string }>({
slowFixture: [async ({}, use) => {
// ... perform a slow operation ...
await use('hello');
}, { timeout: 60000 }]
});

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

フィクスチャオプション

Playwright Testは、個別に設定できる複数のテストプロジェクトの実行をサポートしています。「オプション」フィクスチャを使用して、設定オプションを宣言的で型チェックされたものにできます。テストのパラメータ化について詳しくはこちらをご覧ください。

以下では、他の例のtodoPageフィクスチャに加えて、defaultItemオプションを作成します。このオプションは設定ファイルで設定されます。タプル構文と{ option: true }引数に注目してください。

TodoPageのコードを展開するにはクリック
todo-page.ts
import type { Page, Locator } from '@playwright/test';

export class TodoPage {
private readonly inputBox: Locator;
private readonly todoItems: Locator;

constructor(public readonly page: Page) {
this.inputBox = this.page.locator('input.new-todo');
this.todoItems = this.page.getByTestId('todo-item');
}

async goto() {
await this.page.goto('https://demo.playwright.dev/todomvc/');
}

async addToDo(text: string) {
await this.inputBox.fill(text);
await this.inputBox.press('Enter');
}

async remove(text: string) {
const todo = this.todoItems.filter({ hasText: text });
await todo.hover();
await todo.getByLabel('Delete').click();
}

async removeAll() {
while ((await this.todoItems.count()) > 0) {
await this.todoItems.first().hover();
await this.todoItems.getByLabel('Delete').first().click();
}
}
}
my-test.ts
import { test as base } from '@playwright/test';
import { TodoPage } from './todo-page';

// Declare your options to type-check your configuration.
export type MyOptions = {
defaultItem: string;
};
type MyFixtures = {
todoPage: TodoPage;
};

// Specify both option and fixture types.
export const test = base.extend<MyOptions & MyFixtures>({
// Define an option and provide a default value.
// We can later override it in the config.
defaultItem: ['Something nice', { option: true }],

// Our "todoPage" fixture depends on the option.
todoPage: async ({ page, defaultItem }, use) => {
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addToDo(defaultItem);
await use(todoPage);
await todoPage.removeAll();
},
});
export { expect } from '@playwright/test';

これで、通常通りtodoPageフィクスチャを使用し、設定ファイルでdefaultItemオプションを設定できます。

playwright.config.ts
import { defineConfig } from '@playwright/test';
import type { MyOptions } from './my-test';

export default defineConfig<MyOptions>({
projects: [
{
name: 'shopping',
use: { defaultItem: 'Buy milk' },
},
{
name: 'wellbeing',
use: { defaultItem: 'Exercise!' },
},
]
});

オプション値としての配列

オプションの値が配列、例えば[{ name: 'Alice' }, { name: 'Bob' }]である場合、値を提供する際にそれを追加の配列でラップする必要があります。これは例で示すのが最も分かりやすいでしょう。

type Person = { name: string };
const test = base.extend<{ persons: Person[] }>({
// Declare the option, default value is an empty array.
persons: [[], { option: true }],
});

// Option value is an array of persons.
const actualPersons = [{ name: 'Alice' }, { name: 'Bob' }];
test.use({
// CORRECT: Wrap the value into an array and pass the scope.
persons: [actualPersons, { scope: 'test' }],
});

test.use({
// WRONG: passing an array value directly will not work.
persons: actualPersons,
});

実行順序

各フィクスチャには、フィクスチャ内のawait use()呼び出しによって分離されたセットアップフェーズとティアダウンフェーズがあります。セットアップはテスト/フックによってフィクスチャが使用される前に実行され、ティアダウンはフィクスチャがテスト/フックによって使用されなくなったときに実行されます。

フィクスチャは、実行順序を決定するために以下のルールに従います。

  • フィクスチャAがフィクスチャBに依存する場合:Bは常にAの前にセットアップされ、Aの後にティアダウンされます。
  • 非自動フィクスチャは、テスト/フックが必要とする場合にのみ遅延実行されます。
  • テストスコープのフィクスチャは各テストの後にティアダウンされ、ワーカー・スコープのフィクスチャはテストを実行しているワーカープロセスがシャットダウンされたときにのみティアダウンされます。

以下の例を検討してください。

import { test as base } from '@playwright/test';

const test = base.extend<{
testFixture: string,
autoTestFixture: string,
unusedFixture: string,
}, {
workerFixture: string,
autoWorkerFixture: string,
}>({
workerFixture: [async ({ browser }) => {
// workerFixture setup...
await use('workerFixture');
// workerFixture teardown...
}, { scope: 'worker' }],

autoWorkerFixture: [async ({ browser }) => {
// autoWorkerFixture setup...
await use('autoWorkerFixture');
// autoWorkerFixture teardown...
}, { scope: 'worker', auto: true }],

testFixture: [async ({ page, workerFixture }) => {
// testFixture setup...
await use('testFixture');
// testFixture teardown...
}, { scope: 'test' }],

autoTestFixture: [async () => {
// autoTestFixture setup...
await use('autoTestFixture');
// autoTestFixture teardown...
}, { scope: 'test', auto: true }],

unusedFixture: [async ({ page }) => {
// unusedFixture setup...
await use('unusedFixture');
// unusedFixture teardown...
}, { scope: 'test' }],
});

test.beforeAll(async () => { /* ... */ });
test.beforeEach(async ({ page }) => { /* ... */ });
test('first test', async ({ page }) => { /* ... */ });
test('second test', async ({ testFixture }) => { /* ... */ });
test.afterEach(async () => { /* ... */ });
test.afterAll(async () => { /* ... */ });

通常、すべてのテストが合格し、エラーがスローされない場合、実行順序は以下のようになります。

  • ワーカーのセットアップとbeforeAllセクション
    • autoWorkerFixtureが必要とするため、browserのセットアップ。
    • 自動ワーカーフィクスチャは常に他の何よりも前にセットアップされるため、autoWorkerFixtureのセットアップ。
    • beforeAllが実行されます。
  • 最初のテストセクション
    • 自動テストフィクスチャは常にテストおよびbeforeEachフックの前にセットアップされるため、autoTestFixtureのセットアップ。
    • beforeEachフックで必要とされるため、pageのセットアップ。
    • beforeEachが実行されます。
    • 最初のテストが実行されます。
    • afterEachが実行されます。
    • pageのティアダウン。これはテストスコープのフィクスチャであり、テスト終了後にティアダウンされるべきであるため。
    • autoTestFixtureのティアダウン。これはテストスコープのフィクスチャであり、テスト終了後にティアダウンされるべきであるため。
  • 2番目のテストセクション
    • 自動テストフィクスチャは常にテストおよびbeforeEachフックの前にセットアップされるため、autoTestFixtureのセットアップ。
    • beforeEachフックで必要とされるため、pageのセットアップ。
    • beforeEachが実行されます。
    • 2番目のテストで必要とされるtestFixtureによって必要とされるため、workerFixtureのセットアップ。
    • 2番目のテストによって必要とされるため、testFixtureのセットアップ。
    • 2番目のテストが実行されます。
    • afterEachが実行されます。
    • testFixtureのティアダウン。これはテストスコープのフィクスチャであり、テスト終了後にティアダウンされるべきであるため。
    • pageのティアダウン。これはテストスコープのフィクスチャであり、テスト終了後にティアダウンされるべきであるため。
    • autoTestFixtureのティアダウン。これはテストスコープのフィクスチャであり、テスト終了後にティアダウンされるべきであるため。
  • afterAllとワーカーのティアダウンセクション
    • afterAllが実行されます。
    • workerFixtureのティアダウン。これはワーカー・スコープのフィクスチャであり、最後に1回だけティアダウンされるべきであるため。
    • autoWorkerFixtureのティアダウン。これはワーカー・スコープのフィクスチャであり、最後に1回だけティアダウンされるべきであるため。
    • browserのティアダウン。これはワーカー・スコープのフィクスチャであり、最後に1回だけティアダウンされるべきであるため。

いくつかの観察

  • pageautoTestFixtureは、テストスコープのフィクスチャとして、各テストに対してセットアップおよびティアダウンされます。
  • unusedFixtureは、どのテスト/フックでも使用されないため、セットアップされることはありません。
  • testFixtureworkerFixtureに依存し、そのセットアップをトリガーします。
  • workerFixtureは2番目のテストの前に遅延セットアップされますが、ワーカーシャットダウン中にワーカー・スコープのフィクスチャとして1回ティアダウンされます。
  • autoWorkerFixturebeforeAllフックのためにセットアップされますが、autoTestFixtureはセットアップされません。

複数のモジュールからカスタムフィクスチャを結合する

複数のファイルまたはモジュールからテストフィクスチャをマージできます。

fixtures.ts
import { mergeTests } from '@playwright/test';
import { test as dbTest } from 'database-test-utils';
import { test as a11yTest } from 'a11y-test-utils';

export const test = mergeTests(dbTest, a11yTest);
test.spec.ts
import { test } from './fixtures';

test('passes', async ({ database, page, a11y }) => {
// use database and a11y fixtures.
});

ボックスフィクスチャ

通常、カスタムフィクスチャはUIモード、トレースビューア、およびさまざまなテストレポートで個別のステップとして報告されます。また、テストランナーからのエラーメッセージにも表示されます。頻繁に使用されるフィクスチャの場合、これは多くのノイズを意味する可能性があります。「ボックス化」することで、UIにフィクスチャのステップが表示されないようにすることができます。

import { test as base } from '@playwright/test';

export const test = base.extend({
helperFixture: [async ({}, use, testInfo) => {
// ...
}, { box: true }],
});

これは、興味のないヘルパーフィクスチャに役立ちます。たとえば、共通のデータをセットアップする自動フィクスチャは、テストレポートから安全に非表示にできます。

カスタムフィクスチャのタイトル

通常のフィクスチャ名ではなく、テストレポートやエラーメッセージに表示されるカスタムタイトルをフィクスチャに与えることができます。

import { test as base } from '@playwright/test';

export const test = base.extend({
innerFixture: [async ({}, use, testInfo) => {
// ...
}, { title: 'my fixture' }],
});

グローバルなbeforeEach/afterEachフックの追加

test.beforeEach()test.afterEach()フックは、同じファイルおよび同じtest.describe()ブロック(存在する場合)で宣言された各テストの前後で実行されます。各テストの前後でグローバルに実行されるフックを宣言したい場合は、次のように自動フィクスチャとして宣言できます。

fixtures.ts
import { test as base } from '@playwright/test';

export const test = base.extend<{ forEachTest: void }>({
forEachTest: [async ({ page }, use) => {
// This code runs before every test.
await page.goto('https://:8000');
await use();
// This code runs after every test.
console.log('Last URL:', page.url());
}, { auto: true }], // automatically starts for every test.
});

そして、すべてのテストでフィクスチャをインポートします。

mytest.spec.ts
import { test } from './fixtures';
import { expect } from '@playwright/test';

test('basic', async ({ page }) => {
expect(page).toHaveURL('https://:8000');
await page.goto('https://playwright.dokyumento.jp');
});

グローバルなbeforeAll/afterAllフックの追加

test.beforeAll()test.afterAll()フックは、同じファイルおよび同じtest.describe()ブロック(存在する場合)で宣言されたすべてのテストの前後で、ワーカープロセスごとに1回実行されます。すべてのファイル内のすべてのテストの前後で実行されるフックを宣言したい場合は、次のようにscope: 'worker'を指定した自動フィクスチャとして宣言できます。

fixtures.ts
import { test as base } from '@playwright/test';

export const test = base.extend<{}, { forEachWorker: void }>({
forEachWorker: [async ({}, use) => {
// This code runs before all the tests in the worker process.
console.log(`Starting test worker ${test.info().workerIndex}`);
await use();
// This code runs after all the tests in the worker process.
console.log(`Stopping test worker ${test.info().workerIndex}`);
}, { scope: 'worker', auto: true }], // automatically starts for every worker.
});

そして、すべてのテストでフィクスチャをインポートします。

mytest.spec.ts
import { test } from './fixtures';
import { expect } from '@playwright/test';

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

フィクスチャはワーカープロセスごとに1回実行されますが、すべてのファイルでそれらを再宣言する必要はありません。