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