断言在页面对象中不可用?- 无法读取未定义的属性“ok”

Assert not available in page object? - Cannot read property 'ok' of undefined.

本文关键字:未定义 读取 属性 ok 面对 对象 断言      更新时间:2023-09-26

我有一个小型的守夜测试,它正在读取价格并检查该值是否为正数。

    browser.getText ('.price', function(result) {
       var myPrice = Number(result.value.replace('-.','').trim());
       browser.assert.ok(isPositive(myPrice), 'price is a positive number');
    });

如果我直接将其放在测试本身中,这将非常有效,但是当我将其作为函数移动到页面对象文件中时(如下所示):

checkPrice: function (){
    this.expect.element('@price').text.to.be.visible.before(1000);
    this.getText ('@price', function(result) {
       var myPrice = Number(result.value.replace('-.','').trim());
       this.assert.ok(isPositive(myPrice), 'price is a positive number');
    });
}, 

它抛出此错误:"无法读取未定义的属性'ok'"。我尝试使用 assert.equal 来更改我的支票,但它给出了相同的错误,即该属性无法访问。我在这里读到(NIghtwatch.js错误:"无法读取未定义的'等于'属性),assert范围可能存在一些问题,因为它是client的成员,但是如果我使用client而不是 this它将不再看到断言:"无法读取未定义的属性'断言'"。

我也读过this有时使用起来可能很棘手,但我的 JavaScript 编程技能有限,所以从这个角度来看,我可能会错过一些东西。

您能否给我一个建议,为什么这不起作用,我该如何尝试修复它?

当您

输入内部函数的作用域时,this会发生变化,因此您需要保存对它的引用。

checkPrice: function (){
    var _this = this;
    this.expect.element('@price').text.to.be.visible.before(1000);
    this.getText ('@price', function(result) {
       var myPrice = Number(result.value.replace('-.','').trim());
       _this.assert.ok(isPositive(myPrice), 'price is a positive number');
    });
},