守夜人在for循环中执行命令时出现故障

Nightwatch execute command within for loop runs out of order

本文关键字:故障 命令 执行 for 循环 守夜人      更新时间:2023-09-26

我对单元测试还很陌生,但我一直在尝试用Nightwatch创建一个脚本,该脚本可以遍历页面的正文内容,单击每个链接并报告它是否损坏。

我正在尝试制作一个for循环,它遍历正文内容中的每个标记,计算其中包含的"a"标记的数量,然后单击每个标记,但每当我在for循环中使用browser.execute命令时,脚本都会无序执行。

这是我的密码。我加入了几个console.log语句,试图弄清楚发生了什么:

'Click Links' : function(browser) {
browser
  //Count all tags (p/div) in content that aren't links
  .useCss()
  .execute(function() {
    return document.querySelectorAll("div.field-item.even *:not(a)").length;
  },
  function(tags){
    tag_total = tags.value;
    //Loop through every tag in content & check every a tag contained within
    for (var x = 1; x < tag_total+1; x++) {
      console.log("x val before execute: " + x);
      browser.execute(function() {
        return document.querySelectorAll("div.field-item.even *:not(a):nth-child(" + x + ") a").length;
      },
      function(links){
        console.log("x val at start of execute: " + x);
        a_total = links.value;
        for (var y = 1; y < a_total+1; y++) {
          browser.click("div.field-item.even *:not(a):nth-child(" + x + ") a:nth-child(" + y + ")");
          browser.pause(1000);
          //Conditionals for on-site 404/403 links
          browser.execute(function() {
            return document.querySelector("meta[content='Error Document']");
          }, 
          //Grabs url if link is broken
          function(result){
            if (result.value != null) {
              browser.url(function(result) {
                console.log("BROKEN LINK: " + result.value);
              });
            }
          });
          //Go back to previous page
          browser.url(process.argv[2]);
          browser.pause(1000);
        }
        console.log("x val at end of execute: " + x);
      });
    console.log("x val at end of for loop: " + x);
    }
  })
.end()
}

我得到的输出:

 x val before execute: 1
 x val at end of for loop: 1
 x val before execute: 2
 x val at end of for loop: 2
 x val at start of execute: 3
 x val at end of execute: 3
 ERROR: Unable to locate element: "div.field-item.even *:not(a):nth-child(3) a:nth-child(1)" using: css selector

for循环似乎正在运行并跳过整个browser.execute块。循环结束后,browser.execute块输入x,x为无效数字3。

为什么browser.execute命令会导致for循环无序执行,可以采取任何措施来修复它,使其按预期顺序运行吗?

这与Nightwatch无关,而是与Javascript有关。

当您有一个循环并在该循环中调用一个函数时,该函数中使用的变量将通过引用保存。换句话说,任何函数的变量都不会改变。

如果我们看一个简单的例子,它会更容易:

var myFuncs = [];
for (var i = 0; i < 3; i += 1) {
  myFuncs.push(function () {
    console.log('i is', i);
  });
}
myFuncs[0](); // i is 3
myFuncs[1](); // i is 3
myFuncs[2](); // i is 3

这是因为i被保存为函数中的引用。因此,当i在下一次迭代中递增时,引用的值不会改变,但值会改变。

这可以很容易地通过将函数移动到循环之外来解决:

function log (i) {
  return function () {
    console.log(i);
  }
}
var myFuncs = [];
for (var i = 0; i < 3; i += 1) {
  myFuncs.push(log(i));
}
myFuncs[0](); // i is 0
myFuncs[1](); // i is 1
myFuncs[2](); // i is 2

如果你想进一步探索这个概念,你可以看看这个类似的SO答案(具有讽刺意味的是,它有一个非常相似的例子)。