-2

Here's the deal - getText() method returns promise, it's okay in case when you are using it inside of expect(), but when I'm trying to return string value of an element into variable, it returns promise. Here is the code:

var text = mainPage.counter().getText().then((text) => {
        return text;
})

Is there any way to get the text and assign it to a variable?

Abdul
  • 2,002
  • 7
  • 31
  • 65
Byte Surfer
  • 33
  • 2
  • 5

6 Answers6

2

A promise’s value could be resolved only by another promise, you should probably check this post : How do I return the response from an asynchronous call?

so in your case -

 var data = mainPage.counter().getText().then((text) => {
    return text;
   });
 // at this point data is still a managed promise!
 data.then((text) => {
   console.log(text); // your text would be printed!
  });
Community
  • 1
  • 1
Ram Pasala
  • 4,931
  • 3
  • 16
  • 26
  • Code duplicate for promises handling. better follow: var data = mainPage.counter().getText(); data.then((text) => { console.log(text); // your text would be printed! }); – Optimworks Aug 08 '16 at 12:19
  • yes this could also be done, just wanted to stick to the qn though! – Ram Pasala Aug 08 '16 at 12:21
0

Declare variable 'string' at global level and store text value to it inside then(function(){})

Code snippet:
   var string; 
   mainPage.counter().getText().then((text) => {
      string=text;
    });
Optimworks
  • 2,537
  • 17
  • 20
0

Let the variable be a promise, resolve when needed:

var text = mainPage.counter().getText();
// some other code

text.then(function (realTextValue) {
    console.log(realTextValue);
});
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

You can use await and make your it block async.

// I'm using const x = await this.getElementText();

    public async getElementText(elem) {
         return elem.getText().then((text) => {
              return text;
          })
    }
0

Late to the party but I had a similar problem trying to get the text from an element and resolved it like this:

var yourVar = '';
element.getText()
     .then(function(text){
         yourVar = text;
         return yourVar;
});
Joaquin Casco
  • 704
  • 5
  • 14
-1

Try this one:

var text = function(){ return mainPage.counter().getText(); };