アサーション
はじめに
Playwright には、expect 関数の形式でテストアサーションが含まれています。アサーションを行うには、expect(value) を呼び出し、期待を反映するマッチャーを選択します。toEqual、toContain、toBeTruthy など、あらゆる条件をアサートするために使用できる多くの汎用マッチャーがあります。
expect(success).toBeTruthy();
Playwright には、期待される条件が満たされるまで待機するウェブ固有の非同期マッチャーも含まれています。次の例を考えてみましょう。
await expect(page.getByTestId('status')).toHaveText('Submitted');
Playwright は、取得した要素が"Submitted"テキストを持つまで、テスト ID がstatusの要素を再テストします。条件が満たされるかタイムアウトに達するまで、要素を繰り返し再取得してチェックします。このタイムアウトを渡すか、テスト設定のtestConfig.expect値を使用して一度設定できます。
デフォルトでは、アサーションのタイムアウトは 5 秒に設定されています。さまざまなタイムアウトの詳細については、こちらをご覧ください。
自動再試行アサーション
以下のアサーションは、アサーションが成功するか、アサーションタイムアウトに達するまで再試行します。再試行アサーションは非同期であるため、await する必要があることに注意してください。
非再試行アサーション
これらのアサーションは、任意の条件をテストできますが、自動再試行は行いません。ほとんどの場合、Webページは情報を非同期に表示するため、非再試行アサーションを使用すると不安定なテストにつながる可能性があります。
可能な限り自動再試行アサーションを使用してください。再試行が必要なより複雑なアサーションの場合は、expect.poll または expect.toPass を使用してください。
マッチャーの否定
一般的に、マッチャーの先頭に .not を追加することで、逆が真であると期待できます。
expect(value).not.toEqual(0);
await expect(locator).not.toContainText('some text');
ソフトアサーション
デフォルトでは、アサーションの失敗はテスト実行を終了します。Playwright はソフトアサーションもサポートしています。ソフトアサーションの失敗はテスト実行を**終了させず**、テストを失敗としてマークします。
// Make a few checks that will not stop the test when failed...
await expect.soft(page.getByTestId('status')).toHaveText('Success');
await expect.soft(page.getByTestId('eta')).toHaveText('1 day');
// ... and continue the test to check more things.
await page.getByRole('link', { name: 'next page' }).click();
await expect.soft(page.getByRole('heading', { name: 'Make another order' })).toBeVisible();
テスト実行中の任意の時点で、ソフトアサーションの失敗があったかどうかを確認できます。
// Make a few checks that will not stop the test when failed...
await expect.soft(page.getByTestId('status')).toHaveText('Success');
await expect.soft(page.getByTestId('eta')).toHaveText('1 day');
// Avoid running further if there were soft assertion failures.
expect(test.info().errors).toHaveLength(0);
ソフトアサーションは Playwright テストランナーでのみ機能することに注意してください。
カスタム expect メッセージ
expect 関数の2番目の引数としてカスタム expect メッセージを指定できます。例:
await expect(page.getByText('Name'), 'should be logged in').toBeVisible();
このメッセージは、アサーションに関するより多くのコンテキストを提供し、成功した期待と失敗した期待の両方でレポーターに表示されます。
expect が成功した場合、次のような成功ステップが表示されることがあります。
✅ should be logged in @example.spec.ts:18
expect が失敗した場合、エラーは次のようになります。
Error: should be logged in
Call log:
- expect.toBeVisible with timeout 5000ms
- waiting for "getByText('Name')"
2 |
3 | test('example test', async({ page }) => {
> 4 | await expect(page.getByText('Name'), 'should be logged in').toBeVisible();
| ^
5 | });
6 |
ソフトアサーションもカスタムメッセージをサポートしています。
expect.soft(value, 'my soft assertion').toBe(56);
expect.configure
timeout や soft などの独自のデフォルト値を持つ独自の事前設定された expect インスタンスを作成できます。
const slowExpect = expect.configure({ timeout: 10000 });
await slowExpect(locator).toHaveText('Submit');
// Always do soft assertions.
const softExpect = expect.configure({ soft: true });
await softExpect(locator).toHaveText('Submit');
expect.poll
expect.poll を使用すると、任意の同期 expect を非同期ポーリングのものに変換できます。
次のメソッドは、HTTP ステータス 200 を返すまで指定された関数をポーリングします。
await expect.poll(async () => {
const response = await page.request.get('https://api.example.com');
return response.status();
}, {
// Custom expect message for reporting, optional.
message: 'make sure API eventually succeeds',
// Poll for 10 seconds; defaults to 5 seconds. Pass 0 to disable timeout.
timeout: 10000,
}).toBe(200);
カスタムポーリング間隔も指定できます。
await expect.poll(async () => {
const response = await page.request.get('https://api.example.com');
return response.status();
}, {
// Probe, wait 1s, probe, wait 2s, probe, wait 10s, probe, wait 10s, probe
// ... Defaults to [100, 250, 500, 1000].
intervals: [1_000, 2_000, 10_000],
timeout: 60_000
}).toBe(200);
expect.configure({ soft: true }) と expect.poll を組み合わせて、ポーリングロジックでソフトアサーションを実行できます。
const softExpect = expect.configure({ soft: true });
await softExpect.poll(async () => {
const response = await page.request.get('https://api.example.com');
return response.status();
}, {}).toBe(200);
これにより、ポーリング内のアサーションが失敗してもテストが続行されます。
expect.toPass
コードのブロックが正常に通過するまで再試行できます。
await expect(async () => {
const response = await page.request.get('https://api.example.com');
expect(response.status()).toBe(200);
}).toPass();
カスタムのタイムアウトと再試行間隔も指定できます。
await expect(async () => {
const response = await page.request.get('https://api.example.com');
expect(response.status()).toBe(200);
}).toPass({
// Probe, wait 1s, probe, wait 2s, probe, wait 10s, probe, wait 10s, probe
// ... Defaults to [100, 250, 500, 1000].
intervals: [1_000, 2_000, 10_000],
timeout: 60_000
});
デフォルトでは、toPass のタイムアウトは 0 であり、カスタムのexpect timeoutは尊重されません。
expect.extend を使用したカスタムマッチャーの追加
カスタムマッチャーを提供することで、Playwright のアサーションを拡張できます。これらのマッチャーは expect オブジェクトで使用できます。
この例では、カスタムの toHaveAmount 関数を追加しています。カスタムマッチャーは、アサーションが成功したかどうかを示す pass フラグと、アサーションが失敗したときに使用される message コールバックを返す必要があります。
import { expect as baseExpect } from '@playwright/test';
import type { Locator } from '@playwright/test';
export { test } from '@playwright/test';
export const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: number, options?: { timeout?: number }) {
const assertionName = 'toHaveAmount';
let pass: boolean;
let matcherResult: any;
try {
const expectation = this.isNot ? baseExpect(locator).not : baseExpect(locator);
await expectation.toHaveAttribute('data-amount', String(expected), options);
pass = true;
} catch (e: any) {
matcherResult = e.matcherResult;
pass = false;
}
if (this.isNot) {
pass =!pass;
}
const message = pass
? () => this.utils.matcherHint(assertionName, undefined, undefined, { isNot: this.isNot }) +
'\n\n' +
`Locator: ${locator}\n` +
`Expected: not ${this.utils.printExpected(expected)}\n` +
(matcherResult ? `Received: ${this.utils.printReceived(matcherResult.actual)}` : '')
: () => this.utils.matcherHint(assertionName, undefined, undefined, { isNot: this.isNot }) +
'\n\n' +
`Locator: ${locator}\n` +
`Expected: ${this.utils.printExpected(expected)}\n` +
(matcherResult ? `Received: ${this.utils.printReceived(matcherResult.actual)}` : '');
return {
message,
pass,
name: assertionName,
expected,
actual: matcherResult?.actual,
};
},
});
これで、テストで toHaveAmount を使用できます。
import { test, expect } from './fixtures';
test('amount', async () => {
await expect(page.locator('.cart')).toHaveAmount(4);
});
expect ライブラリとの互換性
Playwright の expect をexpect ライブラリと混同しないでください。後者は Playwright テストランナーと完全に統合されていないため、Playwright 独自の expect を使用するようにしてください。
複数のモジュールからのカスタムマッチャーの結合
複数のファイルまたはモジュールからカスタムマッチャーを結合できます。
import { mergeTests, mergeExpects } from '@playwright/test';
import { test as dbTest, expect as dbExpect } from 'database-test-utils';
import { test as a11yTest, expect as a11yExpect } from 'a11y-test-utils';
export const expect = mergeExpects(dbExpect, a11yExpect);
export const test = mergeTests(dbTest, a11yTest);
import { test, expect } from './fixtures';
test('passes', async ({ database }) => {
await expect(database).toHaveDatabaseUser('admin');
});