在nightwatch自定义命令中指定值后,变量返回undefined

时间:2017-05-03 17:48:27

标签: javascript nightwatch.js

为夜班测试编写custom command

为什么我无法在以下代码段中设置newValidFromText的值?

exports.command = function () {

var newValidFromText; //Want to set value to this variable

var browser= this;
browser
    .useCss()
    .perform(function() {

        //Setting the value to the variable 'newValidFromText'
        newValidFromText = "June 1, 2017 "

        //Testing the value set - console prints "June 1, 2017"
        console.log( "newValidFromText now is: "+ newValidFromText );
    })

    .waitForElementVisible('input[id*="SubscriptionStart"]')

    //Test for correct value - getting validFromText = undefined
    .verify.valueContains('input[id*="SubscriptionStart"]', validFromText) 
 return browser.useCss();
};

3 个答案:

答案 0 :(得分:1)

因为您要求变量超出可见区域

exports.command = function () {

var newValidFromText; //Want to set value to this variable

var browser= this;
 browser
.useCss()
.perform(function() {

    //Setting the value to the variable 'newValidFromText'
    newValidFromText = "June 1, 2017 "

    //Testing the value set - console prints "June 1, 2017"
    console.log( "newValidFromText now is: "+ newValidFromText );

this.waitForElementVisible('input[id*="SubscriptionStart"]') 

    .verify.valueContains('input[id*="SubscriptionStart"]', validFromText); 

})

};

答案 1 :(得分:1)

我在Nightwatch的文档页面Understanding the Command Queue.

中找到了这个
  以这种方式捕获的值在测试之前也是不可用的   运行。在回调中,所有代码都直接在测试用例函数中   body已经解决,并且唯一的地方将运行任何其他代码   在其他回调中。这一点很重要,因为它   可以很容易地认为这可能有用:

// incorrect usage of a callback value

var text;
browser
  .getValue('#input', function (result) {
    text = result.value;
  })
  .setValue('#output', text); // WRONG: text is undefined
  

这里的问题是setValue()调用发生在主测试中   case函数调用,在文本静止时调用回调之前   未定义。要使setValue()具有正确的文本值,它必须   在getText()回调函数内或之后调用:

答案 2 :(得分:0)

但你可以使用自定义方法,它就像一个完美的。

customTitle: function () {

var application = this.waitForElementPresent('@selector')
....do something;
return application;
},

you: function() {

 ...code
 .customTitle();
 return you;
 };