在量角器中解决黄瓜的承诺

时间:2018-04-19 15:45:07

标签: javascript angularjs protractor cucumber

我正在尝试使用量角器编写黄瓜场景并使用assert来验证dom中的元素是否包含它们应该包含的内容。这是我到目前为止所尝试的:

Then('the title should be {string}', function(expectedTitle) {
  const browserTitle=browser.getTitle().then(function(title) {
    return title;
  })
  assert.equal(browserTitle, expectedTitle);
});

这就是我所得到的。我认为这是未能正确解决的承诺。

1) Scenario: Visit Homepage # e2e/features/homepage.feature:6
   ✔ Given I browse to "/" # e2e/definitions/navsteps.js:4
   ✖ Then the title should be "bla bla bla" # e2e/definitions/navsteps.js:9
       AssertionError [ERR_ASSERTION]: ManagedPromise {
         flow_:
          ControlFlow {
            propagateUnhandledRejections_: true,
            activeQueue_:
             TaskQueue {
            == 'bla bla bla'
           at World.<anonymous> (/Users/arnab/work/bla-bla/e2e/definitions/navsteps.js:13:10)
   ✔ After # node_modules/protractor-cucumber-framework/lib/resultsCapturer.js:25

1 scenario (1 failed)
2 steps (1 failed, 1 passed)

使用then解决承诺应该不够吗?我错过了什么?我查看了this SO questionthe accepted solution以同样的方式解析了标题。

1 个答案:

答案 0 :(得分:1)

Then('the title should be {string}', function(expectedTitle) {

  const browserTitle=browser.getTitle().then(function(title) {
    return title;
  })
  // actually, browserTitle here is still a promise, not the string of browser title
  // because Promise.then() will build a new promise

  assert.equal(browserTitle, expectedTitle);
  // Because the `assert` you used can't understand/respect promise, 
  // so it won't wait the promise (browserTitle) resolved/rejected before
  // compare to `expectedTitle`.

  // To fix your problem, you can use assertion library which respect promise,
  // like `chai` and `chai-as-promised`
});

使用chaichai-as-promised

的示例
// protractor conf.js
onPrepare: function(){
  var chai = require('chai'),
      expect = chai.expect;

  chai.use(require('chai-as-promised'));
  global.expect = chai.expect;  
}
// add above code in `onPrepare` of protractor conf.js

Then('the title should be {string}', function(expectedTitle) {

  const browserTitle = browser.getTitle();

  return expect(browserTitle).to.eventually.equal(expectedTitle);
  // expect(A).to.eventually.xxx(B)
  // Only when A is promise-like object, you can use `eventually`.

  // Otherwise, you can't.
  return browser.getTitle().then(function(title){
     expect(title).to.equal(expectedTitle);
     // title at here is not a promise-like object
     // you can't use `eventually`
  });

});

对于黄瓜步骤定义,它需要返回类似promise的对象或调用回调。否则,当自己开始执行时,下一步将不会等待上一步完成。

Then('xxxx', function(){

  return a promise-like objct
});

Then('xxxx', function(callback){


  callback(); //it must be the last step of the function
});