Phil
Phil

Reputation: 349

Protractor JavaScipt function call returns null

I'm trying to call my function from it() but I always get return value of null. I thought my function assigns the value to the return variable back to the caller.

file: "helperDropDownBx.js"

module.exports = function() {
  function myFunctionTest() {
    var reTxt = null;
    try {
      browser.wait(EC.visibilityOf(id_dropDownValue), 30000);
      id_dropDownValue.getAttribute("value").then(function(text) {
        retTxt = text;
      });
    } catch(err) {
      throw new Error(err.message);
    }
    return retTxt;
  }
        
  return{
    myFunctionTest : myFunctionTest
  }
}

file: "TestHelpers.js"

const myHelper = require("../pages/helpers/helperDropDownBx.js");
describe("[Test Helpers]", function(){
    var myHelperObj = new myHelper();

    it('testing Helpers', function() {        
        try{
            //attempt#1, but not working
            var retVal = myHelperObj.myFunctionTest();
            retVal.then(function (value){
               console.log(value);
            )};

            //attempt#2, but not working
             myHelperObj.myFunctionTest().then(function(value){
               console.log(value);
            )};
       }catch(err){
           throw new Error(err.message);
       }
    });
});

both of my attempts above, always return null

Upvotes: 1

Views: 88

Answers (1)

Sergey Pleshakov
Sergey Pleshakov

Reputation: 8948

file: "helperDropDownBx.js"

module.exports = {
  myFunctionTest: async function () {
    // this is a bad practice to start a function with wait
    // all wait should be handled after you complete an action and not before
    await browser.wait(EC.visibilityOf(id_dropDownValue), 30000); 
    return id_dropDownValue.getAttribute("value")
  }
}

file: "TestHelpers.js"

const myHelper = require("../pages/helpers/helperDropDownBx.js");
describe("[Test Helpers]", function(){

  it('testing Helpers', async function() {        
    var value = await myHelper.myFunctionTest();
    console.log(value)
  });
});

if you still curious what you needed to do with .then() to make it work, then something like this

module.exports = {
  myFunctionTest: function() {
    return browser.wait(EC.visibilityOf(id_dropDownValue), 30000)
      .then(() => {
        return id_dropDownValue.getAttribute("value")
          .then(function(text) {
            return text;
          })
      })
  }
}

Looks like hell to me :)

Upvotes: 1

Related Questions