在 Jasmine 2.0 中测试 AngularJS 承诺 [英] Testing AngularJS promises in Jasmine 2.0
本文介绍了在 Jasmine 2.0 中测试 AngularJS 承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在努力思考 Jasmine 2.0 和 AngularJS 的承诺.我知道:
I've been trying to wrap my head around Jasmine 2.0 and AngularJS promises. I know that:
- Jasmine 2.0 引入了
done
功能 替换旧的runs
和waitsFor
函数 - AngularJS
$q
承诺在触发摘要循环之前不会解决
- 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
如何使用 Jasmine 2.0 中的新异步语法测试 AngularJS 承诺?
How can I test AngularJS promises using the new async syntax in Jasmine 2.0?
推荐答案
在您调用 promise.resolve()
之后:
- 调用
$timeout.flush()
.这将强制执行摘要循环并传播承诺解析 - 调用
done()
.这告诉 Jasmine 异步测试已经完成
- 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
});
});
这篇关于在 Jasmine 2.0 中测试 AngularJS 承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文