首页 > 解决方案 > 检查量角器中是否存在元素

问题描述

我是量角器的新手,想检查特定页面中是否存在元素。但是当我使用 isDisplayed() 方法或 isElementPresent() 方法时,它返回一个对象而不是布尔值,

element(by.id('id1')).isPresent().then(async present => {
              if (present) {
                  return true;
              } else {
                  return false;
              }
          });

请让我知道我在这里做错了什么,我收到以下错误。

AssertionError: 预期 { Object (flow_, stack_, ...) } 等于 true

标签: javascripttypescriptprotractor

解决方案


因为量角器 API 是异步的,并且在异步执行完成时返回一个包含最终值的承诺。

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-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与 which repent promise 一起使用的替代方式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, 这里是isPresentispromise 时,才需要添加eventually到断言表达式中。而无论Actual Value是不是承诺,Expect Value都不能成为承诺。

另一种替代方法是使用async/await

var isPresent = await element(by.id('id1')).isPresent();
exepct(isPresent).to.equal(true);

推荐阅读