2014-11-21 44 views
1

我是新來測試,並嘗試用我的控制器在AngularJS中得到這個茉莉花測試設置。我有一個我想模擬的可重用服務,但我一直在收到錯誤(特別是,服務總是失敗,我得到「無法連接到API服務」)。以下是我所嘗試過的。

我的控制器:

angular 
    .module('myApp') 
    .controller('myController', myController); 

function myController($scope, apiService) { 
    apiService.url = "/api/getAccount"; 
    apiService.call().get({ accountNumber: 123 }).$promise.then(function (data) { 
     $scope.account = data; 
    }, function() { 
    throw new Error("Cannot connect to the API service"); 
    }); 

的服務:

angular 
    .module('myApp') 
    .factory('apiService', apiService); 

function apiService($resource) { 
    return { 
     url: '/api/..', 
     call: function() { 
      return $resource(this.url); 
     } 
    } 
}; 

我的茉莉花測試:

describe('myController', function() { 
    var $q, 
    $rootScope, 
    $scope, 
    mockAccountListResponse = { Account: [{ //stuff }] }, 
    mockApiService, 
    deferred; 

    beforeEach(module('myApp')); 

    beforeEach(inject(function (_$q_, _$rootScope_) { 
    $q = _$q_; 
    $rootScope = _$rootScope_; 
    })); 

    beforeEach(inject(function ($controller) { 
    $scope = $rootScope.$new(); 

    mockApiService = { 
    call: function() { 
     return { 
     get: function() { 
      deferred = $q.defer(); 
      deferred.reject("Error Connecting to API Service"); 
      return { $promise: deferred.promise }; 
     } 
     } 
    } 
    } 

    spyOn(mockApiService, 'call').and.callThrough(); 

    $controller('dashboardController', { 
     '$scope': $scope, 
     'apiService': mockApiService, 
    }); 
    })); 

    describe('Upon calling the ApiService', function() { 

    beforeEach(function() { 
     deferred.resolve(mockAccountResponse); 
     $rootScope.$apply(); 
    }); 

    it('should get the account successfully', function() { 
     expect(mockApiService.call).toHaveBeenCalled(); 
    }); 
    }); 
}); 

回答

1

好吧,你實際上是造成問題的原因,當你設置發生的嘲笑。你看,你說行:

deferred.reject("Error Connecting to API Service");

你基本上是說,每當這個模擬服務被調用時,返回一個拒絕承諾讓其他人使用它會得到這個拒絕值和無.then「 s將永遠進入。現在,您只是檢查是否調用了.get,但是我認爲它在您的斷言被考慮之前從承諾中拋出未處理的異常。你爲什麼不直接解決呢? deferred.resolve("Here's a good test value");

由於您剛剛接受測試,如果我沒有提到有一個很酷的模擬庫,它們會自動嘲諷任何使用底層$ httpBackend服務的角色本身,包含角度$資源服務,因爲它依賴於$ httpBackend。

如果您設置了一個包含上述庫的測試html頁面,您的所有網絡請求都會被模擬,您將有權訪問它們嘗試通過網絡發送的值。

這是模擬庫:https://docs.angularjs.org/api/ngMock。我建議嘗試一下!

+1

用deferred.resolve替換deferred.reject(我在下面)修復了這個問題,現在測試成功了,謝謝!此外,這是非常有用的關於ngMock的建議,因爲我認爲$ httpBackend只適用於$ http調用,而不是$ resource。我一定會考慮這一點。 – Trehyu 2014-11-21 20:41:55