Reputation: 559
I've created this custom command for my UI testing in Nightwatch. Here it is in full:
exports.command = function(element, callback) {
var self = this;
try {
this.waitForElementVisible('body', 15000);
console.log("trying..");
window.addEventListener('load', function() {
var selects = document.getElementsByName("select");
console.log(selects);
}, false);
} catch (err) {
console.log("code failed, here's the problem..");
console.log(err);
}
this
.useXpath()
// click dropdowns
.waitForElementVisible(element, 15000)
.click(element)
.useCss()
.waitForElementVisible('option[value="02To0000000L1Hy"]', 15000)
// operation we want all select boxes to perform
.setValue('option[value="02To0000000L1Hy"]', "02To0000000L1Hy")
.useXpath()
.click(element + '/option[4]');
if (typeof callback === "function") {
callback.call(self);
}
return this; // allows the command to be chained.
};
What I'm attempting to do is after I load the page, I want to retrieve all the select boxes and perform the same operation on them. Everything is working correctly except for the code in the try/catch block. I keep getting '[ReferenceError: window is not defined]' and am unsure of how to get past that.
Upvotes: 2
Views: 5255
Reputation: 2553
Hey there @logan_gabriel,
You could also use the execute command which I use when I need to inject a bit of JavaScript on the actual page. As @Steve Hyndig pointed out, your tests are running in the Node instead of on an actual browser window (somewhat confusing, since a window is generally open while tests are being run! Except if using PhantomJS to headless test, of course).
Here is an example custom command which will inject some JavaScript onto the page based on your original post:
exports.command = function(callback) {
var self = this;
this.execute(function getStorage() {
window.addEventListener('load', function() {
let selects = document.getElementsByName('select');
return selects;
}
},
// allows for use of callbacks with custom function
function(result) {
if (typeof callback === 'function') {
callback.call(self, selects);
}
});
// allows command to be chained
return this;
};
Which you could call from your test using the below syntax, including an optional callback to do something with the result:
client
.setAuth(function showSession(result) {
console.log(result);
});
You could opt to just do the work inside of the custom function, but I run into problems due to the async nature of Nightwatch sometimes if I don't nest stuff inside of callbacks, so it's more a safety thing.
Good luck!
Upvotes: 0
Reputation: 1859
The 'window' property is undefined in the global scope because it's being run via command line Node and not in the browser as one might assume initially.
You could try to use this.injectScript from the Nightwatch API but I would suggest using the Selenium Protocol API 'elements'
Upvotes: 3