A similar question: Jasmine angularjs - spy on a method that is called when the controller is initialized
In my controller, I use the angular -local-storage package to provide local storage through injection.
in my unit tests, I want to make sure that the data is retrieved from the service, so I spy on the "get" and "add" methods and make fun of them (.andCallFake).
this works great with all methods that are called through $ scope. $ watch - while I force $ digest. but for the method that is called when the controller is initialized, it does not work. Can someone tell me why this is not working?
Application> Main.js
angular.module('angularTodoApp')
.controller('MainCtrl',['$scope','localStorageService',function ($scope, localStorageService) {
var todosInStore = localStorageService.get('todos');
$scope.todos = todosInStore && todosInStore.split('\n') || [];
$scope.$watch('todos', function(){
localStorageService.add('todos', $scope.todos.join('\n'));
},true);
$scope.addTodo = function() {
$scope.todos.push($scope.todo);
$scope.todo = '';
};
$scope.removeTodo = function(index) {
$scope.todos.splice(index,1);
};
}]);
test> Main.js
describe('Controller: MainCtrl', function () {
beforeEach(module('angularTodoApp'));
var MainCtrl,
scope,
localStorageService,
store = [];
beforeEach(inject(function ($controller, $rootScope, _localStorageService_) {
scope = $rootScope.$new();
localStorageService = _localStorageService_;
MainCtrl = $controller('MainCtrl', {
$scope: scope,
localStorageService: _localStorageService_
});
spyOn(localStorageService,'get').andCallFake(function(key){
return store[key];
});
spyOn(localStorageService,'add').andCallFake(function(key, val){
store[key] = val;
});
}));
it('should retrieve "todos" from the store and assign to scope', function () {
expect(localStorageService.get).toHaveBeenCalledWith('todos');
expect(scope.todos.length).toBe(0);
});
it('should add items to the list and update the store for key = "todos"', function () {
scope.todo = 'Test 1';
scope.addTodo();
scope.$digest();
expect(localStorageService.add).toHaveBeenCalledWith('todos', jasmine.any(String));
expect(scope.todos.length).toBe(1);
});
all tests pass, except those specified in the constructor:
expect(localStorageService.get).toHaveBeenCalledWith('todos');