角度单位测试$ scope。$ on on service not working

时间:2015-06-09 15:31:02

标签: angularjs unit-testing service scope karma-jasmine

我正在尝试为依赖于$ rootScope。$ on的服务编写一些karma / jasmine / sinon单元测试,以触发它出去并获取一些数据。我的主要问题是,即使我在beforeEach中执行$ rootScope,我也无法获得$ rootScope。$ on事件。任何帮助将不胜感激。

服务......

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

   }
}    

测试

 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');

    });

});

我已经看过几个在控制器中执行此类操作的示例,您可以将作为显式依赖项注入作用域,但没有任何人在服务中执行此操作的示例(可能有充分理由?)。

1 个答案:

答案 0 :(得分:0)

显然我有一些令人敬畏的拼写错误导致了我的问题:^)