mardi 24 novembre 2015

How to unit test a function with a promise and callback function with Angular

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

Aucun commentaire:

Enregistrer un commentaire