我有一个定义为
this.clientRowName = element(by.id('CLIENT_NAME')); //page object file
我想读取这个元素中的文本,即"ABC",但是执行以下代码:
var client = page.clientRowName.getText();
返回的是一个对象而不是字符串。是否有其他方法可以获取该元素的文本呢?
我有一个定义为
this.clientRowName = element(by.id('CLIENT_NAME')); //page object file
我想读取这个元素中的文本,即"ABC",但是执行以下代码:
var client = page.clientRowName.getText();
返回的是一个对象而不是字符串。是否有其他方法可以获取该元素的文本呢?
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文档页面应该能够解决你的疑问。
另一种解决方案可能是使用 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);
});
根据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
会使代码更容易阅读和调试。
我通常使用 element.getAttribute('value')
.getAttribute('value')
may not work. Yo can also try .getAttribute('textContent')
or .getAttribute('innerText')
- moudrick
.eventually
方法来解析 Promise 并从其中获取值。expect(page.clientRowName.getText()).to.eventually.equal("ABC")
- Chuck van der Linden