AngularJS inject service mock inside service tests

与世无争的帅哥 提交于 2019-12-05 05:33:34

I would spy on the actual $rootScope instead of trying to inject your own custom object.

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();
});

I've tested this in CoffeScript, but the code above should still work.

You could create a RootController and then inject it:

inject(function(myService, $controller){
  target = myService;
  $controller('rootController', {
        $scope : $rootScope.$new(),
        $rootScope : myService
  });
});  

With this approach you can access $rootScope functions from your 'myService'; Such 'myService.$on()'

I just made it, let me know if help is needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!