我正在尝试对以下功能进行单元测试:
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被嘲笑!
答案 0 :(得分:1)
spyOn(TemplateService, 'getDetails').and.callThrough();
此行将在间谍上下文中执行getDetails的实际实现。你可以使用像
这样的东西spyOn(TemplateService, 'getDetails').and.returnValue(true)
代替。如果要测试回调内部发生的情况,通常需要通过$ scope手动触发摘要周期更新。$ apply();
答案 1 :(得分:1)
尝试做这样的事情
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();
});