Playwright アサーション(Assertions)
この章では、Playwright のアサーション体系について包括的に紹介します。自動リトライアサーション、汎用アサーション、ソフトアサーションの使い方も含みます。
アサーションとは
アサーション(Assertion)は、テストの期待結果が実際の結果と一致しているかどうかを検証するために使用します。
Playwright には2つのアサーションが用意されています:汎用アサーション(Jest 由来)と自動リトライアサーション(Playwright 独自)。
自動リトライアサーション vs 汎用アサーション
自動リトライアサーション(Async Matchers)
Playwright の Web 固有アサーションは、条件が満たされるかタイムアウトするまで自動的にリトライします。必ず使用する必要があります。await。
例
// 自動リトライアサーション —— 条件が満たされるまで待機する
await expect(page.getByText('サンプル')).toBeVisible();
await expect(page.getByText('サンプル')).toBeVisible();
汎用アサーション
非 Web 固有の値の比較に使用され、自動リトライは行われません。
例
// 汎用アサーション —— 即座に実行され、待機しない
expect(1 + 1).toBe(2);
expect('hello').toContain('ell');
expect(true).toBeTruthy();
expect(1 + 1).toBe(2);
expect('hello').toContain('ell');
expect(true).toBeTruthy();
| タイプ | 自動リトライの有無 | await の必要性 | 適用シナリオ |
|---|---|---|---|
| 自動リトライアサーション | である | 必須await | ページ要素、URL、タイトルなどの Web 固有コンテンツ |
| 汎用アサーション | 否 | 不要 | 通常の変数、配列、オブジェクトなどの JavaScript 値 |
ページレベルのアサーション
例
// ページタイトルのアサーション
await expect(page).toHaveTitle(サンプル - 学ぶのは技術だけではなく、夢でもあります!);
await expect(page).toHaveTitle(/サンプル/);
// ページ URL のアサーション
await expect(page).toHaveURL('https://www.example.com/');
await expect(page).toHaveURL(/サンプル\.com/);
await expect(page).toHaveTitle(サンプル - 学ぶのは技術だけではなく、夢でもあります!);
await expect(page).toHaveTitle(/サンプル/);
// ページ URL のアサーション
await expect(page).toHaveURL('https://www.example.com/');
await expect(page).toHaveURL(/サンプル\.com/);
可視性アサーション
例
const btn = page.getByRole('button', { name: '提交' });
// 要素が表示されている
await expect(btn).toBeVisible();
// 要素が非表示
await expect(btn).toBeHidden();
// 要素が DOM に存在する(ただし、表示されているとは限らない)
await expect(btn).toBeAttached();
// 要素がビューポート内で表示されている
await expect(btn).toBeInViewport();
// 要素が表示されている
await expect(btn).toBeVisible();
// 要素が非表示
await expect(btn).toBeHidden();
// 要素が DOM に存在する(ただし、表示されているとは限らない)
await expect(btn).toBeAttached();
// 要素がビューポート内で表示されている
await expect(btn).toBeInViewport();
テキストと値のアサーション
例
const heading = page.getByRole('heading', { name: 'サンプル' });
// 要素のテキスト内容が完全一致する
await expect(heading).toHaveText('学ぶのは技術だけでなく、夢でもある!');
// 要素のテキスト内容が部分文字列を含む
await expect(heading).toContainText('技术');
// input の現在値
await expect(page.getByLabel('用户名')).toHaveValue('サンプル_user');
// 要素の内容が空である
await expect(page.getByTestId('error-msg')).toBeEmpty();
// 要素のテキスト内容が完全一致する
await expect(heading).toHaveText('学ぶのは技術だけでなく、夢でもある!');
// 要素のテキスト内容が部分文字列を含む
await expect(heading).toContainText('技术');
// input の現在値
await expect(page.getByLabel('用户名')).toHaveValue('サンプル_user');
// 要素の内容が空である
await expect(page.getByTestId('error-msg')).toBeEmpty();
状態アサーション
例
const checkbox = page.getByLabel('同意协议');
const input = page.getByLabel('邮箱');
// 要素が有効である
await expect(input).toBeEnabled();
// 要素が無効である
await expect(input).toBeDisabled();
// 要素が編集可能である
await expect(input).toBeEditable();
// チェックボックスがオンになっている
await expect(checkbox).toBeChecked();
// 要素がフォーカスを取得している
await expect(input).toBeFocused();
const input = page.getByLabel('邮箱');
// 要素が有効である
await expect(input).toBeEnabled();
// 要素が無効である
await expect(input).toBeDisabled();
// 要素が編集可能である
await expect(input).toBeEditable();
// チェックボックスがオンになっている
await expect(checkbox).toBeChecked();
// 要素がフォーカスを取得している
await expect(input).toBeFocused();
属性アサーション
例
const element = page.locator('.サンプル-logo');
// DOM 属性のアサーション
await expect(element).toHaveAttribute('src', '/static/images/logo.png');
// 属性の存在のみをチェックする
await expect(element).toHaveAttribute('alt');
// CSS クラス名のアサーション
await expect(element).toHaveClass('logo-primary');
// CSS プロパティ値のアサーション
await expect(element).toHaveCSS('display', 'block');
// 要素 ID のアサーション
await expect(element).toHaveId('main-logo');
// アクセシブルな名前(アクセシブルネーム)
await expect(page.getByRole('button')).toHaveAccessibleName('提交');
// DOM 属性のアサーション
await expect(element).toHaveAttribute('src', '/static/images/logo.png');
// 属性の存在のみをチェックする
await expect(element).toHaveAttribute('alt');
// CSS クラス名のアサーション
await expect(element).toHaveClass('logo-primary');
// CSS プロパティ値のアサーション
await expect(element).toHaveCSS('display', 'block');
// 要素 ID のアサーション
await expect(element).toHaveId('main-logo');
// アクセシブルな名前(アクセシブルネーム)
await expect(page.getByRole('button')).toHaveAccessibleName('提交');
数量アサーション
例
// 一致する要素の数
const items = page.getByRole('listitem');
await expect(items).toHaveCount(5);
// filter と組み合わせて使用
const activeItems = page.getByRole('listitem').filter({ hasText: '已激活' });
await expect(activeItems).toHaveCount(3);
const items = page.getByRole('listitem');
await expect(items).toHaveCount(5);
// filter と組み合わせて使用
const activeItems = page.getByRole('listitem').filter({ hasText: '已激活' });
await expect(activeItems).toHaveCount(3);
汎用アサーション早見表
| メソッド | 説明 | 例 |
|---|---|---|
toBe(value) | 厳密等価(===) | expect(x).toBe(42) |
toEqual(value) | 深い等価 | expect(obj).toEqual({ a: 1 }) |
toContain(item) | 配列/文字列の包含 | expect(arr).toContain('a') |
toBeTruthy() | 値が真値である | expect(x).toBeTruthy() |
toBeFalsy() | 値が偽値である | expect(x).toBeFalsy() |
toBeNull() | 値が null である | expect(x).toBeNull() |
toBeGreaterThan(n) | n より大きい | expect(x).toBeGreaterThan(10) |
toBeLessThan(n) | n より小さい | expect(x).toBeLessThan(100) |
toHaveLength(n) | 配列の長さ | expect(arr).toHaveLength(3) |
expect.soft() ソフトアサーション
通常のアサーションは失敗すると、テストを即座に終了します。
ソフトアサーション失敗しても終了せず、後続のコードを実行し続け、テスト終了時にすべての失敗をまとめて報告します。
例
test('表单验证多项检查', async ({ page }) => {
await page.goto('https://example.com/form');
// ソフトアサーション —— 失敗してもテストは止まらない
await expect.soft(page.getByLabel('用户名')).toBeVisible();
await expect.soft(page.getByLabel('密码')).toBeVisible();
await expect.soft(page.getByLabel('邮箱')).toBeVisible();
await expect.soft(page.getByRole('button', { name: '注册' })).toBeEnabled();
// 上記のいずれかのアサーションが失敗しても、チェックを続行し、最後にまとめて報告する
});
await page.goto('https://example.com/form');
// ソフトアサーション —— 失敗してもテストは止まらない
await expect.soft(page.getByLabel('用户名')).toBeVisible();
await expect.soft(page.getByLabel('密码')).toBeVisible();
await expect.soft(page.getByLabel('邮箱')).toBeVisible();
await expect.soft(page.getByRole('button', { name: '注册' })).toBeEnabled();
// 上記のいずれかのアサーションが失敗しても、チェックを続行し、最後にまとめて報告する
});
フォームページをテストする際に使用します
expect.soft()欠落しているフィールドを一度にすべて見つけることができ、一つずつ修正してから次の問題を確認する必要がありません。これにより、デバッグ効率が大幅に向上します。
アサーションタイムアウト
自動リトライアサーションのデフォルトタイムアウトは5秒で、設定ファイルまたは個別のアサーションでカスタマイズできます:
例
// 個別のアサーションのタイムアウトを設定(ミリ秒)
await expect(page.getByText('加载中...')).toBeHidden({ timeout: 10000 });
// 設定ファイルでグローバルに設定する
// playwright.config.ts:
// export default defineConfig({
// expect: { timeout: 10000 },
// });
await expect(page.getByText('加载中...')).toBeHidden({ timeout: 10000 });
// 設定ファイルでグローバルに設定する
// playwright.config.ts:
// export default defineConfig({
// expect: { timeout: 10000 },
// });