AngularJS - 如何测试由服务设置的$ scope初始值

时间:2016-04-08 06:26:43

标签: angularjs unit-testing jasmine

我们说我们有以下角度控制器:

.controller('Ctrl', function ($scope, localStorageService) {
  $scope.vma = localStorageService.get('vma_vma') || 10;
}

它在初始化期间使用外部服务(localStorageService)。 Basicelly localStorageService.get返回先前存储的值'vma_vma',如果不存在则返回null。

我已经模拟了localStorageService,单元测试如下所示:

describe('Controller: Ctrl', function () {
  // load the controller's module
  beforeEach(module('App', function($provide){
    localStorage = {};
    localStorage.get = jasmine.createSpy();
    localStorage.set = jasmine.createSpy();
    $provide.value('localStorageService', localStorage);
  }));

  var Ctrl,
    scope;
  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    Ctrl = $controller(' Ctrl', {
      $scope: scope,
      localStorageService: localStorageService
    });
  }));

我希望能够测试2个案例:

it('should get vma and return 10 when vma not present', function () {
    ???
    expect($scope.vma).toBe(10);
  });

  it('should get vma in localstorage when present', function () {
    ???
    expect($scope.vma).toBe(15);
  });
});

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您无需创建模拟localStorageService。只是为了窥探真实的一个。但解决方案最终是完全相同的:只需配置模拟/间谍以在实例化控制器之前返回您想要的

describe('Controller: Ctrl', function () {
  var $controller,
      localStorageService,
      scope;

  beforeEach(module('App'));
  beforeEach(inject(function(_$controller_, $rootScope, _localStorageService_) {
    scope = $rootScope.$new();
    $controller = _$controller_;
    localStorageService = _localStorageService_;
  }));

  it('should get vma and return 10 when vma not present', function() {
    // given no vma_vma in the local storage
    spyOn(localStorageService, 'get').and.returnValue(null);

    // when instantiating the controller
    $controller('Ctrl', {$scope: scope});

    // then its vma is initialized to 10
    expect($scope.vma).toBe(10);
    expect(localStorageService).toHaveBeenCalledWith('vma_vma');
  });

  it('should get vma in localstorage when present', function() {
    // given a vma_vma equal to 15 in local storage
    spyOn(localStorageService, 'get').and.returnValue(15);

    // when instantiating the controller
    $controller('Ctrl', {$scope: scope});

    // then its vma is initialized to 15
    expect($scope.vma).toBe(15);
    expect(localStorageService).toHaveBeenCalledWith('vma_vma');
  });
});