我正在尝试使用 $ httpBackend 来测试我的$ http请求..我上传
此错误
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(); ,那么我的测试通过了,我能够删除此错误。 我的问题为何发生此错误?如果无法在控制器中使用该功能,那么测试此功能的用途是什么?
答案 0 :(得分:0)
在初始化控制器时,因为您正在调用$scope.getData()
,系统会提取data.json
。因此,在测试中初始化控制器时,每次初始化控制器时都必须模拟该请求。
克服这种情况的一种方法是使用此控制器将ng-init="getData()"
添加到html元素,以便仅在html请求时提取数据,而不是在初始化控制器时。