Jasmine angularjs - 在初始化控制器时调用的角度局部存储方法的间谍

Vin*_*met 4 javascript jasmine angularjs angular-local-storage

类似的问题:Jasmine angularjs - 监视控制器初始化时调用的方法

在我的控制器中,我使用angular-local-storage包通过注入提供localStorageService.

在我的单元测试中,我想确保从服务中检索数据,因此我监视"get"和"add"方法并模拟它们(.andCallFake).

这适用于通过$ scope调用的所有方法.$ watch - 只要我强制$ digest.但是对于在控制器初始化时调用的方法,它似乎不起作用.任何人都可以建议为什么这不起作用?

应用> Main.js

angular.module('angularTodoApp')
  .controller('MainCtrl',['$scope','localStorageService',function ($scope, localStorageService) {

    var todosInStore =  localStorageService.get('todos');
    $scope.todos = todosInStore && todosInStore.split('\n') || [];
    //$scope.todos = ['Item 1', 'Item 2', 'Item 3'];

    $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);
    };
  }]);
Run Code Online (Sandbox Code Playgroud)

测试> 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);
  });
Run Code Online (Sandbox Code Playgroud)

除了构造函数中的那个之外,所有测试都通过:

expect(localStorageService.get).toHaveBeenCalledWith('todos');
Run Code Online (Sandbox Code Playgroud)

Mic*_*mza 5

原因是控制器在您调用的点初始化$controller,在您的示例中,您创建间谍之前spyOn.您的示例中的解决方案是将调用$controller以后的调用spyOn.

对于较长的测试套件,为了保持干燥,您可能必须将呼叫$controller置于单独的功能中,然后您可以在模拟任何所需的服务后调用.