在 nightwatch 自定义命令中赋值后变量 returns 未定义

Variable returns undefined after assigning value in nightwatch custom command

正在为守夜人测试编写 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();
};

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

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); 

})

};

我在 Nightwatch 的文档页面中找到了这个 Understanding the Command Queue.

values captured this way also aren't available until the test is running. In a callback, all code directly in the test case function body has already resolved, and the only place any other code will run is in other callbacks. This is important to keep in mind because it can be easy to think this might work:

// incorrect usage of a callback value

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

The problem here is that the setValue() call happens in the main test case function call, before the callback is called when text is still undefined. For setValue() to have the correct value for text, it must be called within, or some time after, the getText() callback:

但是你可以使用你的自定义方法,它会很完美。

customTitle: function () {

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

you: function() {

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