0

When creating a Page Object Model class (In this case i'll use JavaScript/TypeScript example) I see 2 typical ways of doing locators. Typically either something like this:

export class LoginPage {
    readonly page: Page;
    readonly LOGIN_BUTTON: Locator;

    constructor(page: Page) {
        this.page = page;
        this.LOGIN_BUTTON = page.locator('#login');
    }
    ...
}

However I also occasionally see them as their own functions. So something like this:

export class LoginPage {
        readonly page: Page;
        private loginButton = () => this.page.locator('#login');
    
        constructor(page: Page) {
            this.page = page;
        }
        ...
    }

Is there really a big difference between something like this outside of readability? I overwhelmingly see the first example used more, but figured it was worth asking.

2
  • Isn't locator in second example eveluated when you try to access login button? While in the first example it it initialized when construct ing an object. For some pages such a delayed Evaluation, when part of the page is not loaded yet, can make sense
    – dzieciou
    Aug 24, 2023 at 18:29
  • @dzieciou That is a good point, and does matter if you were to switch pages I guess whilst using the same original page object.
    – Mercfh
    Aug 25, 2023 at 15:30

1 Answer 1

2

In the second case, the locator objects are created every time it is called/used. When the LoginPage object is created, nothing related to the locator is executed.

In the first case, when the LoginPage object is created, the locator object is created and this exact object is re-used.

The best approach will depend on the context of your page, but as long as it is hidden inside the LoginPage, encapsulation is satisfied and you can pick and choose without affecting other parts of the code.

3
  • I suppose the second case matters when you maybe change pages without re-instating the page object? Although I guess the case is uncommon, since most people just use the constructor version.
    – Mercfh
    Aug 25, 2023 at 15:31
  • The locator object can be instantiated regardless of content and effects. What needs to be managed are the objects that are generated when searching using the locator objects. These can be stale if the content changes. Aug 26, 2023 at 12:42
  • @Mercfh If you found the answer satisfactory, could you mark it as accepted, so others will know if answers the problem? Aug 26, 2023 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.