如何在AngularJS服务Jasmine测试中模拟$ http? [英] How do I mock $http in AngularJS service Jasmine test?
本文介绍了如何在AngularJS服务Jasmine测试中模拟$ http?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试测试AngularJS服务 carService
,但 $ httpBackend
似乎无效。
I am trying to test an AngularJS service carService
, but the $httpBackend
does not seem to work.
//carService
angular.module('services').factory('carService',
function($http) {
return {
getTypes: function() {
return $http.get('/api/cars/types');
}
};
});
有人可以解释为什么回复是空的吗?
Can anybody explain why the response is null?
describe("Services", function () {
beforeEach(module("app.services"));
describe("Car services", function () {
var service, $httpBackend;
beforeEach(inject(function($injector) {
service = $injector.get('carService');
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('GET', "/api/cars/types").respond(["Toyota", "Honda", "Tesla"]);
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('getTypes - should return 3 car manufacturers', function () {
service.getTypes().then(function(response) {
expect(response.length).toEqual(3); //the response is null
});
$httpBackend.flush();
});
});
});
推荐答案
试试这个:
expect(response.data.length).toEqual(3);
$ http
返回的响应对象请求在 data
属性中包含响应数据( docs )。
The response object returned by a $http
request has the response data within the data
property (docs).
这篇关于如何在AngularJS服务Jasmine测试中模拟$ http?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文