如何删除意外请求:GET data.json? [英] how to remove Unexpected request: GET data.json?
问题描述
我正在尝试使用 $httpBackend 来测试我的 $http 请求 ..我正在获取
I am trying to use $httpBackend to test my $http request ..i AM getting
这个错误
Unexpected request: GET data.json
No more request expected
这是我的测试代码
beforeEach(inject(function($rootScope,$controller,appfactory,_$httpBackend_) {
$scope = $rootScope.$new();
$httpBackend=_$httpBackend_;
ctrl = $controller('cntrl', {$scope: $scope});
fac=appfactory;
modeSpy= spyOn(fac, 'mode').and.returnValue('a');
}));
it('test true value',function(){
expect(true).toBeTruthy()
})
it('check message value',function(){
$scope.toggle();
expect($scope.message).toEqual('naveen')
})
it("tracks that the spy was called", function() {
//expect(fac.setValue).toHaveBeenCalled();
var response=[{"name":"naveen"},{"name":"parveen"}]
$httpBackend.expectGET('data.json').respond(response);
$scope.getData();
$httpBackend.flush();
expect($scope.data[0].name).toEqual('naveen')
});
这是我的代码http://plnkr.co/edit/zdfYdtWbnQz22nEbl6V8?p=preview
消除此错误的解决方案
I have this controller
.controller('cntrl',function($scope,appfactory,$http){
$scope.data=[];
appfactory.setValue('test abc');
$scope.getData=function(){
$http.get('data.json').success(function(data){
console.log(JSON.stringify(data))
$scope.data=data;
}).error(function(data){
console.log(JSON.stringify(data))
})
}
$scope.getData();
$scope.toggle=function(){
if(appfactory.mode()=='a'){
$scope.message='naveen'
}else {
if(appfactory.mode()=='b'){
$scope.message='parveen'
}
}
}
})
如果我注释掉这一行 $scope.getData(); 或删除这一行 $scope.getData(); 那么我的测试就通过了,我可以消除这个错误.我的问题为什么会发生这个错误?如果不能使用控制器中的功能,那么测试这个功能有什么用?
if i comment out this line $scope.getData(); or remove this line $scope.getData(); then my test is pass and I am able to remove this error . My Question why this error occurred? If am not able to use the function in controller then what is the use of testing of this function ?
推荐答案
当初始化控制器时,因为你正在调用 $scope.getData()
, data.json
将被提取.因此,在测试中初始化控制器时,每次初始化控制器时都必须模拟该请求.
When initialising the controller because you're calling $scope.getData()
, data.json
will be fetched. So, when initialising the controller in test, that request would have to be mocked every time controller is initialised.
解决此问题的一种方法是使用此控制器将 ng-init="getData()"
添加到 html 元素,以便仅在 html 和不是在控制器初始化时.
One way to overcome this is to add ng-init="getData()"
to the html element using this controller, so that the data would be fetched but only on request by the html and not when controller is initialized.
这篇关于如何删除意外请求:GET data.json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!