在不使用的情况下,在AngularJS中连接到服务器数据源的建议方法是什么$resource.
将$resource有很大的局限性,如:
我写了一个AngularJS服务,我想对它进行单元测试.
angular.module('myServiceProvider', ['fooServiceProvider', 'barServiceProvider']).
factory('myService', function ($http, fooService, barService) {
this.something = function() {
// Do something with the injected services
};
return this;
});
Run Code Online (Sandbox Code Playgroud)
我的app.js文件已注册:
angular
.module('myApp', ['fooServiceProvider','barServiceProvider','myServiceProvider']
)
Run Code Online (Sandbox Code Playgroud)
我可以测试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();
});
});
Run Code Online (Sandbox Code Playgroud)
这证明了服务可以由DI框架创建,但是接下来我想对服务进行单元测试,这意味着模拟注入的对象.
我该怎么做呢?
我已经尝试将模拟对象放在模块中,例如
beforeEach(module(mockNavigationService));
Run Code Online (Sandbox Code Playgroud)
并将服务定义重写为:
function MyService(http, fooService, barService) {
this.somthing = function() {
// Do something with the injected services
};
});
angular.module('myServiceProvider', …Run Code Online (Sandbox Code Playgroud)