angularjsjasminehttpbackend

Unsure on how to successfully test this function using $httBackend


This is the function in the controller:

var vm = this;
vm.getData = getData;

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

and this is my (stripped down) test file:

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

I would like to test that the result if calling getData() return the correct data.

Currently I'm getting the error $http.get is not a function. Setting a breakpoint in my function shows that http is stubbed with $httpBackend though.

I think there is something fundamental I'm not grasping - any pointers would be greatly appreciated.


Solution

  • You shouldn't have to create the controller with:

    $http: $httpBackend  
    

    to mock the backend. $httpBackend will mock the request itself already.

    Further the test and assertion is done in the wrong order:

    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