不确定如何使用$ httBackend

时间:2016-11-30 13:19:28

标签: angularjs jasmine httpbackend

这是控制器中的功能:

var vm = this;
vm.getData = getData;

function getData(val) {
  return $http.get('/get-data', {
    params: {
      query: val
    }
  }).then(function(response) {
    return response.data;
  });
}

这是我的(剥离的)测试文件:

describe('Controller: MyCtrl', function() {
  'use strict';

  var MyCtrl;
  var rootScope;
  var scope;
  var httpMock;

  beforeEach(function() {
    module('MyModule');

    inject(function($controller, $rootScope, $httpBackend) {
      rootScope = $rootScope;
      scope = $rootScope.$new();
      httpMock = $httpBackend;
      MyCtrl = $controller('MyCtrl as vm', {
        $rootScope: rootScope,
        $scope: scope,
        $http: httpMock,
      });
    });
  });

  describe('vm.getData()', function() {
    it('returns the required data', function() {
      httpMock.when('GET', '/get-data?query=test-val').respond(200, {data: 'test-data'});
      httpMock.flush();
      expect(scope.vm.getData('test-val')).toEqual('test-data');
    });
  });
});

如果调用getData()返回正确的数据,我想测试结果。

目前我收到错误$http.get is not a function。在我的函数中设置断点显示http虽然存在$ httpBackend。

我认为有一些基本的东西我没有理解 - 任何指针都会非常感激。

1 个答案:

答案 0 :(得分:0)

您不应该使用以下命令创建控制器:

$http: $httpBackend  

嘲笑后端。 $ httpBackend已经模拟了请求本身。

此外,测试和断言以错误的顺序完成:

httpMock.when('GET', '/get-data?query=test-val').respond(200, {data: 'test-data'});
MyCtrl.getData('test-val').then(function(_result_){ //perform the request
  result = _result_;                                //save the result of the promise
});
httpMock.flush();                                   //execute the request
expect(result).toBe('test-data');                   //assert that the result is as expected