如何在指令单元测试中模拟资源



我有一个指令,它调用资源,然后处理响应。我的单元测试总是给我"意外请求GET"。我尝试过一些方法来嘲笑这些资源,但没有成功。如果有人知道怎么做,提前非常感谢!

;(function(app){
  'use strict';
  app.directive('reportBalance', ['feelingsResource', function(feelingsResource){
    function reportBalanceDirective(scope){
      buildTotalObject(scope);
      getFeelingsTotals(scope);
    }
    function buildTotalObject(scope){
      scope.total = {
        'sad' : 0,
        'happy' : 0,
        getFeelingsTotal : function(){
          return this.sad + this.happy;
        },
        getPercentage: function(feeling) {
          if(!this.getFeelingsTotal())
            return '0%';
          return (this[feeling] / this.getFeelingsTotal() * 100) + '%';
        }
      };
    }
    function getFeelingsTotals(scope){
      feelingsResource.totals({}, function(response){
        onGetFeelingsTotalSuccess(scope, response);
      });
    }
    function onGetFeelingsTotalSuccess(scope, response){
      scope.total.sad = Math.abs(response.totals.sad);
      scope.total.happy = Math.abs(response.totals.happy);
    }
    return {
      restrict: 'E',
      scope: {},
      templateUrl: 'app/commons/directives/reports/balance/report-balance-template.html',
      link: reportBalanceDirective
    };
  }]);
})(app);

这是规格:

describe("Report Balance Directive:", function() {
  var scope, element;
  beforeEach(function(){
    module('app');
    module('templates');
  });
  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    element = angular.element('<report-balance></report-balance>');
    $compile(element)(scope);
    scope.$digest();
  }));
  it('should contains a "totals" in its scope', function(){
    expect(scope.totals).toBeDefined();
  });
});

错误:

Error: Unexpected request: GET http://localhost:3000/feelings/totals

好吧,您只需要使用mock$httpBackend,就像任何其他涉及$http请求的单元测试一样:

$httpBackend.whenGET('/feelings/totals').respond(someData);

或者,由于您委托给一个服务来进行$http查询,因此模拟服务本身:

spyOn(feelingsResource, 'totals').andCallFake(function(config, callback) {
    callback(someData);
});

最新更新