我有服务:
(function () {
angular.module('app').service('MyAppService', MyAppService);
MyAppService.$inject = ['$http', 'testUrl'];
function MyAppService($http, testUrl) {
var service = {
testFunction: testFunction
};
return service;
function testFunction() {
/*testurl is my backend API*/
return $http.get(testUrl)
.error(function(){
return;
})
.then(function (response) {
return response.data;
});
}
}
})();
我在控制器中将其称为:
testControllerFunction();
function testControllerFunction() {
MyAppService.testFunction().then(function (response) {
app.testResponse = response; //This my http response
console.log(app.testResponse);
});
}
我正在MyAppService中为成功的$ http.get请求编写业力测试案例:
describe('MyAppService', function () {
var MyAppService,http;
beforeEach(function() {
module('app');
inject(function ($injector) {
MyAppService = $injector.get('MyAppService');
testUrl = $injector.get('testUrl');
http = $injector.get('$httpBackend');
});
});
it('should call the backend testurl ', function () {
MyAppService.testFunction();
http.expectGET(testUrl);
});
});
但这似乎不起作用?我哪里做错了? 谢谢!
答案 0 :(得分:1)
您必须flush $httpBackend
it('should call the backend testurl ', function () {
http.expectGET(testUrl);
MyAppService.testFunction();
http.flush();
});