测试AngularJS承诺在茉莉花2.0 [英] Testing AngularJS promises in Jasmine 2.0
本文介绍了测试AngularJS承诺在茉莉花2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在试图环绕茉莉花2.0和AngularJS承诺我的头。我知道:
I've been trying to wrap my head around Jasmine 2.0 and AngularJS promises. I know that:
- Jasmine 2.0 introduced the
done
function to replace the oldruns
andwaitsFor
functions - AngularJS
$q
promises will not resolve until a digest cycle is triggered
如何测试使用新的异步语法茉莉花2.0 AngularJS的承诺?
How can I test AngularJS promises using the new async syntax in Jasmine 2.0?
推荐答案
您的来电后, promise.resolve()
:
-
$ timeout.flush()
一>。这将迫使摘要周期和传播的承诺分辨率 - 呼叫
()完成
。这告诉茉莉异步测试完成
- Call
$timeout.flush()
. This will force a digest cycle and propagate the promise resolution - Call
done()
. This tells Jasmine the async tests have completed
下面是一个例子( 在Plunker 演示):
Here's an example (Demo on Plunker):
describe('AngularJS promises and Jasmine 2.0', function() {
var $q, $timeout;
beforeEach(inject(function(_$q_, _$timeout_) {
// Set `$q` and `$timeout` before tests run
$q = _$q_;
$timeout = _$timeout_;
}));
// Putting `done` as argument allows async testing
it('Demonstrates asynchronous testing', function(done) {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('I told you I would come!');
}, 1000); // This won't actually wait for 1 second.
// `$timeout.flush()` will force it to execute.
deferred.promise.then(function(value) {
// Tests set within `then` function of promise
expect(value).toBe('I told you I would come!');
})
// IMPORTANT: `done` must be called after promise is resolved
.finally(done);
$timeout.flush(); // Force digest cycle to resolve promises
});
});
这篇关于测试AngularJS承诺在茉莉花2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文