我已经在Nightwatch中为我的UI测试创建了这个自定义命令。这是完整的:
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.
};
我尝试做的是在加载页面后,我想检索所有选择框并对它们执行相同的操作。除了try / catch块中的代码之外,一切都正常工作。我一直在' [ReferenceError:窗口未定义]'我不确定如何克服这个问题。
答案 0 :(得分:4)
“window”属性在全局范围内未定义,因为它是通过命令行节点运行的,而不是最初可能假设的浏览器。
您可以尝试使用Nightwatch API中的this.injectScript,但我建议使用Selenium Protocol API 'elements'
答案 1 :(得分:0)
嘿那里@logan_gabriel,
您还可以使用我需要在实际页面上注入一些JavaScript时使用的execute命令。正如@Steve Hyndig指出的那样,你的测试是在Node中运行而不是在实际的浏览器窗口上运行(有点令人困惑,因为在运行测试时窗口通常是打开的!当然,除非使用PhantomJS进行无头测试)。 / p>
这是一个示例自定义命令,它将根据您的原始帖子将一些JavaScript注入页面:
git rm --cached ParentFolder/myfile.h
git add parentfolder/myfile.h
您可以使用以下语法从测试中调用,包括可选回调以对结果执行某些操作:
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;
};
你可以选择只做自定义函数内部的工作,但是由于Nightwatch的异步特性,我遇到了问题,如果我不在回调中嵌入东西,那么它更安全。
祝你好运!