0

Bit stumped on how to combine $httpBackend and promises with unit tests. The function I'm trying to test (in a controller) is:

  vm.getData = (callback) => {
    $http.get('http://localhost:3000/cars?_start=0&_end=100').then(result => {
      return callback(result.data);
    });
  };

The test that's failing looks something like this...

  describe('controllerToTest', () => {
    beforeEach(() => {
      angular.module('test', [])
      .controller('controllerToTest', require('./controllerToTest'));
    });

    beforeEach(angular.mock.module('test'));

    beforeEach(angular.mock.inject($injector => {
      $rootScope = $injector.get('$rootScope').$new(true);
      $q = $injector.get('$q').defer();
      $httpBackend = $injector.get('$httpBackend');
      $httpBackend.when("GET", "http://localhost:3000/cars?_start=0&_end=100").respond({});
      vm = $injector.get('$controller')('controllerToTest', {});
    }));


    it('should return the callback function', () => {
      let whatAmI = null;
      let callbackFn = () => {
        whatAmI = 'boom'
      };

      $q.resolve(
        (x) => {
          return x();
        }
      );

      vm.getData(callbackFn);

      $rootScope.$digest();

      expect(whatAmI).toEqual('boom');
    });
  }

1 Answer 1

1

$httpBackend doesn't return result synchronously. To get response from pending $httpBackend requests $httpBackend.flush() method should be used:

...
vm.getData(callbackFn);

$httpBackend.flush();

$rootScope.$digest();

expect(whatAmI).toEqual('boom');
...

Just make sure $httpBackend is available in it function's scope

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.