我有这样的服务。
这只是简单地发出一个http get 请求。
angular.module('myApp').service('TESTService', ['$http',
function($http) {
var request = function(url) {
return $http({
method: 'GET',
url: url
});
};
return {
get: function(url) {
return request(url);
}
};
}
]);
在我的 Controller 中,我调用了该服务
TESTService.get('/api/product' + id).success(
function(result) {
console.log(result)
}
);
我需要为其编写单元测试
describe('test here', function () {
var testCtrl, scope, httpBackend, testService;
// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, _TESTService_) {
scope = _$rootScope_.$new();
httpBackend = _$httpBackend_;
testService = _TESTService_;
testCtrl = _$controller_('testCtrl', {
$scope: scope
});
it('should return http data', function() {
var productData = {
data: [
{
obj: {
id:'123'
}
}
]
}
httpBackend.expectGET('/api/product/' + id).respond(productData);
TESTService.get('/api/product/' + id).
then(function(data) {
var result = data;
})
httpBackend.flush();
expect(result).toEqual(productData)
});
}));
运行测试后,我得到了
Error: Unexpected request: GET /api/product/undefined
如何编写测试以确保其通过?有任何想法吗?非常感谢!
最佳答案
您的变量“id”似乎未定义。如果你投入
var id = 123;
此行之前:
httpBackend.expectGET('/api/product/' + id).respond(productData);
它将调用/api/product/123。
所以也许您一开始就在寻找这个:
httpBackend.expectGET('/api/product/' + productData.data[0].obj.id).respond(productData);
TESTService.get('/api/product/' + productData.data[0].obj.id).
等等...希望有帮助!
关于javascript - 如何在我的情况下测试 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28421804/