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

4

6

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).

Pam answered 22/3, 2016 at 6:53 Comment(0)
K
4

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.

Kickoff answered 13/4, 2016 at 0:2 Comment(1)
I'm having the same issue. I would venture out and say that there's a bug in nightwatch.js. Would anyone from the nightwatch team care to comment? my test suite is growing and having this: locateStrategy: 'xpath', all over my code is not fun.Clarke
A
3

Try to set:

"use_xpath": true

in nightwatch.conf.js file, not nightwatch.json

Worked for me :)

Aston answered 15/1, 2020 at 10:56 Comment(0)
B
1

Perhaps it'll help someone.

Try to set:

"use_xpath": true

in your nightwatch.json

Butterbur answered 19/2, 2019 at 15:27 Comment(0)
J
0

To get around this you can loop over your elements and set any given locate strategy for each element, like this:

var pageObject = {
    url: 'https://google.com',
    elements: {
        myFirstElement: {
            selector: "//div[@class='my-first-el']"
        },
        mySecondElement: {
            selector: "//div[@class='my-seconds-el']"
        }
    }
};

for (var el in pageObject.elements){
    pageObject.elements[el]["locateStrategy"] = "xpath";
}
module.exports = pageObject;
Juba answered 27/3, 2018 at 13:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.