我们什么时候应该将 .then 与量角器承诺一起使用



我对量角器有很多不稳定的地方,我确信有些事情我不明白。有时我需要在继续之前单击按钮时使用 .then((,有时它没有任何影响,我不应该使用 .then(( 或测试失败。

我想知道在量角器中测试时何时应该使用 .then(( 回调?例:

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

当我使用这种形式的测试(没有 .then(((时,我在浏览器上看到单击按钮没有完成,测试继续以下期望,然后停止。

如果我使用 .then(( 表单,则单击按钮就完成了,测试继续而不会出错。

在其他测试中,单击按钮时我不需要使用 then(( 回调。

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

让-马克

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

那是:

  1. 量角器将控制流中的所有驱动程序命令排队,
  2. 当你需要驱动程序命令的结果时,你应该使用 .then,
  3. 当您不需要驱动程序的结果时,您可以避免 .then 但所有以下说明必须在控制流中排队,否则它们将在队列中的命令之前运行,导致不可预测结果。因此,如果要运行非驱动程序测试命令,则应将其添加到 .then 回调中,或将测试包装到 Promise 中,并在 ControlFlow 中将测试排队。请参阅下面的示例。

这是我的测试在没有 .then 的情况下工作的示例:

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

帮自己一个忙,避免 .then

今天,async/await更适合传递承诺

但简而言之,打开量角器 API 页面 https://www.protractortest.org/#/api,找到您将要使用的方法并查看它返回的内容。如果它说承诺,只需在调用它之前添加await。确保使包装功能async

it('test case 1', async () => {
  await elem.click()
})