我检查了所有内容,但似乎仍有错误
服务:
angular.module('app.services')
.factory('eventService', ['$http', '$q', function($http, $q) {
return {
get: function() {
var deffered = $q.defer();
$http.get('x')
.success(function(data) {
deffered.resolve(data);
})
.error(function(){
deffered.reject("could not access events");
});
return deffered.promise;
}
};
}])
单元测试:
describe('when fetching events by service', function() {
var service;
var $httpBackend;
var appConfig;
beforeEach(function() {
module("ngMockE2E");
module("app.services");
inject(function(eventService, _$httpBackend_) {
service = eventService;
$httpBackend = _$httpBackend_;
});
});
it('should get items', function(){
$httpBackend.expectGET('x').respond([{ name : 1}]);
var promise = service.get();
promise.then(function(data){
console.log(data);
});
$httpBackend.flush();
});
});
我在.flush()
上收到以下错误Error: No pending request to flush !
at /test/lib/angular-mocks.js:1148
at /test/unit/services/EventServiceSpec.js:26
另外,我如何确保eventService正在使用$ httpBackend设置。那就是使用$ httpBackend而不是$ http的依赖关系生成eventService?我认为我可能是错误的原因。
答案 0 :(得分:0)
$httpBackend.whenGET('x').respond([{ name : 1}]); // when you receive a request expectation, respond X
$httpBackend.expectGET('x').respond([{ name : 1}]); // add a request expectation and respond X
$httpBackend.expectGET('x'); // add a request expectation
因此,您只需在发出请求时设置行为,而不是实际添加请求期望。
您需要使用:
$httpBackend.expectGET('x').respond([{ name : 1}]);
或
$httpBackend.whenGET('x').respond([{ name : 1}]);
$httpBackend.expectGET('x');