0

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.

2 Answers2

0

You return variable 'count' outside the callback,that is why.You can take a look this topic 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.
    }
);

What do you want to do with the 'value'?

ps:do not remember custom_command.I think it is very helpful for this issue.

Community
  • 1
  • 1
Bao Tran
  • 618
  • 4
  • 15
0

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.

Vishu
  • 338
  • 1
  • 10