如何为 angularJS 中的 $http.get 编写 karma-jasmine 测试用例?
How to write a karma-jasmine test case for $http.get in angularJS?
我有一个服务:
(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 请求编写一个 karma 测试用例:
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);
});
});
但这似乎不起作用?我哪里做错了?
谢谢!
你必须 flush $httpBackend
it('should call the backend testurl ', function () {
http.expectGET(testUrl);
MyAppService.testFunction();
http.flush();
});
我有一个服务:
(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 请求编写一个 karma 测试用例:
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);
});
});
但这似乎不起作用?我哪里做错了? 谢谢!
你必须 flush $httpBackend
it('should call the backend testurl ', function () {
http.expectGET(testUrl);
MyAppService.testFunction();
http.flush();
});