我已经盯着这几个小时,但我不明白它有什么问题。它告诉我,当我在控制器文件中定义addTodo方法时,它并不存在 - 我在这里缺少什么?
main.js
angular.module('mytodoApp')
.controller('MainCtrl', function ($scope, localStorageService) {
// breaks on repeat or blank input
function addTodoFn() {
$scope.todos.push($scope.todo);
$scope.todo = '';
}
function removeTodoFn(index) {
$scope.todos.splice(index, 1);
}
function watchFn() {
localStorageService.set('todos', $scope.todos);
}
//////////
var todosInStore = localStorageService.get('todos');
$scope.todos = todosInStore || [];
$scope.$watch('todos', watchFn, true);
$scope.addTodo = addTodoFn;
$scope.removeTodo = removeTodoFn;
});
main.spec.js
describe('Controller: MainCtrl', function () {
var MainCtrl;
var scope;
var store = [];
var todo;
var localStorage = {
addItem: function() {
store.push(todo);
},
deleteItem: function(index) {
store.splice(index, 1);
}
};
beforeEach(function(){
module('mytodoApp');
});
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl as mc', {
$scope: scope
});
// LocalStorage mock.
spyOn(MainCtrl, 'addTodo').and.callFake(localStorage.addItem); <-- throwing the error
spyOn(MainCtrl, 'removeTodo').and.callFake(localStorage.deleteItem);
}));
afterEach(function() {
store = [];
todo = '';
});
it('should have no items to start with', function() {
expect(store.length).toBe(0);
});
it('should add items to the list', function() {
todo = 'a';
scope.addTodo();
expect(store.length).toBe(1);
todo = 'b';
scope.addTodo();
expect(store.length).toBe(2);
});
});
错误
PhantomJS 1.9.8(Mac OS X 0.0.0)控制器:MainCtrl应该将项目添加到列表FAILED
错误:/Users/Baggio/mytodo/test/spec/controllers/main.js:29中不存在addTodo()方法
答案 0 :(得分:1)
您正在监视addTodo
的{{1}}方法。但MainCtrl
没有这样的方法。该方法位于MainCtrl
上,而不是scope
。