Search code examples
functionreturnnightwatch.js

nightwatch.js return value from function outside a test


I have trouble moving certain code outside a test into a function that needs to return a value.

Here is part of my code for the test file

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

Now, the variable noOfThreadsByInlineCode indeed gets the value in the DOM, but the variable noOfThreadsByFunction is undefined. The console does indeed print the correct value, so the function does get the correct value out of the DOM.

I would appreciate help in updating the function so that I do get the value returned.


Solution

  • One word answer is Asynchronisity. The code doesn't wait for your callback to get complete, thats what the feature of Node JS is.

    If you are in desperately in need for the content inside of the callback you can write this variable into a file and then access it anywhere you want inside your code. Here's a bit of a workaround:

    Save something in a file:

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

    Access it somewhere else:

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

    Hope it helps.