gpt4 book ai didi

javascript - AngularJS 和 Jasmine : mocking services

转载 作者:行者123 更新时间:2023-11-29 19:29:11 24 4
gpt4 key购买 nike

我无法模拟以下服务“广播者”对服务“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

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

最佳答案

关键是在您从 $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

关于javascript - AngularJS 和 Jasmine : mocking services,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29106585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com