检查量角器中是否存在元素

时间:2018-05-28 00:14:54

标签: javascript typescript protractor

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

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

请告诉我这里的错误,我收到以下错误。

  

AssertionError:期望{Object(flow_,stack_,...)}等于   真

2 个答案:

答案 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()或使用理解/尊重承诺的库,例如jasminechai-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();
}