AngularJS implements service testing services

I am trying to test the service but nothing useful, and was hoping for some help. Here is my situation:

My service looks a bit like

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

And I want to mock the services introduced in 'myService' before the service is introduced into my tests so that I can test the initialization code below

  var mySvc = { params: {} } // Listen to route changes. $rootScope.$on('$routeUpdate', mySvc.updateHandler); 

I use Jasmine for tests and layouts. This is what I came up with now

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

This does not work. My root layout does not replace the original, and the Injection Dependency document is more confusing to me.

Please, help

+7
source share
2 answers

I would spy on a real $ rootScope instead of trying to enter my 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 tested this in CoffeScript, but the code above should still work.

+7
source

You can create a RootController and then enter it:

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

With this approach, you can access the $ rootScope functions from your "myService"; Such a 'myService. $ On () '

I just did this, let me know if help is needed.

0
source

All Articles