如何使用 Angular 对具有承诺和回调函数的函数进行单元测试

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

对于如何将 $httpBackend 和 promises 与单元测试结合起来有些困惑。我要测试的功能(在控制器中)是:

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

失败的测试看起来像这样...

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

$httpBackend 不会 return 同步结果。要从待处理的 $httpBackend 请求中获得响应,应使用 $httpBackend.flush() 方法:

...
vm.getData(callbackFn);

$httpBackend.flush();

$rootScope.$digest();

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

只需确保 $httpBackendit 函数的范围内可用