vitalets / playwright-bdd

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

Question: Example code for writing custom locators #152

Closed NikkTod closed 4 months ago

NikkTod commented 4 months ago

Hi @vitalets, do you happen to have some example on how we write custom locators with decoratrs syntax.

In my fixture file I have the following:

image

But how to call it from the my POM page file

image

vitalets commented 4 months ago

This is because TypeScript does not know that you added getByDataTestId method to the page. In general I'd suggest to not augment Playwright's built-in objects like page, etc. I see two options:

  1. Inherit your POMs from the BasePage that contains such common methods:

    
    class BasePage {
    constructor(public page) {}
    
    getByDataTestId(id: string) {
    return the.page.locator(`[data-test="${id}"]`);
    }
    }

class RealPage extends BasePage { getSubmitButton() { return this.getByDataTestId('submit'); } }

// ... base.extend({ realPage: ({ page }, use) => use(new RealPage(page)) });


2. Or create a separate helper fixture and pass it to POMs:
```ts
class Helper {
  constructor(public page) {}

   getByDataTestId(id: string) {
    return the.page.locator(`[data-test="${id}"]`);
  }
}

class RealPage {
  constructor(public helper: Helper) {}

  get page() {
    return this.helper.page;
  }

  getSubmitButton() {
    return this.helper.getByDataTestId('submit');
  }
}

// ...
base.extend({
  helper: ({ page }, use) => use(new Helper(page)),
  realPage: ({ helper }, use) => use(new RealPage(helper))
});
NikkTod commented 4 months ago

@vitalets thanks for confirming, will go with option 1, I already have such common class.