AngularJS 和 Jasmine:模拟服务

AngularJS and Jasmine: mocking services

我无法模拟以下服务 "broadcaster" 对服务 "pushServices" 的依赖性。

angular.module('broadcaster', ['pushServices']);

angular.module('broadcaster').service('broadcaster', [
    '$rootScope', '$log', 'satnetPush',
    function ($rootScope, $log, satnetPush) {
        // .. contents ..
    };
};

Jasmine 规范如下:

describe('Test Broadcaster Service', function () {
    'use strict';

    var broadcasterService, mockPushService;
    beforeEach(module('broadcaster'));
    beforeEach(inject(function($injector) {

        broadcasterService = $injector.get('broadcaster');
        mockPushService = {
            getSomething: function () { return 'mockReturnValue'; }
        };

        module(function ($provide) {
            $provide.value('satnetPush', mockPushService);
        });

    }));

    it('should return a non-null broadcaster object', function () {
        expect(broadcasterService).not.toBeNull();
    });

});

我得到的错误是典型的 "Unknown provider":

PhantomJS 1.9.8 (Linux) Test Broadcaster Service should return a non-null broadcaster object FAILED
    Error: [$injector:unpr] Unknown provider: $pusherProvider <- $pusher <- satnetPush <- broadcaster
    http://errors.angularjs.org/1.3.14/$injector/unpr?p0=%24pusherProvider%20%3C-%20%24pusher%20%3C-%20satnetPush%20%3C-%20broadcaster

我做错了什么?我应该如何注入依赖项?

关键是在从 $injector 获得被测服务之前先 $provide 模拟服务。然后 'satnetPush' 将存在:

describe('Test Broadcaster Service', function () {
    'use strict';

    var broadcasterService, mockPushService;

    beforeEach(function() {
        module('broadcaster');

        module(function ($provide) {
            mockPushService = {
                getSomething: function () { return 'mockReturnValue'; }
            };

            $provide.value('satnetPush', mockPushService);
        });

        inject(function($injector) {
            broadcasterService = $injector.get('broadcaster');
        })
    });

    it('should return a non-null broadcaster object', function () {
        expect(broadcasterService).not.toBeNull();
    });
});

这是一个working fiddle