在angularjs中,service是单例的,通常用来与后台交互数据,需要数据的组件只需要注入某个service即可,service的典型例子:
app.factory(‘EventService‘, [‘$http‘, ‘$q‘,
function($http, $q) {
return {
getEvents: function() {
var deferred = $q.defer();
$http.get(‘/events.json‘).success(function(result) {
deferred.resolve(result);
}).error(function(result) {
deferred.reject(result);
});
return deferred.promise;
}
};
}]);对于$http的请求,将使用$httpBackend服务进行测试并指定模拟返回的数据:
it(‘should have settings from http request‘, function() {
var result;
var expected = {
"period": "day",
"date": "2015-3-23",
};
//setup
httpBackend.expectGET(‘/XXX.json‘).respond(expected);
var promise = settingService.setting();
promise.then(function(data) {
result = data;
});
httpBackend.flush();
expect(result).toEqual(expected);
});当然 使用$httpBackend(http://docs.angularjs.cn/api/ngMock/service/$httpBackend)服务前需要将它注入,
beforeEach(function() {
module(‘services‘);
inject(function(SearchSettingService, $httpBackend) {
settingService = SearchSettingService;
httpBackend = $httpBackend;
});
});$httpBackend提供了很多方便测试的方法,并且很好地支持REST。
httpBackend.expectGET(url).respond(data); httpBackend.expectPOST(url, param).respond(data); httpBackend.expectJSONP(url).respond(data);
还有其他的方法请自行查询。
还需要解释的是:httpBackend.flush(); 当执行这行代码时,angular会调用这个setup(发送请求并拦截该请求),并将返回指定的数据。
在前面的文章里面我们介绍了Moco(http://hcc0926.blog.51cto.com/172833/1619706), 也可以通过Moco进行打桩测试,配置很简单。
参考链接:
http://www.smashingmagazine.com/2014/10/07/introduction-to-unit-testing-in-angularjs/
http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/testing-services.html
http://andyshora.com/unit-testing-best-practices-angularjs.html
http://icodeit.org/2014/01/how-to-test-service-in-angularjs/
本文出自 “Eason's hcc” 博客,请务必保留此出处http://hcc0926.blog.51cto.com/172833/1623391
原文:http://hcc0926.blog.51cto.com/172833/1623391