Search code examples
protractore2e-testing

Are getter functions necessary for Protractor element locators


When using PageObjects for Protractor e2e tests, should you use getter functions for the element locator variables instead of having variables?

example:

public loginButton: ElementFinder = $('#login-submit');
public loginUsername: ElementFinder = $('#login-username');

Or should you use a getter function in the Page Object like this:

public get loginButton(): ElementFinder {
  return $('#login-submit');
}

public get loginUsername(): ElementFinder {
  return $('#login-username');
}

Is one approach better than another?


Solution

  • No getters needed, since protractor ElementFinder and ElementArrayFinder objects are lazy - no any searching for this element will be done until you will try to call some methods on them. Actually thats also a reason why you don't need to use await for protractor element search methods:

    const button = $('button') // no await needed, no getter needed
    console.log('Element is not yet tried to be searched on the page')
    await button.click() // now we are sending 2 commands one by one - find element and second - do a click on found element.
    

    http://www.protractortest.org/#/api?view=ElementFinder

    ElementFinder can be used to build a chain of locators that is used to find an element. An ElementFinder does not actually attempt to find the element until an action is called, which means they can be set up in helper files before the page is available.