Friday 1 January 2016

Save text from an element to a variable to reuse later


This post is my first post and covers something that I needed to solve the first day I started using Protractor.

Take this bit of HTML code below. Perhaps I want to get the value inside the SPAN to store for reuse.

<html>
    <head>
        <title>Example Page</title>
    </head>

    <body>
        <span id='name'>Ferris Beuller</span>
    </body>
</html>

My first attempt resulted in something like this.


var reusuableVariable = null;
reusuableVariable = pages.dashboard.greeting.getText();
console.log(reusuableVariable);

That did not work. I ended up with something like this (partial extract); 
{ ptor_: 
   { controlFlow: [Function],
     schedule: [Function],
     getSession: [Function],
     getCapabilities: [Function],
     quit: [Function],
     actions: [Function],

     executeScript: [Function], ...

I knew enough to tell myself that looks like an object being printed out... So off to Stackoverflow.
It didn't take too long to find a post which solved my problem.

var reusuableVariable = null;

element(by.id('name')).getText().then(function(text) {
    console.log('Getting the text');
    reusuableVariable = text;  
});
console.log(reusuableVariable);

This didn't seem to work. The console would output:
null
Getting the text

You may notice that the first thing that is output to the console is null. 

Perhaps you expected 'Getting the text' first, if so remember that Protractor runs on Node.Js and is asynchronous.

Therefore the element(by.id('name')).getText() returns a promise then execution continues to console.log(reuseableVariable); and as the promise has not been fulfilled yet the variable is still set to null.

Using Protractor we do know that the promises will be managed and processed in order. So if we make use of this we can reuse variables inside callbacks later in the script. In these scripts the callback is the argument given to the .then function which is executed when Protractor locates the element.

var reusuableVariable = null;

element(by.id('name')).getText().then(function(text) {

    console.log('Getting the text');
    reusuableVariable = text;
});

element(by.binding('vm.name')).getText().then(function(text) {

    console.log('Re-using the text')
    console.log(reusuableVariable);
});


Output
Getting the text
Re-using the text
Ferris Beuller

You can extend this further by reusing variables between jasmine describe and it functions. Just remember to scope your variable declaration appropriately so it can be seen in the places you want to reuse it.




No comments:

Post a Comment