NIghtwatch.js error: "Cannot read propery 'equal' of undefined

NIghtwatch.js error: "Cannot read propery 'equal' of undefined

我正在尝试 运行 一个简单的 Nightwatch.js 登录测试,告诉表单记住登录,然后测试 cookie 以查看布尔值是否存在。每次我尝试 运行 测试时,我都会收到错误:

"Cannot read propery 'equal' of undefined"

client.getCookie() 的回调函数相关联。

任何人都可以帮助我了解如何修复此错误吗?

这是我的代码:

module.exports = {
  'Test "Keep me logged in." ' : function (client) {
    client
      .windowMaximize()
      .url('www.mysite.com')
      .setValue('#login > form > table > tbody > tr:nth-child(1) > td:nth-child(2) > input[type="text"]', 'testuser')
      .setValue('#login > form > table > tbody > tr:nth-child(2) > td:nth-child(2) > input[type="password"]', 'testpass')
      .click('#login > form > table > tbody > tr:nth-child(4) > td > label > input[type="checkbox"]')
      .click('#login > form > table > tbody > tr:nth-child(5) > td > input[type="submit"]')
      .waitForElementVisible('body', 2000);

      client.getCookie('RememberMe', function(result){ 
            this.assert.equal(result.value, 'True');
      });
  }
};

函数是 javascript 中的词法范围,因此它设置了对关键字 this 的新引用。

试试这样的东西:

  client.getCookie('RememberMe', function(result){ 
      this.assert.equal(result.value, 'True');
  }.bind(this))

编辑:

似乎 assertclient 的成员,所以如果框架支持,调用应该类似于

  client.getCookie('RememberMe', function(result){ 
      client.assert.equal(result.value, 'True');
  })

原来Nightwatch.js还不支持这个功能:https://twitter.com/nightwatchjs/status/434603106442432512

根据最新的 Nightwatch 版本,cookie 支持现在是原生的!

查看文档 here。我唯一要注意的是要问 - 你确定你真的要检查字符串值 'True' 吗?或者你更愿意检查一个布尔值,它看起来像这样:

  client.getCookie('RememberMe', function(result){ 
        this.assert.equal(result.value, true);
  });

另一个关于调试的小建议是,要确保您访问的是正确的 cookie,请检查它是否也是 .name

最后,尝试通过删除 waitForElementVisible 之后的分号来链接 getCookie 命令,这样您的代码如下所示:

  .waitForElementVisible('body', 2000)
  .getCookie('RememberMe', function(result){ 
        this.assert.equal(result.value, 'True');
  });

我不是关于 JS 作用域建议的最佳人选,但 看起来 好像 this 的上下文嵌套太多了。如果您仍然遇到问题,请尝试将其替换为 client

运气好!