如何在角度js中测试$ http调用? [英] how to test $http call in angular js?

查看:257
本文介绍了如何在角度js中测试$ http调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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
    }
})

这里是plunker
http://plnkr.co/edit/POryyDUc8bvvfvI5Oap7?p=preview

here is plunker http://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?

推荐答案

您可以通过以下方式注入数据服务:

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 promises的例子 here 使用$ httpBackend。

There is an example regarding testing promises using Angular and Jasmine here and an example regarding testing $http promises here using $httpBackend.

这篇关于如何在角度js中测试$ http调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆