简体   繁体   中英

Variable returns undefined after assigning value in nightwatch custom command

Writing a custom command for a nightwatch test.

Why cannot I set the value of the newValidFromText in the following code snippet?

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

Because you asked your variable out of visibility zone

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

})

};

I found this in Nightwatch's Documentation pages 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:

But you can use your custom method for that and it will be like a perfect.

customTitle: function () {

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

you: function() {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM