如何在 angular js 中测试 $http 调用? [英] how to test $http call in angular js?
问题描述
我正在尝试使用 karma 和 jasmine 测试我的 $http 请求.我制作了一个控制器并注入了一个服务.在服务中,我调用了 $http 服务.我需要测试该服务,我将如何测试这个服务,这是我的控制器.
I am trying to test my $http request using karma and jasmine.I make one controller and inject a service .In service I call $http service.I need to test that service how I will test this service this is my controller.
angular.module('app',[]).controller('first',function($scope,data){
$scope.name='test';
data.getData().then(function(data){
console.log(data);
})
}).factory('data',function($http){
return{
getData:getData
}
function getData(){
return $http.get('data.json').success(successCall).error(errorcallback)
}
function successCall(data){
return data
}
function errorcallback(data){
return data
}
})
这里是plunkerhttp://plnkr.co/edit/POryyDUc8bvvfvI5Oap7?p=preview
我是这样开始的
describe('http controller test', function () {
var $rootScope,
$scope,
controller;
beforeEach(function(){
module('app') ;
inject(function($injector){
$rootScope = $injector.get('$rootScope') ;
$scope=$rootScope.$new();
controller =$injector.get('$controller')('first',{$scope:$scope})
})
})
describe('Init value',function(){
it('check name value',function(){
expect($scope.name).toEqual('test');
})
})
it('it should be true',function(){
expect(true).toBeTruthy();
})
})
你能告诉我当控制器中存在服务依赖时如何编写测试吗??如何在 jasmine 中测试 $http 请求?在我的控制器中有一个服务的依赖项.如何将它注入我的测试文件中?
could you please tell me how to write test when there is dependency of service in controller ?? how to test $http request in jasmine?in my controller there is a dependency of a service .how to inject this in my test file?
推荐答案
你可以通过这种方式注入 data
服务:
You can inject the data
service this way:
describe('http controller test', function () {
var $rootScope,
$scope,
data,
controller;
beforeEach(module('app'));
beforeEach(inject(function ($controller, $rootScope, $state, _data_) {
scope = $rootScope.$new();
state = $state;
data = _data_;
controller = $controller('first',{$scope:$scope});
});
it('data service should be defined',function(){
expect(data).toBeDefined();
});
});
有一个关于使用 Angular 和 Jasmine 测试承诺的例子这里 和关于使用 $ 在 此处 测试 $http 承诺的示例http后端.
There is an example regarding testing promises using Angular and Jasmine here and an example regarding testing $http promises here using $httpBackend.
这篇关于如何在 angular js 中测试 $http 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!