類似問題:Jasmine angularjs - spying on a method that is called when controller is initialized茉莉angularjs - 上稱爲角本地存儲方法刺探當控制器被初始化
以我控制器I使用所述角度本地存儲包通過注射,以提供localStorageService。
在我的單元測試中我想確保數據是從服務中檢索的,所以我窺探了「get」和「add」方法並嘲笑它們(.andCallFake)。
對於通過$ scope調用的所有方法,這可以正常工作$ watch - 只要我強制$摘要。但是對於在控制器初始化時調用的方法,它似乎不起作用。 任何人都可以建議爲什麼這不起作用?
應用> Main.js
3210測試> Main.js
describe('Controller: MainCtrl', function() {
// load the controller's module
beforeEach(module('angularTodoApp'));
var MainCtrl,
scope,
localStorageService,
store = [];
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, _localStorageService_) {
scope = $rootScope.$new();
localStorageService = _localStorageService_;
MainCtrl = $controller('MainCtrl', {
$scope: scope,
localStorageService: _localStorageService_
});
//mock localStorageService get/add
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);
});
所有測試都通過,除了一個在構造:
expect(localStorageService.get).toHaveBeenCalledWith('todos');
是的,當我醒來時,我才意識到。上帝永遠不要熬夜,並試圖弄清楚它!謝謝!接受,upvoted。 –