我有一个 AngularJS 服务编写,我想单元测试它。
angular.module('myServiceProvider', ['fooServiceProvider', 'barServiceProvider']).
factory('myService', function ($http, fooService, barService) {
this.something = function() {
// Do something with the injected services
};
return this;
});
My app.js file has these registered:
angular
.module('myApp', ['fooServiceProvider','barServiceProvider','myServiceProvider']
)
我可以测试 DI 的工作原理:
describe("Using the DI framework", function() {
beforeEach(module('fooServiceProvider'));
beforeEach(module('barServiceProvider'));
beforeEach(module('myServiceProvder'));
var service;
beforeEach(inject(function(fooService, barService, myService) {
service=myService;
}));
it("can be instantiated", function() {
expect(service).not.toBeNull();
});
});
这证明了服务可以通过 DI 框架来创建,然而接下来我想对服务进行单元测试,这意味着对注入的对象进行模拟。
我该怎么做呢?
我已经尝试将我的模拟对象放在模块中,例如。
beforeEach(module(mockNavigationService));
and rewriting the service definition as:
function MyService(http, fooService, barService) {
this.somthing = function() {
// Do something with the injected services
};
});
angular.module('myServiceProvider', ['fooServiceProvider', 'barServiceProvider']).
factory('myService', function ($http, fooService, barService) { return new MyService($http, fooService, barService); })
但后者似乎完全阻止了 DI 创建的服务。
有人知道我如何在单元测试中模仿注入的服务吗?
谢谢
大卫