在Angular控制器中,我有一些代码,如:
$http.save('api/purchases').$promise.then(function(response) {
var location = response.headers('location'); // to retrieve the location in response header
})
在茉莉花的单元测试中,
it('..', function(){
$httpBackend.expectPost('api/purchase').respond(201, {}, {location: 'xxx'});
// when run the test, it reports an error with 'undefined is not a constructor' (evaluting response.headers('location'))
})
如何测试response.headers(' location')?
答案 0 :(得分:3)
Angular docs似乎表示在给定statusText
时响应需要headers
(因为它不是可选的,在传入headers
时是必需的)
function([status,] data [,headers,statusText])
你应该能够传递一些像201这样的文本
$httpBackend.expectPost('api/purchase').respond(201, {}, {location: 'xxx'}, 'Created');
答案 1 :(得分:0)
在$ resource action中使用transformResponse
var resource = $resource('api/purchase', {}, {
get: {
method: 'GET',
transformResponse: function(data, headers) {
var response = {};
response.data = data;
response.headers = headers();
return response;
}
}
}
检索'location':
resource.get().$promise.then(function(response){
var location = response.headers.location; // 'headers' has been put into response object above
})
然后测试可以正常运行。