vitalets / playwright-bdd

BDD testing with Playwright runner
https://vitalets.github.io/playwright-bdd/
MIT License
304 stars 36 forks source link

Question:Best way to use Add Locator Handler? #231

Open RichardCariven opened 4 days ago

RichardCariven commented 4 days ago

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?

vitalets commented 4 days ago

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 }]
    });
  2. 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 }]
    });
  3. 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:
```js
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();
  });
});