0
我学习了使用Karma来测试我的angularjs应用程序。但是,我的控制器中不少使用多个服务,这些服务是检索json然后加载到页面的http请求。我一直因为两个问题而无法回答。 1)如何模拟这些服务2)我应该为我的控制器测试什么问题2我觉得很难回答,因为控制器功能取决于我在其他控制器中使用的服务。无论如何,让我告诉我的控制器之一,然后,“库”房我的服务:我应该测试我的角度控制器?
我的一个控制器的
angular.module('ccApp')
.controller('CountriesCtrl', ['$scope', '$routeParams', '$location','countryInfo', 'getCountries', 'countriesCache', 'getNeighbors',
'buildCountry', '$timeout', '$q',
function($scope, $routeParams, $location, countryInfo, getCountries, countriesCache, getNeighbors,
buildCountry, $timeout, $q){
getCountries.countriesObject.then(function(response){
$scope.geocountries = response.data.geonames;
},
function(response){
alert("error");
});
$scope.toCountry = function(geocountry){
getNeighbors(geocountry.geonameId)
.then(function(response){
buildCountry(geocountry, response);
var path = '/countries/'+countryInfo.name+'/capital';
$location.path(path);
}),
function(response){
alert('Error');
};
};
$scope.goHome = function(){
$location.path('/');
};
}]);
我应该在控制器规格中测试什么?
这里就是服务收纳在库:
angular.module('library', [])
.service('countryInfo', function(){
var country = {
name: '',
pop: '',
area: '',
capital: '',
code: '',
capPop: '',
numNeigh: 0,
neighbors: []
};
return country;
})
.factory('countriesCache', ['$cacheFactory', function($cacheFactory){
return $cacheFactory('countriesCached');
}])
.factory('getCountries', ['$http', function($http){
var request = {
username: 'vman'
};
return { countriesObject : $http({
method: 'GET',
url: 'http://api.geonames.org/countryInfoJSON',
params: request
})};
}])
.factory('getCountry', ['$http', function($http){
return function(countryCode){
return $http({
method: 'GET',
url: 'http://api.geonames.org/countryInfoJSON',
params: { username: 'vman', country: countryCode }
});
};
}])
.factory('getNeighbors', ['$http', function($http){
return function(geonameId){
return $http({
method: 'GET',
url: 'http://api.geonames.org/neighboursJSON',
params: { username: 'vman', geonameId: geonameId }
});
};
}])
.factory('buildCountry', ['countryInfo', '$q', '$timeout', function(countryInfo, $q, $timeout){
return function(geocountry, response){
countryInfo.name = geocountry.countryName;
countryInfo.code = geocountry.countryCode;
countryInfo.pop = geocountry.population;
countryInfo.area = geocountry.areaInSqKm;
countryInfo.capital = geocountry.capital;
countryInfo.neighbors = response.data.geonames;
countryInfo.numNeigh = response.data.geonames.length;
};
}])
.run(['$rootScope', '$location', function($rootScope, $location) {
$rootScope.$on('$routeChangeError', function() {
$location.path('/error');
});
}]);
@suneet_bansal感谢铺设了详细的模拟。我会在稍后尝试。所以,我是否正确理解你,我没有测试实际服务,而是调用服务的范围函数?更具体地说,我测试的范围函数调用服务,在这种情况下,纯粹模拟服务 – Vman
是的,你砰的一声。 –