2013-11-04 38 views
18

我有一個函數在我的範圍內檢索我的服務狀態,當用戶點擊一個按鈕,或 當某些事件被觸發,並自動調用此函數。

這是我的功能,在控制器中定義我使用:

$scope.getStatus = function() { 
    $http({method: 'GET', url: config.entrypoint + config.api + '/outbound/service/' + $scope.serviceId}) 
    .success(function(data) { 
     $scope.errorMessage = ''; 
     $scope.serviceAllGood = data; 
    }) 
    .error(function() { 
     $scope.serviceAllGood = ''; 
     $scope.errorMessage = 'We are experiencing problems retrieving your service status.'; 
    }); 
    } 

單元測試是由像:

describe('SendServiceCtrl', function(){ 
    var scope, ctrl, $httpBackend, configuration; 

    beforeEach(function() { 
     module('papi', 'ngUpload'); 
    }); 

    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller, config) { 
     configuration = config; 
     $httpBackend = _$httpBackend_; 
     $httpBackend.expectGET(configuration.entrypoint + configuration.api + "/user/outboundstatus/").respond(200, {"meta":{"apiVersion":"0.1","code":200,"errors":null},"response":{"allowed":false}}); 
     scope = $rootScope.$new(); 
     ctrl = $controller('SendServiceCtrl', {$scope: scope}); 
    })); 

    it('Should get the status', function() { 

    scope.serviceId = '09bb5943fa2881e1'; 
    scope.getStatus(); 
    $httpBackend.whenGET(configuration.entrypoint + configuration.api + '/outbound/service/' + scope.serviceId).respond(200, {"meta":{"apiVersion":"0.1","code":200,"errors":null}}); 

    }); 

}); 

在單元測試我有也等$ httpBackend測試同一個控制器,但他們都工作得很輕鬆。我究竟做錯了什麼?

回答

12

您需要在之前提供whenGET您調用該方法。

it('Should get the status', function() { 
    scope.serviceId = '09bb5943fa2881e1'; 
    $httpBackend.whenGET(configuration.entrypoint + configuration.api + '/outbound/service/' + scope.serviceId).respond(200, {"meta":{"apiVersion":"0.1","code":200,"errors":null}}); 
    scope.getStatus(); 
}); 

設置請求的期望然後觸發請求。

希望這會有所幫助。

+0

模板也會導致此故障。 – FlavorScape

+0

你是否認爲使用像'ui.bootstrap'這樣的'$ templateCache'確實會嘲笑GET的需求? – domokun

+0

@domokun你能發佈一個鏈接到使用的地方嗎? –