我正在使用 yeoman 生成器创建的应用程序,并在 karma 中进行测试。
我的每项服务都有可重用的模拟对象。我如何正确地用模拟替换特定的服务依赖关系,这样我就可以使用茉莉花来监视方法
到目前为止,我已经这样做了:
我的服务:
angular.module('ql')
.service('loginService', ['$http','API','authService', function ($http, API, authService) {
return {
//service implementation
}]);
authService 的模拟:
'use strict';
//lets mock http auth service, so it would be spied upon.
ql.mock.$authServiceMockProvider = function() {
this.$get = function() {
var $service = {
loginConfirmed: function() { }
};
return $service;
};
};
//and register it.
angular.module('qlMock').provider({
$authServiceMock: ql.mock.$authServiceMockProvider
});
我的测试:
'use strict';
describe('When i call login method()', function () {
// load the service's module
beforeEach(module('ql'));
beforeEach(angular.mock.module('qlMock'));
// instantiate service
var loginService,
authService,
$httpBackend;
beforeEach(function() {
// replace auth service with a mock.
// this seems kind of dirty... is there a bettery way?
module(function($provide, $injector){
authService = $injector.get('$authServiceMockProvider').$get();
$provide.value('authService', authService);
});
//actually get the loginService
/*jshint camelcase: false */
inject(function(_loginService_, _$httpBackend_) {
loginService = _loginService_;
$httpBackend =_$httpBackend_;
});
//http auth module method, that should be call only on success scenarios
spyOn(authService, 'loginConfirmed').andCallThrough();
});
it('it should do something', function () {
//actual test logic
});
});
我不喜欢的是这条线:
authService = $injector.get('$authServiceMockProvider').$get();
我想简单地以某种方式获取 authServiceMock(无需获取提供程序,并调用 et 方法),然后将其注入 loginService。
我知道我可以简单地调用我的 $authServiceMock authService,并将其作为模拟提供,以便它始终覆盖我的默认实现,但我不想这样做。