Search code examples
functionvariablesprotractorgettextpreserve

Protractor: preserve variable outside getText() function


I want to preserve variable outside getText() function, so that I can match it to the values latter in the tests. Example:

Page object file:

this.numberOfAllLines = element(by.id('all_lines'));
this.tableCell = element(by.css('.table_results_lines'));
this.sumOfAllLinesText = element(by.id('sum_lines'));

Spec file:

var numberOfLines = '';
var newNumberOfLines = '';

describe(...
    it(...
        page.numberOfAllLines.getText().then(function(num) {
            numberOfLines = num;
        });

        newNumberOfLines = numberOfLines + 10;

        expect(page.tableCell.getText()).toEqual(newNumberOfLines);

        // doing some clicks

        expect(page.sumOfAllLinesText.getText()).toEqual(newNumberOfLines);
    });
});

This is not answered in How do I return the response from an asynchronous call?.


Solution

  • This piece of code newNumberOfLines = numberOfLines + 10 is async and will execute before even the assignment of numberOfLines = num; happens.

    What you are doing is correct. Having a global variable which hold the value to be compared. But have the assignment code inside the chained promise of getText().

    it(...
            page.numberOfAllLines.getText().then(function(num) {
                numberOfLines = num;
                newNumberOfLines = numberOfLines + 10;
            });  
    
            expect(page.tableCell.getText()).toEqual(newNumberOfLines);