angular unit testing $scope.$on in a service not working

191 views Asked by At

I'm trying to write some karma / jasmine / sinon unit tests for a service that relies upon $rootScope.$on to trigger it to go out and fetch some data. My main issue is that I can't seem to get the $rootScope.$on event to fire even when I perform a $rootScope.$broadcast in the beforeEach. Any help would be much appreciated.

The Service...

(function (angular) {
    'use strict';

    angular.module('myModule')
       .service('myService', myService);

    myService.$inject = ['$rootScope','dependencyService1','dependencyService2','$q'];

    function myService($rootScope,dependencyService1,dependencyService2,$q) {

        var massagedData; 

        $rootScope.$on('myEvent', function (event, data) {
            var info1 = dependencyService1.getSomeInfo();
            var info2 = dependencyService2.getSomeOtherInfo();
            massagedData = massageData(info1,info2);

       }

       return {
          getPreFetchedData: function(){return massagedData;}
       }

   }
}    

The Tests

 describe('Service fetches data', function() {
    var myService, $rootScope;

    beforeEach(module('myModule'));

    beforeEach(inject(function(_$rootScope_,_myService_,dependencyService1,dependencyService2,$q) { // jshint ignore:line
            myService = _myService_;
            $rootScope = _$rootScope_;

            var fakeResults = {
                1: {someInfo:'info'}
            };               

            spyOn(dependencyService1, 'getSomeInfo').and.returnValue($q.when(fakeResults));
            spyOn(dependencyService2, 'getSomeOtherInfo').and.returnValue($q.when(true));

            spyOn($rootScope, '$broadcast').and.callThrough();

            $rootScope.$broadcast('myEvent',{eventData:'data'});

            $rootScope.$digest();

        })
    );

    it('Fetches and massages data on event', function () {
            var results = myService.getPreFetchedData();
            expect(results.someProperty).toEqual('info');

    });

});

I have seen several examples of doing something like this in a controller where you can inject a scope as an explicit dependency, but no examples of anyone doing this in a service (maybe for a good reason?).

1

There are 1 answers

0
Patrick Rogers-Ostema On

Apparently I had some sort awesome typo that was causing my problem :^)