Handle a JavaScript dialog
Register a dialog handler before the action, then accept, dismiss, or answer alert, confirm, and prompt.
A JavaScript dialog from alert(), confirm(), or prompt() blocks the page until it is handled. Register the handler on the page before the action that opens the dialog, because the dialog fires during that action, not after it.
Register the handler before the action
Attach the handler with onDialog(), then perform the action. The handler receives the Dialog and decides what to do with it.
$page->events()->onDialog(static function ($dialog): void {
if ('confirm' === $dialog->type()) {
$dialog->accept();
return;
}
$dialog->dismiss();
});
$page->getByRole('button', ['name' => 'Remove account'])->click();
expect($page->getByText('Account removal scheduled'))->toBeVisible();
$dialog->type() is alert, confirm, or prompt. $dialog->message() is the text shown to the user.
Answer a prompt
For a prompt, pass the reply to accept(). Use $dialog->defaultValue() to read the field's initial text if you need it.
$page->events()->onDialog(static function ($dialog): void {
$dialog->accept('Ada Lovelace');
});
$page->getByRole('button', ['name' => 'Rename project'])->click();
The unhandled-dialog trap
The library keeps a dialog listener attached to every page, so an unhandled dialog is not auto-dismissed. The action that opened it waits, then times out. Always register a handler before the action, and keep the handler narrow: accept or dismiss, nothing more.
$page->events()->onDialog(static fn ($dialog) => $dialog->dismiss());
$page->getByRole('button', ['name' => 'Leave page'])->click();
Pitfalls
- A handler registered after the click misses the dialog, and the click hangs on the open dialog.
- Do not run navigation or assertions inside the handler. Collect what you need, respond to the dialog, and assert in the test body.
Expected result
The action that opens the dialog completes, because the handler answered it. Assert the page state after the dialog, such as a confirmation message, rename result, or unchanged page after dismissal.