0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Playwrightでブラウザのダイアログをテストする

Posted at

この記事は何か?

Playwrightでブラウザのダイアログ(alert、confirm、prompt)をテストする方法を解説する。

目次

ダイアログ処理の基本フロー

Playwrightでダイアログを処理する際は、以下の手順で実装する。

  1. ダイアログイベントのリスナーを登録する
    • リスナー内にダイアログの検証を記述する
    • リスナー内にダイアログを閉じる操作を記述する
  2. ダイアログを表示する操作を実行する

ダイアログの種類と処理方法

Alertダイアログ

Alertダイアログはユーザーへの通知を目的とし、OK以外の選択肢はない。
以下は実装例である。

test('Alertダイアログの処理', async ({ page }) => {
  await page.goto('https://example.com');

  page.once('dialog', async dialog => {
    expect(dialog.type()).toBe('alert');
    expect(dialog.message()).toBe('これはAlertダイアログです');
    await dialog.accept();
  });

  await page.getByRole('button', { name: 'Alert表示' }).click();
});

Confirmダイアログ

ConfirmダイアログはOKとキャンセルの選択肢を持つ。accept()でOK、dismiss()でキャンセルを選択できる。
以下は実装例である。

test('Confirmダイアログの処理', async ({ page }) => {
  await page.goto('https://example.com');

  page.once('dialog', async dialog => {
    expect(dialog.type()).toBe('confirm');
    expect(dialog.message()).toBe('OKをクリックしますか?');
    await dialog.accept();
  });

  await page.getByRole('button', { name: 'Confirm表示' }).click();
});

キャンセルする場合はdismiss()を使用する。

await dialog.dismiss();

Promptダイアログ

Promptダイアログはテキスト入力を受け付ける。accept()の引数に入力値を渡す。
以下は実装例である。

test('Promptダイアログの処理', async ({ page }) => {
  await page.goto('https://example.com');

  page.once('dialog', async dialog => {
    expect(dialog.type()).toBe('prompt');
    expect(dialog.message()).toBe('名前を入力してください');
    await dialog.accept('山田太郎');
  });

  await page.getByRole('button', { name: 'Prompt表示' }).click();
});

入力なしでキャンセルする場合はdismiss()を使用する。

await dialog.dismiss();

リスナーの登録タイミング

ダイアログイベントのリスナーは、ダイアログを表示する操作より前に登録する必要がある。以下は誤った実装例である。

// 誤った例
await page.getByRole('button', { name: 'Alert表示' }).click();

page.once('dialog', async dialog => {  // この時点では既にダイアログが表示済み
  await dialog.accept();
});

この実装では、ダイアログ表示後にリスナーを登録しているため、イベントを捕捉できない。

参考資料

Dialogs - Playwright

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?