我正在学习使用Karma和Jasmine在Angular中进行单元测试,并试图确定如何正确模拟工厂并测试它是否被控制器调用。工厂从ESPN API发出一个简单的http请求。当控制器调用它时,它将响应数据传递到数组。到目前为止,我所基于的是:Angular单元测试控制器-controller内部的模拟服务。不幸的是,我似乎无法正确地做到这一点。
这是我的控制器和工厂的外观:
angular.module('TeamApp.services',[])
.factory('espnAPIservice',function($http) {
var espnAPI = {};
espnAPI.getTeams = function() {
return $http({
method: 'GET',
url: 'http://api.espn.com/v1/sports/hockey/nhl/teams?'
})
}
return espnAPI;
});
//Calls the espnAPIservice and stores the retrieved information in an array
angular.module('TeamApp.controllers',[])
.controller('TeamCtrl', ['$scope','espnAPIservice',function($scope,espnAPIservice) {
$scope.teams = [];
espnAPIservice.getTeams().success(function (response) {
$scope.teams = response;
});
}]);
angular.module('TeamApp',['TeamApp.services','TeamApp.controllers']);
到目前为止,这是我的测试:
describe('controller: TeamCtrl', function() {
var $scope, ctrl;
//Inject controller module into the factory that it the controller will call
beforeEach(module('TeamApp.controllers', function($provide) {
var espnAPIservice = {
getTeams: function(){}
};
spyOn(espnAPIservice,'getTeams').andReturn('ESPN'); //change return value
$provide.value('espnAPIservice',espnAPIservice);
}));
//Inject the $controller and $rootScope services
beforeEach(inject(function($rootScope, $controller, espnAPIservice) {
//Create a new scope that is the child of $rootScope
$scope = $rootScope.$new();
//Create the controller
ctrl = $controller('TeamCtrl',{$scope: $scope, espnAPIservice: espnAPIservice});
}));
it('should call the getTeams function', function(){
expect($scope.teams).toBe('ESPN');
});
这是我运行测试时遇到的错误:
PhantomJS 1.9.7(Windows 7)控制器:TeamCtrl应该调用getTeams函数FAILED
TypeError:“未定义”不是函数(评估'espnAPIservice.getTeams()。success(function(response){
$ scope.teams = response;})')在c:/ Users / jquering / Documents / Coding Practice / Angular Practice / nhlStats / app / scripts / teams.js:21
在调用时(c:/ Users / jquering / Documents / Coding Practice / Angular Practice / nhlStats / app / lib /angular.js:3762)
实例化(c:/ Users / jquering / Documents / Coding Practice / Angular Practice / nhlStats / app / lib / angular.js:3773)实例化
于c:/ Users / jquering / Documents / Coding Practice / Angular Practice / nhlStats / app / lib / angular.js:6884
at c:/ Users / jquering / Documents / Coding Practice / Angular Practice / nhlStats / test / controllers / spec / main.js:18
在调用时(c:/ Users / jquering / Documents / Coding Practice / Angular Practice / nhlStats / app / lib / angular.js:3762)
在workFn(c:/ Users / jquering / Documents / Coding Practice / Angular Practice / nhlStats / app / lib / angular-mocks .js:2144)未定义
预期[]为'ESPN'。
PhantomJS 1.9.7(Windows 7):执行1 of 1(1 FAILED)错误(0.009秒/ 0.008秒)
任何帮助将非常感激!
如何正确模拟工厂
beforeEach(module(function ($provide){
$provide.factory('TheSameName', function (){
//return your mock here
});
}));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句