【发布时间】:2020-01-08 17:38:52
【问题描述】:
JS 新手。我有这个功能。首先,它检查缓存中的数据。如果不存在,它会为此数据调用后端并将其保存到缓存中。
function doSomething() {
return getCachedData()
.catch(function() {
return getData()
.then(saveDataToCache);
});
}
我需要测试在第一次和第二次执行方法 doSomething 时调用缓存和后端的次数。这是我的测试:
it('should test', function() {
spyOn(this.service, 'doSomething').andCallThrough();
spyOn(this.service, 'getCachedData').andCallThrough();
spyOn(this.service, 'getData').andCallThrough();
this.service.doSomething();
this.$rootScope.$apply();
expect(this.service.doSomething.callCount).toBe(1);
expect(this.service.getCachedData.callCount).toBe(1);
expect(this.service.getData.callCount).toBe(1);
this.service.doSomething();
this.$rootScope.$apply();
expect(this.service.doSomething.callCount).toBe(2);
expect(this.service.getCachedData.callCount).toBe(2);
expect(this.service.getData.callCount).toBe(1);
});
但是,我收到一条错误消息,指出 getCachedData 和 getData 的调用计数始终为 0,无论是第一次还是第二次。
将 this.$rootScope.$apply(); 更改为 this.$rootScope.$digest(); 并没有改善任何东西。我还手动对其进行了测试,一切似乎都运行良好。
我还注意到,如果我将函数 doSomething 更改如下,那么 getCachedData 的计数是 2 和 2,这是正确的。
function doSomething() {
this.getCachedData();
return getCachedData()
.catch(function() {
return getData()
.then(saveDataToCache);
});
}
【问题讨论】:
标签: javascript angularjs unit-testing jasmine