AngularJS在服务测试中注入服务模拟

Abe*_*oun 7 unit-testing jasmine angularjs angularjs-service

我一直试图测试一项服务暂时没有用,并希望得到一些帮助.这是我的情况:

我的服务看起来有点像这样

myModule.factory('myService', ['$rootScope', '$routeParams', '$location', function($rootScope, $routeParams, $location) {

  var mySvc = {
    params: {}
  }

  // Listen to route changes.
  $rootScope.$on('$routeUpdate', mySvc.updateHandler);

  // Update @params when route changes
  mySvc.updateHandler = function(){ ... };

  ...
  ...

  return mySvc;

}]);
Run Code Online (Sandbox Code Playgroud)

我想在服务注入'myService'我的测试之前模拟注入的服务,这样我就可以测试下面的初始化代码了

  var mySvc = {
    params: {}
  }

  // Listen to route changes.
  $rootScope.$on('$routeUpdate', mySvc.updateHandler);
Run Code Online (Sandbox Code Playgroud)

我正在使用Jasmine进行测试和模拟.这就是我现在想出来的

describe('myService', function(){
  var rootScope, target;
  beforeEach(function(){
    rootScope = jasmine.createSpyObj('rootScope', ['$on']);

    module('myModule');
    angular.module('Mocks', []).service('$rootScope', rootScope );
    inject(function(myService){
      target = myService;
    });        
  });

  it('should be defined', function(){
    expect(target).toBeDefined();
  });

  it('should have an empty list of params', function(){
    expect(target.params).toEqual({});
  });

  it('should have called rootScope.$on', function(){
    expect(rootScope.$on).toHaveBeenCalled();
  });
});
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我的rootcope mock并没有取代原版,而依赖注入文档让我更加困惑.

请帮忙

小智 7

我会窥探实际的$ rootScope而不是尝试注入你自己的自定义对象.

var target, rootScope;
beforeEach(inject(function($rootScope) {
  rootScope = $rootScope;

  // Mock everything here
  spyOn(rootScope, "$on")
}));

beforeEach(inject(function(myService) {
  target = myService;
}));

it('should have called rootScope.$on', function(){
  expect(rootScope.$on).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)

我已经在CoffeScript中对此进行了测试,但上面的代码仍然有效.