我是 Protractor 新手,想要检查某个元素是否存在于特定页面中。但是当我使用 isDisplayed() 方法或 isElementPresent() 方法时,它返回一个对象而不是 bool 值,
element(by.id('id1')).isPresent().then(async present => {
if (present) {
return true;
} else {
return false;
}
});
请让我知道我在这里做错了什么,我收到以下错误。
AssertionError: expected { Object (flow_, stack_, ...) } to equal true
最佳答案
因为 Protractor API 是异步的,并返回一个 promise ,该 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()
或使用理解/尊重 Promise 的库,例如 jasmine
、chai-正如所 promise 的
。
让我们使用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
一起使用,后者会重新 promise Promise,如下所示:
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
)为promise时,才需要添加eventually
进入断言表达式。而且无论实际值
是否是 promise ,期望值
都不能是 promise 。
另一种替代方法是使用async/await
:
var isPresent = await element(by.id('id1')).isPresent();
exepct(isPresent).to.equal(true);
关于javascript - 检查 Protractor 中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50557653/