2

我无法模拟以下服务“广播者”对服务“pushServices”的依赖关系。

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

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

茉莉花规格如下:

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

});

我得到的错误是典型的“未知提供者”:

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

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

4

1 回答 1

3

关键是在您从 $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();
    });
});

这是一个工作小提琴

于 2015-03-19T19:35:15.823 回答