我正在用nightwatch运行这个测试,我在循环中有一个循环,第一个运行正常,但它无法进入第二个循环。 我写了一个console.log并返回:
Number of links:[object Object]
这是我的代码: 不进入循环2的原因是什么? 提前谢谢。
.execute(
function() {
return document.querySelectorAll('.menuElementsAgregator>li').length
},
function(result) {
total_links = result.value;
console.log("Number of main links:" + total_links);
for (var i = 2; i <= total_links; i++) {
(function (i) {
browser.waitForElementPresent('.menuElementsAgregator', 3000)
.click('.menuElementsAgregator>li:nth-child(' + i + ')>a')
.waitForElementVisible('.menuElementsAgregator>li:nth-child(' + i + ')', 2000)
.execute(
function () {
return document.querySelectorAll('.menuElementsAgregator>li:nth-of-type(' + i + ')>.tsr-nav-second-level .has-sub .clickableTabWithLink').length
},
function(result) {
total_links2 = result.value;
console.log("Number of links:" + total_links2);
for (var j = 2; j <= total_links2 + 1; j++) {
browser.waitUntilElementIsClickable('.menuElementsAgregator>li:nth-child(' + i + ')')
.click('.menuElementsAgregator>li:nth-child(' + i + ')')
.waitForElementPresent('.menuElementsAgregator>li:nth-of-type(' + i + ')>.tsr-nav-second-level>li:nth-of-type(' + j + ').has-sub', 5000)
.click(' .menuElementsAgregator>li:nth-of-type(' + i + ')>.tsr-nav-second-level>li:nth-of-type(' + j + ').has-sub .clickableTabWithLink:first-child')
.pause(1000)
.waitForElementVisible('.games-list', 5000);
}
}
)
})(i);
}
})
答案 0 :(得分:0)
问题是total_links
不是整数而是对象。
尝试替换
console.log("Number of main links:"+ total_links);
与
console.log("Number of main links:", total_links);
这将显示你在total_links中的内容。如果您无法修复,请添加内容为total_links
答案 1 :(得分:0)
这个代码绝对不行,因为你不能在循环中使用回调,你的索引'i'在第二个循环中总是等于'total_links.length'。你可以试试这个:
.execute(
function() {
return document.querySelectorAll('.menuElementsAgregator>li').length
},
function(result) {
total_links = result.value;
console.log("Number of main links:" + total_links);
for (var i = 2; i <= total_links; i++) {
(function(i){ // this is a closure
browser.waitForElementPresent('.menuElementsAgregator', 3000)
.click('.menuElementsAgregator>li:nth-child(' + i + ')>a')
.waitForElementVisible('.menuElementsAgregator>li:nth-child(' + i + ')', 2000)
.execute(
function() {
return document.querySelectorAll('.menuElementsAgregator>li:nth-child(' + i + ')>.tsr-nav-second-level>.has-sub').length
},
function(result2) {
total_links2 = result2.value;
console.log("Number of links:" + total_links2);
for (var j = 0; j <= total_links2; j++) {// i = total_link.length already, before get in to this loop.
browser.waitForElementPresent('.menuElementsAgregator>li:nth-child(' + i + ')>.tsr-nav-second-level>.has-sub:nth(' + j + ')', 3000)
.click('.menuElementsAgregator>li:nth-child(' + i + ')>.tsr-nav-second-level>.has-sub:nth(' + j + ')>a')
.pause(3000)
.waitForElementVisible('.games-list', 5000);
}
}
)
})(i) // close
}
}
)
你应该看看api .perform(),这对这类工作有很大的帮助。它使我的代码更清晰,更易读。 Ps:花一些时间研究关闭。