测试从 AngularJS 中另一个方法的 return 语句调用一个方法的次数

Testing how many times a method was called from another method's return statement in AngularJS

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);
        });
}

创建对象。例如:

system_metrics ={
 cache_calls:0,
 backend_calls:0,
 reset_cache:function(){this.cache_calls=0;},
 reset_backend_calls:function(){this.backend_calls=0;},
 add_cache_call:function(){this.cache_calls++;}
 add_backend_call:function(){this.cache_calls++;}
}

function getCachedData(){
    //add this line
   system_metrics.add_cache_call();
}

function getData(){
    //add this line
   system_metrics.add_backend_call();
}

I need to test how many times cache and backend are called on the first and the second time the method doSomething is executed

function doSomething(){
  if(system_metrics.cache_calls === 1){
     //the first time the method doSomething is executed
  }
  if(system_metrics.cache_calls === 2){
     //the second time the method doSomething is executed
  }
  if(system_metrics.backend_calls === 1){
     //the first time the method doSomething is executed
  }
  if(system_metrics.backend_calls === 2){
     //the second time the method doSomething is executed
  }
}

在执行期间的任何时间..可以说在一天结束时 您现在可以查看 system_metrics.cache_calls 以了解当天的缓存调用总数。如果您从未重置缓存调用

在执行期间的任何时候,您都可以使用 system_metrics.reset_cache_calls

清除缓存调用的次数

如果您的问题是检查缓存被调用了多少次 当 doSomething 第一次或第二次运行时。

如果你的问题是检查后端被调用了多少次 当 doSomething 第一次或第二次运行时。

将以下内容添加到您的 system_metrics do_something_calls add_do_something_call reset_do_something_calladd_do_something_call 添加到您的 do_something function 我想你明白了

通过这种方法,您可以随时随地跟踪任何指标