[英]Jasmine async test using promises
我正在使用角度承诺进行一些Jasmine测试,并且有一个与计时有关的问题。 在Angular中找到了基于单元测试基于承诺的代码的答案,但需要对其工作方式进行澄清。 鉴于then
方法始终以异步方式处理,如何保证以下测试能够通过。 是否存在expect
将在被执行的then
块之前运行并在分配值之前运行期望的风险。 或者...摘要周期是否保证将在预期运行之前分配值。 意思是,摘要循环将有效地像阻塞调用一样,该阻塞调用保证在允许代码继续执行之前,所有的promise均已解决。
function someService(){
var deferred = $q.defer();
deferred.resolve(myObj);
return deferred.promise;
}
it ('testing promise', function() {
var res;
var res2;
someService().then(function(obj){
res = "test";
});
someService().then(function(obj){
res2 = "test2";
});
$rootScope.$apply();
expect(res).toBe('test');
expect(res2).toBe('test2');
});
摘要循环实际上将像阻塞调用一样工作,以确保在允许继续执行代码之前,所有诺言都已得到解决。
是的,尽管更准确地说,它将保证已解决的诺言的成功回调将运行。
虽然Michal的答案指出了正确的想法,但这里的关键是在相关范围上调用了$apply()
。 这是Angular文档中的示例:
it('should simulate promise', inject(function($q, $rootScope) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue;
promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toBeUndefined();
// Simulate resolving of promise
deferred.resolve(123);
// Note that the 'then' function does not get called synchronously.
// This is because we want the promise API to always be async, whether or not
// it got called synchronously or asynchronously.
expect(resolvedValue).toBeUndefined();
// Propagate promise resolution to 'then' functions using $apply().
$rootScope.$apply();
expect(resolvedValue).toEqual(123);
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.