【问题标题】:how to test $http call in angular js?如何在 Angular js 中测试 $http 调用?
【发布时间】:2015-12-18 15:36:04
【问题描述】:

我正在尝试使用 karma 和 jasmine 测试我的 $http 请求。我制作了一个控制器并注入了一项服务。在服务中我调用 $http 服务。我需要如何测试该服务测试这个服务这是我的控制器。

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
    }
})

这里是笨蛋 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 请求?在我的控制器中有一个服务的依赖项。如何在我的测试文件中注入它?

【问题讨论】:

标签: angularjs angularjs-directive angularjs-scope jasmine karma-jasmine


【解决方案1】:

您可以通过这种方式注入data 服务:

 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 here 测试 Promise 的示例和一个关于使用 $httpBackend 测试 $http Promise here 的示例。

【讨论】:

  • 有没有在线测试编辑器来测试这个?我正在研究有 $httpbackend 吗?我们可以使用那个 httpbackend 吗?
  • 多次看到这个茉莉花关键字 spyOn spyOn ...?那是什么
  • 如果 $http 请求需要 httpbackend 和 spyOn 为什么不使用
【解决方案2】:

$httpbackend 是你需要的。

API Reference / ngMock / service components in ngMock / $httpBackend

这是来自该页面的 sn-p。

    describe('MyController', function() {
   var $httpBackend, $rootScope, createController, authRequestHandler;

   // Set up the module
   beforeEach(module('MyApp'));

   beforeEach(inject(function($injector) {
     // Set up the mock http service responses
     $httpBackend = $injector.get('$httpBackend');
     // backend definition common for all tests
     authRequestHandler = $httpBackend.when('GET', '/auth.py')
                            .respond({userId: 'userX'}, {'A-Token': 'xxx'});

     // Get hold of a scope (i.e. the root scope)
     $rootScope = $injector.get('$rootScope');
     // The $controller service is used to create instances of controllers
     var $controller = $injector.get('$controller');

     createController = function() {
       return $controller('MyController', {'$scope' : $rootScope });
     };
   }));


   afterEach(function() {
     $httpBackend.verifyNoOutstandingExpectation();
     $httpBackend.verifyNoOutstandingRequest();
   });


   it('should fetch authentication token', function() {
     $httpBackend.expectGET('/auth.py');
     var controller = createController();
     $httpBackend.flush();
   });

【讨论】:

    猜你喜欢
    • 2019-05-02
    • 2021-05-18
    • 2018-05-22
    • 2023-03-05
    • 2020-07-25
    • 2015-02-01
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多