我是量角器的新手,想要检查特定页面中是否存在元素。但是当我使用isDisplayed()方法或isElementPresent()方法时,它返回一个Object而不是Boolean,
element(by.id('id1')).isPresent().then(async present => {
if (present) {
return true;
} else {
return false;
}
});
请告诉我这里的错误,我收到以下错误。
AssertionError:期望{Object(flow_,stack_,...)}等于 真
答案 0 :(得分:3)
因为protractor API是Async并返回一个promise,它在异步执行完成时保存最终值。
var isPresent = element(by.id('id1')).isPresent()
// isPresent is a promise, promise is a javascript object, not a boolean value
// only when the async exection done, the isPresent can be assigned and
// hold the boolean value inside.
//使用promise的最终值,您可以使用then()
或使用理解/尊重承诺的库,例如jasmine
,chai-as-promised
。
让我们使用chai作为断言api来检查isPresent
:
var chai = require('chai'),
expect = chai.expect;
var isPresent = element(by.id('id1')).isPresent();
// because chai don't understand/respect promise, so we can't do as following,
// otherwise will get your error: expected { Object (flow_, stack_, ...) } to equal true
exepct(isPresent).to.equal(true)
// we have to consume the promise in then():
isPresent.then(function(present) { // the `present` here is a boolean value
expect(present).to.equal(true);
});
替代方式我们可以将chai
与重复承诺的chai-as-promised
一起使用,如下所示:
var chai = require('chai'),
chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised );
expect = chai.expect;
var isPresent = element(by.id('id1')).isPresent();
expect(isPresent).to.eventually.equal(true);
注意:仅当Actual Value
,这里是isPresent
是承诺时,您需要将eventually
添加到断言表达式中。无论Actual Value
是否承诺,Expect Value
都不能成为承诺。
另一种替代方法是使用async/await
:
var isPresent = await element(by.id('id1')).isPresent();
exepct(isPresent).to.equal(true);
答案 1 :(得分:0)
const buttonsByClassName = ['tools-menu-button', 'view-ds'];
for (let className of buttonsByClassName) {
const btn = element(by.className(className));
const btnIsPresent = await btn.isPresent();
console.log(`element(by.className(${className}))`, btnIsPresent);
expect(btnIsPresent).toBeTruthy();
}