单元测试$ http调用内部服务

时间:2016-10-19 11:20:54

标签: angularjs karma-jasmine

我正在尝试在服务中测试$http个调用,在$http响应时,将响应数据存储在服务本身(不会向控制器返回响应)。我发现的大多数示例(甚至是AngularJs文档)都在控制器中测试$http次调用。例如:

app.factory('dataFactory', function($http){
  return {
    getData: function(){
      return $http.get('https://some-url');
    }
  }
});

app.controller('MainCtrl', function($scope, dataFactory, $http) {
  $scope.name = 'World';

  dataFactory.getData().success(function(data){
    $scope.data = data;
  })
});

此代码的单元测试是:

describe('with httpBackend', function() {
    beforeEach(inject(function($controller, $rootScope, $httpBackend) {
      $scope = $rootScope.$new();

      $httpBackend.when('GET', 'https://some-url')
        .respond({things: 'and stuff'});

      MainCtrl = $controller('MainCtrl', { $scope: $scope });
      $httpBackend.flush();
    }));

    it('should set data to "things and stuff"', function() {
      expect($scope.data).toEqual({
        things: 'and stuff'
      });
    });
});

但是在我的服务中,我正在以下列方式打电话:

app.service('dataService', function($http) {

    var self = this;

    this.getData = function() {
        $http.get('https://some-url/')
        .then(
            function success(response) {
                self.data = response.data
            },
            function error(msg) {
                console.log(msg);
            }
        );
    };

});

为此,我需要对服务进行单元测试,而不是控制器。

编辑:下面是我写过的单元测试(已通过,但不确定它是否正确):

describe('.getData()', function() {
    beforeEach(inject(function($httpBackend) {
        $httpBackend.when('GET', 'https://some-url/')
            .respond({data: 'sample data'});
        dataService.getData();
        $httpBackend.flush();
    }));
    it('should store data correctly', function() {
        expect(dataService.data).toEqual({data: 'sample data'});
    });
});

需要一些关于单元测试方法的帮助,我应该遵循使用$ http调用(和存储数据)来测试服务。

0 个答案:

没有答案
相关问题