![](/img/trans.png)
[英]Angular.js promise not resolving when unit testing service with karma
[英]Unit Testing promise in service in angular js
我正在尝试对以下功能进行单元测试:
Service.test = function(id) { return this.getDetails(id).then(function (details){ return "name"; }); };
到目前为止,我已经亲自尝试过并完成以下操作:
describe( 'TempServ', function() { var TempSer, $httpBackend, $q, CapabilityService; beforeEach(inject(function(_TempServ_, _$httpBackend_, _$q_, _CapabilityService_) { TempServ = _TempServ_; $q = _$q_; $httpBackend = _$httpBackend_; CapabilityService = _CapabilityService_; })); it(" should be in Pending state",function() { spyOn(TemplateService, 'getDetails').and.callThrough(); console.log(TemplateService.test()); }); });
我想要一些可以模拟getDetails的东西,我可以返回我想要的东西,而不是真正返回的东西,并测试功能是否可以完全正常工作。 仅要嘲笑getDetails!
spyOn(TemplateService, 'getDetails').and.callThrough();
该行将在间谍上下文中执行getDetails的实际实现。 您可以使用类似
spyOn(TemplateService, 'getDetails').and.returnValue(true)
代替。 如果要测试回调中发生的情况,通常需要通过$ scope。$ apply();手动触发摘要循环更新。
尝试做这样的事情
spyOn(TemplateService, 'getDetails').and.returnValue($q.when('mockDetails'));
$rootScope.$digest();
这将使您可以进行如下测试:
it('should be in pending state', function(done) {
spyOn(TemplateService, 'getDetails').and.returnValue($q.when('mockDetails'));
TemplateService.test().then(function(result) {
expect(result).toBe('name'); // this could also be a value computed with "mockDetails"
done();
});
$rootScope.$digest();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.