我正在尝试测试一个使用服务
的 Controller
。但是,service
目前是 null
,因为我想在 controller
中隔离测试。
这是当前的测试,它不起作用,因为 BoardService
是 null
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
BoardController = $controller('BoardController', {
$scope: scope,
board: {id: 1, tasks: {}},
BoardService: null
});
}));
it ("should add a new task", function() {
var tasksBefore = scope.board.tasks.length;
scope.addTask(category, 'this is a new task');
var tasksAfter = scope.board.tasks.length;
expect(tasksAfter).toBe(tasksBefore + 1);
});
这是来自 Controller 的 addTask()
函数:
$scope.addTask = function(category, task) {
BoardService.addTask({name : task, category : category.id}).success(function(task_id) {
// Removed code for simplicity
});
}
Aaa 最后,service
中的函数:
this.addTask = function(data) {
return $http.post($rootScope.serverRoot + '/task/create', data);
}
最佳答案
我认为这个想法是模拟一个BroadService
...所以可能是...
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
var boardService = {
addTask:function(task){
var d = $q.defer();
d.resolve(/*Whatever your service function returns: if its just a task_id, return an int or something*/);
return d.promise;
};
};
BoardController = $controller('BoardController', {
$scope: scope,
board: {id: 1, tasks: {}},
BoardService: boardService
});
}));
it ("should add a new task", function() {
var tasksBefore = scope.board.tasks.length;
scope.addTask(category, 'this is a new task');
scope.$apply();
var tasksAfter = scope.board.tasks.length;
expect(tasksAfter).toBe(tasksBefore + 1);
});
关于javascript - AngularJS, Jasmine : Testing a controller function calling a service using $http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23908498/