什么时候应该用量angular器承诺?

量angular器有很多不稳定的情况,我确信有一些我不明白的地方。 有时我需要在继续之前点击button来使用.then(),有时不会有任何影响,我不应该使用.then()或者testing失败。

我想知道什么时候应该在量angular器中testing时使用.then()callback? 例如:

createAccountForm = $('#form-create-account'); submitButton = createAccountForm.$('button[type=submit]'); browser.wait(EC.elementToBeClickable(submitButton), 5000); submitButton.click(); // .then(function(){ <-- uncomment in the .then form // find the confirmation message var message = $('.alert-success'); browser.wait(EC.visibilityOf(message), 5000); log.debug('After visibilityOf'); expect(message.isPresent()).to.be.eventually.true; // }); --> uncomment when in .then form 

当我使用这种forms的testing(没有.then()),我看到在浏览器上点击button没有完成 ,testing继续下面的期望,然后停止。

如果我使用.then()表单,点击button完成 ,并且testing继续没有错误。

在其他testing中,当点击button时,我不需要使用then()callback。

那么,什么时候应该使用.then(),什么时候不使用?

让 – 马克

这个问题的答案可以在这篇文章中find: http : //spin.atomicobject.com/2014/12/17/asynchronous-testing-protractor-angular/

那是 :

  1. 量angular器将所有驱动程序命令排入ControlFlow,
  2. 当你需要驱动程序命令的结果时,你应该使用。然后,
  3. 当你不需要驱动程序的结果,你可以避免。但是,所有下面的指令必须排入ControlFlow中,否则将在队列中的命令之前运行,导致不可预知的结果。 所以,如果你想运行一个非驱动程序testing命令,你应该把它添加到.thencallback中,或者把testing包装到一个Promise中,并将testing排入ControlFlow。 看下面的例子。

这里是我的testing没有工作的一个例子。然后:

 log.debug('test0'); // enqueue the click submitButton.click(); var message = $('.alert-success'); // enqueue the wait for message to be visible browser.wait(EC.visibilityOf(message), 5000); log.debug('test1'); // enqueue a test expect(message.isPresent()).to.be.eventually.true; log.debug('test2'); // a function returning a promise that does an async test (check in MongoDB Collection) var testAccount = function () { var deferred = protractor.promise.defer(); // Verify that an account has been created accountColl.find({}).toArray(function (err, accs) { log.debug('test5'); expect(err).to.not.exist; log.debug('test6'); expect(accs.length).to.equal(1); return deferred.fulfill(); }); return deferred.promise; }; log.debug('test3'); // Enqueue the testAccount function browser.controlFlow().execute(testAccount); log.debug('test4'); 

产出现在是我们所期望的:

 test0 test1 test2 test3 test4 test5 test6