nightwatch.js return 来自测试外部函数的值

nightwatch.js return value from function outside a test

我无法将测试之外的某些代码移动到需要 return 值的函数中。

这是我测试文件的部分代码

function getCountOfTopics(browser){
    var count;
    browser.getText('@sumTopics',
        function(result){
            count = result.value;
            console.log(result.value);
        }
    );
    return count;
};

module.exports = {    
    
    'Create article' : function(browser){
        var noOfThreadsByInlineCode, noOfThreadsByFunction;
        
        browser.getText('@sumTopics',
            function(result){
                noOfThreadsByInlineCode = result.value;
            }
        );

        noOfThreadsByFunction = getCountOfTopics(browser);

        browser.end();
    }
}

现在,变量noOfThreadsByInlineCode确实得到了DOM中的值,但是变量noOfThreadsByFunction是未定义的。控制台确实打印了正确的值,因此该函数确实从 DOM.

中获取了正确的值

如果能帮助我更新函数,我将不胜感激,这样我就能得到值 returned。

你return变量'count'在回调之外,也就是why.You可以看看这个题目How to return value from an asynchronous callback function?

function getCountOfTopics(browser){
var count;
browser.getText('@sumTopics',
    function(result){
        count = result.value;
        console.log(result.value);
       ///  result.value is available in this callback.
    }
);

你想用 'value' 做什么?

ps:不记得了custom_command.I觉得对这个问题很有帮助。

一个词的答案是异步。代码不会等待你的回调完成,这就是 Node JS 的特点。

如果您迫切需要回调中的内容,您可以将此变量写入文件,然后在代码中的任何位置访问它。这里有一些解决方法:

在文件中保存内容:

var fs = require('fs');

iThrowACallBack(function(response){
  fs.writeFile('youCanSaveData.txt', this.response, function(err) {
    if (err) throw err;
    console.log('Saved!');
    browser.pause(5000);
  });
});

在其他地方访问它:

iAccessThefile(){
   response = fs.readFileSync('youCanSaveData.txt').toString('utf-8');
}

希望对您有所帮助。