'Variable scope in protractor

I am running protractor and jasmine to run unit tests.

I need to know the build version of my web app in order to execute different tests.

I have declared a variable to store this version value.

var version ='';

I am getting the version number by using the following code.

menuObject.modaltext.getText().then(function(text) {
            version = text.slice(79,86);
            console.log(version);
            browser.driver.sleep(7000);
});

The version number is acquired correctly and is consoled properly.

But when i use this version outside of this .then function, its value becomes undefined and I am unable to check for any conditions using that variable.

How can i access the version number so that I use it to control the flow of the tests.

![version variable is highlighted, I am unable to access the version inside the if cases]

enter image description here



Solution 1:[1]

Try changing var to let. This allows to access your version inside your specs.

describe('Nodeprojectpart2Component', () => {
    let version = '';
    beforeEach(() => {
        version = '1.0';
      });

    it('test', () => {
      console.log( 'version' + version);
    });

  });

Issue with your code - Your are retrieving the value of version inside an asynchronous/callback function. Now before your function executes, your console is executed and prints undefined. I am not sure why would you like to define code outside specs. But if you still want to, you shall have the retrieval logic right after you define it in desribe block, something like -

describe('Nodeprojectpart2Component', () => {
        let version = '';
        version = //logic to find the version here itself
        ....

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1