Protractor:element.getText() 返回的是一个对象而不是字符串。

54

我有一个定义为

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

我想读取这个元素中的文本,即"ABC",但是执行以下代码:

var client = page.clientRowName.getText();

返回的是一个对象而不是字符串。是否有其他方法可以获取该元素的文本呢?

4个回答

110

getText()方法返回一个 Promise,你需要解析(resolve)它:

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

或者,如果你只想断言文本内容,可以让expect()为你解决 Promise:

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

Promises and the Control Flow文档页面应该能够解决你的疑问。


2
如果您正在使用 Chai expectations,它有一个 .eventually 方法来解析 Promise 并从其中获取值。expect(page.clientRowName.getText()).to.eventually.equal("ABC") - Chuck van der Linden
大家好,我能在 toEqual() 或者 toBe() 中使用 getText 函数吗?就像这样:expect(element.getText()).toEqual(element2.getText()) - AquariusPotter

4

另一种解决方案可能是使用 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);
});

0

如果你在2021年,你一定会想看这个答案

根据Protractor的文档,.getText()返回一个Promise。

截至2021年,处理Promise最好的方法是使用async/await关键字。这将使Protractor“冻结”并等待,直到Promise解决后再运行下一个命令。

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

.then() 可以使用,但是使用 async/await 会使代码更容易阅读和调试。


0

我通常使用 element.getAttribute('value')


.getAttribute('value') may not work. Yo can also try .getAttribute('textContent') or .getAttribute('innerText') - moudrick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接