var count = 0;
function abc(){
asyncService.getCount(function(response){
count = response.data;
}, function(error){
console.log(error);
});
}
it('check count', function(){
asyncService.getCount.and.returnValue(Promise.resolve(2));
ctrl.abc();
expect(count).toBe(2);
}
我想测试茉莉花的计数值。请帮我解决这个问题。我找不到任何解决方案。 我也嘲笑了这项服务。但它仍然给出计数为 0
使用 $q,您可以使用 $rootScope.$digest((; 自行解决。
it('check count', function(){
asyncService.getCount.and.returnValue($q.resolve(2));
ctrl.abc();
$rootScope.$digest();
expect(count).toBe(2);
}
$q是 Promise 的 AngularJS 包装器。
- 将spyOn与异步服务一起使用。
- 响应变量 计数是在传递给异步服务的回调函数中设置的。该异步服务的返回值似乎 微不足道。因此,您必须使用callFake模拟服务并执行回调。
JSFiddle: Jasmine Async Callback Handling
describe('testing', function(){
it('testing async service', function(){
spyOn(asyncService, 'getCount').and.callFake(function(res, err){
res({data: 2})
})
abc();
expect(count).toBe(2);
})
})
注意:您必须使用 Jasmine 版本 2 或更高版本才能使用上述代码片段。