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

时间:2015-11-25 01:59:47

标签: javascript angularjs unit-testing jasmine karma-jasmine

对如何将$ 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');
    });
  }

1 个答案:

答案 0 :(得分:1)

<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="@dimen/toolbar_height" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <RelativeLayout .... </RelativeLayout> </android.support.v7.widget.Toolbar> 不会同步返回结果。要从待处理的$httpBackend请求中获取响应,请使用$httpBackend方法:

$httpBackend.flush()

请确保... vm.getData(callbackFn); $httpBackend.flush(); $rootScope.$digest(); expect(whatAmI).toEqual('boom'); ... 功能范围内的$httpBackend可用