Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Nightwatch use xpath by default in page object files

All my page objects look something like this:

  elements: {
      header: {
         locateStrategy: 'xpath',
         selector: "//h3[text()='Welcome']"
      },
      loginButton: {
         locateStrategy: 'xpath',
         selector: "//button[text()='Login']"
      },
      forgotPasswordLink: {
         locateStrategy: 'xpath',
         selector: "//a[text()='Forgot Password?']"
      },
      signupButton: {
         locateStrategy: 'xpath',
         selector: "//button[text()='Signup']"
      }

It would be way better if I could just say "use xpath everywhere" - that would all collapse mightily

The docs say that you should be able to set "use_xpath" : true in your "test settings", but I have tried that in all the places I can see in nightwatch.json, and it doesn't have any effect.

(It's not completely clear if they mean that this setting will affect declarations in page object files, in any case: the example only shows it affecting subequent assert calls in the test case).

like image 563
GreenAsJade Avatar asked Mar 22 '16 06:03

GreenAsJade


People also ask

How do I switch from XPath to CSS selector in Nightwatch?

By default, Nightwatch uses CSS selectors for its locator strategy. You can change this behavior for an individual test file by using the methods “useCss()” and “useXpath()”. These allow you to switch back and forth between CSS and XPath selectors.


1 Answers

You can just use a javascript function like this (depending on your favourite way to create objects):

var xSelector = function (selector) {
    return {
        selector: selector,
        locateStrategy: 'xpath'
    }
};

And then use it like so:

elements: {

    xxx: xSelector('//a[text()="Bank Details"]')
    createStepButton: { selector: '#menu-create-item' },
}

Hint: In the sample above the createStepButton is still using the css selector strategy. Consider also creating a cssSelector function for uniform readability of the elements section.

like image 126
profMamba Avatar answered Sep 19 '22 13:09

profMamba