54

I have an element defined as

this.clientRowName = element(by.id('CLIENT_NAME')); //page object file

I want to read the text in this element which is "ABC" but doing: var client = page.clientRowName.getText();

returns an object instead of a string. Is there any other way that I can get the text for the element

Roopali Bansal
  • 673
  • 2
  • 7
  • 19

4 Answers4

110

getText() returns a promise, you need to resolve it:

page.clientRowName.getText().then(function (text) {
    console.log(text);
});

Or, if you just want to assert the text, let expect() resolve the promise for you:

expect(page.clientRowName.getText()).toEqual("ABC");

Promises and the Control Flow documentation page should clear things up.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 2
    If you are using Chai expectations, it has a `.eventually` method to resolve a promise and get the value from inside it. `expect(page.clientRowName.getText()).to.eventually.equal("ABC")` – Chuck van der Linden Aug 23 '16 at 22:44
  • hi everyone, can I use getText function in toEqual() or toBe() ? like that : *expect(element.getText()).toEqual(element2.getText())* – AquariusPotter Jun 30 '20 at 02:03
4

Another solution may be to use async/await.

class Page {
  constructor() {
    this.clientRowName = $('#CLIENT_NAME');
  }
}

/****************/

it('should console.log client name', async () => {
  const client = await Page.clientRowName.getText();
  console.log(client);
});
robdonn
  • 250
  • 3
  • 11
0

I usually used element.getAttribute('value')

ji-ruh
  • 725
  • 1
  • 7
  • 24
  • `.getAttribute('value')` may not work. Yo can also try `.getAttribute('textContent')` or `.getAttribute('innerText')` – moudrick May 30 '20 at 01:43
0

If you're in 2021, you will want to read this answer

according to protractors documentation, .getText() returns a promise.

The best way to handle a promise, as of 2021, is to use async/await keywords. This will make Protractor 'freeze' and wait, until the promise is resolved before running the next command

it('test case 1', async () => {
  let text = await page.clientRowName.getText();
  console.log(text);
})

.then() can also be used, but using async/await will make your code a lot more readable and easier to debug.

Sergey Pleshakov
  • 7,964
  • 2
  • 17
  • 40