Testing modals

Find the dialog, then look inside it

A modal is a dialog with a name. Scope every locator to it: buttons such as "Close" or "Cancel" often exist elsewhere on the page too.

const invite = page.getByRole('dialog', { name: 'Invite teammate' });
await invite.getByLabel('Email').fill('ada@example.com');
await invite.getByRole('button', { name: 'Send invite' }).click();
await expect(invite).toBeHidden();

The page behind a modal

A native <dialog> opened with showModal() makes the rest of the page inert. Playwright waits for an inert button to become clickable, so the click times out. That is the modal working. Custom modals only cover the page with a backdrop; there the error says another element "intercepts pointer events".

// A short trial click proves the page behind is blocked.
await expect(
  page.getByRole('button', { name: 'Rename project' }).click({ trial: true, timeout: 1000 })
).rejects.toThrow();

Focus

A good modal moves focus inside when it opens, keeps Tab inside while open, and gives focus back to the button that opened it. Check all three with toBeFocused().

A modal on top of a modal

Both dialogs are on the page at the same time. Give each its own locator by name, and assert which ones are still open.

Popups that appear whenever they like

Newsletter and cookie popups appear at random moments and block clicks. A try/catch around every click cannot cover all of them. Register a handler once: before each action, Playwright checks whether the overlay is visible and runs your handler first.

await page.addLocatorHandler(
  page.getByRole('dialog', { name: 'Join our newsletter' }),
  async (overlay) => {
    await overlay.getByRole('button', { name: 'No thanks' }).click();
  }
);

Native dialog

Project: Apollo

Rename project

Custom modal

Sending an invite takes a moment.

Modal over a modal

Post: Hello world

Shop

Cart: 0 items

Loading products…