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()在你的期望之前 –