Page object command callbacks using element references do not use API context
See original GitHub issueNote: this was originally mentioned in #1043 but I figured it deserved its own, independent issue.
Callbacks in page object element commands (those referencing an ‘@’-prefixed element):
https://github.com/nightwatchjs/nightwatch/blob/v0.9.5/lib/page-object/command-wrapper.js#L74
have their callbacks wrapped and re-called with a different context (the Nightwatch object) than normal callbacks:
https://github.com/nightwatchjs/nightwatch/blob/v0.9.5/lib/page-object/command-wrapper.js#L97
Example (using sample from http://nightwatchjs.org/guide#defining-elements ):
module.exports = {
'Test': function (client) {
function callback () {
console.log('is client: ' + (this === client) + '; ctor: ' + this.constructor.name);
}
var google = client.page.google();
google.navigate()
.click('@searchBar', callback) // (1) page element
.click('input[type=text]', callback) // (2) page selector
.api.click('input[type=text]', callback) // (3) client/api selector
client.end();
}
};
Output:
is client: false; ctor: Nightwatch // (1)
is client: true; ctor: Object // (2)
is client: true; ctor: Object // (3)
Expected:
a) Context of element command to be consistent and be client/api.
or
b) However, I think it would be more appropriate for the context to be the page instance in the case where the commands are being called from a page object ((1), (2)). That context would allow it to retain access to page-specific commands while also having access to client/api through the api property:
function callback () {
console.log(this === google); // true
console.log(this.api === client); // true
}
Compatibility:
Changing the context like this is a breaking change that could affect existing projects if they’re already depending on the Nightwatch context now. You might need a compatibility flag or whatever it is you do to handle this kind of situation to allow for backwards compatibility.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:1
- Comments:6 (2 by maintainers)

Top Related StackOverflow Question
Hey @weixiaobo88,
Thanks for being thorough with your information 😸 !
Your problem is in your nightwatch call. In your last argument you specify the test location of
./test/e2ewhich also includes the folder where your page object is defined. Because the page object is defined in a JS file, its being picked up by the test loader and run as a test. This is where your error is coming from, not the actualgoogle.test.jstest.In your nightwatch.json file, you specify a correct
src_foldersvalue of"test/e2e/tests/". This will correctly point to just your test and ignore the page object JS in the run. Ditching the./test/e2efrom your call to nightwatch should fix the problem for you.So what is the solution for this? Why can I not use @photos inside certain callbacks? I notice It doesn’t work with
'.elements'or inside'.moveToElement'functions/page/photos_page.js