Angularjs 如何调用$http请求
我正在尝试制作一个$http请求的演示,并测试该服务。我喜欢这样Angularjs 如何调用$http请求,angularjs,angularjs-directive,angularjs-scope,jasmine,karma-jasmine,Angularjs,Angularjs Directive,Angularjs Scope,Jasmine,Karma Jasmine,我正在尝试制作一个$http请求的演示,并测试该服务。我喜欢这样 .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.stri
.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'
}
}
}
})
我从json文件中加载数据并在视图中显示。但当我尝试测试该应用程序时,我发现了错误,为什么?如何删除该错误
beforeEach(inject(function($rootScope,$controller,appfactory,_$httpBackend_) {
$scope = $rootScope.$new();
$httpBackend=_$httpBackend_;
createController = function() {
return $controller('cntrl', {'$scope' : $scope });
};
}));
it("tracks that the spy was called", function() {
var response=[{"name":"naveen"},{"name":"parveen"}]
$httpBackend.expectGET('data.json').respond(response);
var controller = createController();
$scope.getData();
$httpBackend.flush();
expect($scope.data[0].name).toEqual('naveen')
});
})
这是我的密码
获取数据的http调用实际上在测试中被调用了两次。一个是控制器初始化时(因为您正在调用
$scope.getData()
),第二个是在规范中手动调用$scope.getData()
时
您的期望只会被模仿一次(在控制器初始化之前)。要修复测试(模拟控制器实际执行的操作),必须在调用$scope.getData()
之前再次设置期望值
见普朗克:
或
您可以将
expectGET
替换为whenGET
,如果未调用资源,则不会使测试失败。但是,由于您期望的是expect($scope.data[0].name.).toEqual('naveen')
其中的'naveen'来自http响应,所以这种更改应该是可以的。@claies我的问题不同。。!!有何不同?在此代码中,您从未提供whenGET
。哦,明白了。。!!解决我的问题。这篇文章相关吗?