Reputation: 11374
I have tried to create a mock of my BoardService
. However, the .then
function is not being run in the controller
when running the test, but it's working fine when running the actual application.
Here is the test:
beforeEach(inject(function($rootScope, $controller, $q) {
scope = $rootScope.$new();
BoardController = $controller('BoardController', {
$scope: scope,
board: {
id: 1,
tasks: []
},
BoardService: {
addTask: function(data) {
var defer = $q.defer();
defer.resolve(1);
return defer.promise;
}
}
});
}));
it("should add a new task", function() {
scope.addTask(category, 'this is a new task');
expect(scope.board.tasks.length).toBe(1);
});
And the controller function:
$scope.addTask = function(category, task) {
BoardService.addTask({name: task, category: category.id, boardId: $scope.board.id}).then(function(task_id) {
// Never reaches here
$scope.board.tasks.push({id : task_id, name : task, category : category.id, board_id : $scope.board.id});
});
}
Why is it never reaching the comment in the .then
function?
Upvotes: 0
Views: 290
Reputation: 196
As we discussed on IRC: you need to call scope.$digest for the promise to fire.
Upvotes: 1
Reputation: 17878
After resolving the promise you need to trigger a digest-cycle for angular to pick up on it.
scope.addTask(category, 'this is a new task');
scope.$digest();
expect(scope.board.tasks.length).toBe(1);
Upvotes: 2