vitalets/playwright-bdd

Question:Best way to use Add Locator Handler?

RichardCariven opened this issue · 2 comments

I need to use https://playwright.dev/docs/api/class-page#page-add-locator-handler in my tests to handle a random dialogue popup that is breaking my tests.

with non playwright BDD test usually I could add the Handler in at the start of the test case and then it would run before every step

With the PlaywrightBDD can I just add it to one step, and will it then apply to all following steps in a feature or do I need to call it explicitly in every step?

There are different options:

  1. If locator handler should be applied on all pages, you can enable it in auto-fixture:
export const test = base.extend({
  handleSignupPopup: [async ({ page }, use) => {
    await page.addLocatorHandler(page.getByText('Sign up to the newsletter'), async () => {
      await page.getByRole('button', { name: 'No thanks' }).click();
    });
    await use();
  }, { auto: true }]
});
  1. If handler should be applied only on some pages, you can filter it by tags in auto-fixture as well:
export const test = base.extend({
  handleSignupPopup: [async ({ page, $tags }, use) => {
    if ($tags.includes('@haspopup')) {
      await page.addLocatorHandler(page.getByText('Sign up to the newsletter'), async () => {
        await page.getByRole('button', { name: 'No thanks' }).click();
      });
    }
    await use();
  }, { auto: true }]
});
  1. And as you mentioned, it is possible to apply locator handler explicitly by step, I would only suggest to do it in background step:
Feature: my feature

    Background:
      Given I always decline signup popup

    Scenario: ...

Step:

Given('I always decline signup popup', async ({ page }) => {
  await page.addLocatorHandler(page.getByText('Sign up to the newsletter'), async () => {
    await page.getByRole('button', { name: 'No thanks' }).click();
  });
});

Great thankyou, I was on holiday but have just done the auto fixture approach