错误:addTodo()方法不存在 - 为什么会抛出此错误?

时间:2015-09-02 10:37:57

标签: angularjs jasmine

我已经盯着这几个小时,但我不明白它有什么问题。它告诉我,当我在控制器文件中定义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()方法

1 个答案:

答案 0 :(得分:1)

您正在监视addTodo的{​​{1}}方法。但MainCtrl没有这样的方法。该方法位于MainCtrl上,而不是scope

顺便说一句,如果你侦察范围,你的测试会测试任何东西:它只测试Jasmin间谍做它应该做的事情,而不是测试实际的addTodo()方法做它应该做的事情。你应该监视或嘲笑的是控制器的依赖,即localStorage服务。