我正在使用HttpBackend来模拟我的Angular应用程序正在进行的一些调用的一些Http响应。
然而,当我运行测试时,我得到了错误"意外请求:[object object]未定义"。
我知道这个错误通常意味着你错过了或打错了应用程序发出的$http请求之一,所以它找不到响应。但我的错误并不像其他错误那样具体,通常会说"意外请求:GET api/call",所以我不知道出了什么问题。
以前有人遇到过这种特定的错误吗?
样本代码
角度控制器:
app.controller( 'ctrl',
[ '$scope' , '$http' , '$location', function( $scope, $http, $location ) {
$http.get(
"/api/1.0/id/" + id,
{
headers: getAuthHeaders()
}
).success(function( data ){ //... })]
);
茉莉花试验
it('should ...', function(){
httpBackend.whenGET('/api/1.0/id/*').respond(200,{"test":"Test"});
//...
});
我自己尝试了您的代码并进行了测试。我添加了一个设置ID的功能,但我认为你有一些模拟程序:
//PRESET ID
var id = 'deajedgwe1e213df';
//FUNCTION TO CAPSULATE API CALL
this.callApi = function () {
http.get(
"/api/1.0/id/" + id,
{
//headers: getAuthHeaders()
}
).success(function( data ){
console.log('success', data);
}).error(function (err) {
console.log('error', err);
});
};
//FUNCTION TO SET ID
this.setId = function (ID) {
id = ID;
};
然后我复制了你的测试并修改成这样:
it('should ...', function(){
ctrl.setId('test123ID');
httpBackend.expectGET('/api/1.0/id/test123ID').respond(200,{"test":"Test"});
ctrl.callApi();
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
这是有效的。你可以这样做的替代方案:
it('should ...', function(){
httpBackend.expectGET(/api/i).respond(200,{"test":"Test"});
ctrl.callApi();
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
这也有效,但它只是验证/api是否已被调用。。。我不知道,如果这是那个,你想测试什么。
我认为主要的问题是在api调用中使用星号表示法。试着像我一样修改你的代码。如果这没有帮助,您应该调用您的头函数。
祝你好运。