单元测试。使用$ componentController的组件 - 特别是$ postLink

时间:2017-03-10 14:45:37

标签: javascript angularjs unit-testing angular-components

在我的$ postLink方法中,我在单元测试中手动触发,未定义绑定中的vm / $ ctrl值。

Working Link

Console Error Image

组件规格

angular.module('softwearplayApp')
.component('swImageEditor', {
    templateUrl: 'views/sw-image-editor.html',
    bindings: {
      image: '<',
      close: '&',
      mode: '<',
      save: '&'
    },
    controller: SwImageEditorController
  });

PostLink方法

$ctrl.$postLink = function() {
  console.log($ctrl.image); //<----------- $ctrl.image is defined
  $timeout(function() {
    var img = new Image();

    img.src = $ctrl.image.url; //<--------- $ctrl.image is undefined
    img.classList.toggle('hidden');

    imageContainer = $element[0].querySelector('.image-editor__container');
    cropResultContainer = $element[0].querySelector('.image-editor__crop-result');

    imageContainer.append(img);

    cropper = new Cropper(img, {
      aspectRatio: ASPECT_RATIO[$ctrl.mode]['4/3'],
      ready: function() {
        $ctrl.isLoading = false;
      }
    });
  });
};

刷新$ timeout后,我们传入的绑定变为未定义。

单元测试:

var
    $componentController,
    $timeout,
    $ctrl,
    $rootScope = {},
    LOCALS = {
      $element: {}
    },
    BINDINGS = {
      image: {url: 'abcdef'},
      close: function() {},
      mode: 'landscape',
      save: function() {
      }
    },
    ASPECT_RATIO;

  beforeEach(inject(function(_$rootScope_, $compile, $templateCache, _$componentController_, _ASPECT_RATIO_, _$timeout_) {
    ASPECT_RATIO = _ASPECT_RATIO_;
    $timeout = _$timeout_;
    $componentController = _$componentController_;
    $rootScope = _$rootScope_;
    LOCALS.$scope = $rootScope.$new();
    LOCALS.$element = angular.element('<sw-image-editor></sw-image-editor>');
    LOCALS.$element = $compile(LOCALS.$element)(LOCALS.$scope);
  }));

    it('should define the $postLink', function() {
     $ctrl = $componentController('swImageEditor', LOCALS, BINDINGS);
      $ctrl.$postLink();
      $timeout.flush();
      expect($ctrl.showCroppedImage).toBeTruthy();
      expect($ctrl.isLoading).toBeFalsy();
    });

  });

0 个答案:

没有答案