你如何在angularjs服务中模拟$ rootScope?

时间:2014-03-28 23:17:26

标签: angularjs unit-testing angularjs-service

鉴于我有这样的服务。

angular.module('app')
  .factory('Session', function Session($rootScope, $cookieStore) {
    var user;

    if (user = $cookieStore.get('user')) {
      $rootScope.currentUser = user;
    }

});

和测试

'use strict';

describe('Service: Session', function () {
  var Session,
    _rootScope,
    _cookieStore;

  beforeEach(module('app'));

  beforeEach(module(function($provide, $injector) {
    _rootScope = $injector.get('$rootScope').$new();
    _cookieStore = {
      get: angular.noop
    };
    $provide.value('$rootScope', _rootScope);
    $provide.value('$cookieStore', _cookieStore);
  }));

  beforeEach(inject(function(_Session_) {
    Session = _Session_;
  }));

  it('transfers the cookie under user into the currentUser', function() {
    spyOn(_cookieStore, 'get').andReturn('user');
    inject(function(_Session_) {
      Session = _Session_;
    });
    expect(_rootScope.currentUser).toEqual('user');
  });
});

我最终得到了

Error: [$injector:unpr] Unknown provider: $rootScope
http://errors.angularjs.org/1.2.6/$injector/unpr?p0=%24rootScope

有人可以向我解释一下我缺少什么概念吗?我发现单元测试服务非常困难。

1 个答案:

答案 0 :(得分:5)

诀窍是使用$ injector在特定时刻显式实例化服务。 (感谢您的帮助@caitp)

'use strict';

describe('Service: Session', function () {
  var _cookieStore;

  beforeEach(module('rallyApp'));

  beforeEach(module(function($provide) {
    _cookieStore = {
      get: angular.noop
    };
    $provide.value('$cookieStore', _cookieStore);
  }));

  it('transfers the cookie under user into the currentUser', function() {
    inject(function($rootScope, $injector) {
      spyOn(_cookieStore, 'get').andReturn('caitp');
      $injector.get('Session');
      expect($rootScope.currentUser).toBe('caitp');
    });
  });
});