This page explains how to verify the text displayed in JavaScript dialogs.
Note on automatic dialog handling
In Nexus test runs, if a scenario does not include a specific step to close a dialog, the dialog will be closed automatically when it appears.
The types of dialogs that are subject to this automatic closing during execution are:
confirmdialog (OK, Cancel)
alertdialog (OK)
promptdialog (Text input field, OK, Cancel)
Verification steps
By using Playwright's page.waitForEvent('dialog') pattern, you can wait for a dialog to appear and verify its contents. To perform this verification, you must include both the code to wait for the dialog event and the action that triggers the dialog (such as a button click) in your code.
Sample code for an alert dialog
The sample code below verifies that the text of an alert dialog displayed upon clicking a button is "I am a JS Alert".
const dialogPromise = page.waitForEvent('dialog', (dialog) => {
// Verify the dialog message
expect(dialog.message()).toBe('I am a JS Alert');
// Verify that the dialog type is 'alert'
expect(dialog.type()).toBe('alert');
// Dismiss the dialog
dialog.dismiss();
return true;
});
// Click the element that triggers the dialog
await page.getByRole('button', { name: 'Click for JS Alert' }).click();
// Wait for the dialog to be handled
await dialogPromise;Code explanation
page.waitForEvent('dialog', (dialog) => { ... })Waits for a dialog event to occur. When the dialog appears, the callback function (the second argument) is executed.
expect(dialog.message()).toBe('Expected Text')Retrieves the message displayed in the dialog and verifies (asserts) that it matches the expected text.
expect(dialog.type()).toBe('alert')Verifies the type of dialog. Specify
alertfor an alert orconfirmfor a confirmation dialog.
dialog.dismiss()Closes the dialog. If you want to simulate clicking "OK" on a confirmation dialog, use
dialog.accept().
await page.getByRole(...).click()This is the action that triggers the dialog. Please change this to match the target element or action as needed.
How to check your test implementation
To confirm that the assertion is working as expected, try temporarily changing the expected string passed to
toBe()to an incorrect value (e.g.,toBe('Incorrect Text')) and run the test. If the test fails as expected, then you have confirmed that the verification step is working as intended.