不确定如何使用 $httBackend 成功测试此功能

Unsure on how to successfully test this function using $httBackend

这是控制器中的函数:

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() return 正确的数据,我想测试结果。

目前我收到错误 $http.get is not a function。在我的函数中设置断点表明 http 已被 $httpBackend 存根。

我认为有一些基本的东西我没有掌握 - 任何指点将不胜感激。

您不必创建控制器:

$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