0

我有一个指令调用资源,然后操纵响应。 我的单元测试总是给我“意外的请求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 

回答

0

好吧,你只需要使用mock $httpBackend,如涉及$ HTTP请求的任何其他单元测试:

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

或者,因为你委托给一个服务,使该$ HTTP查询,嘲笑服务本身:

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

我不知道是不是因为我的后台是另一台服务器端口(后端-p 3000和前端-p 9000 ),但它仍然在做一个意外的请求...谢谢无论如何@ jb-nizet 即使使用绝对url,不起作用: $ httpBackend.whenGET('http:// localhost:3000/feelings/totals' ).respond(someData); –

+1

JB是正确的,你应该注入$ httpBackend,使用whenGET并保存在相对URL中,并且不要忘记$ httpBackend.flush()在你的期望之前 –