单元测试Angular指令访问外部元素

Tru*_*ill 6 unit-testing angularjs angularjs-directive

我有一个自定义指令,它使用一个属性来指定它修改的另一个控件.

指令定义对象:

{
    restrict: 'E',
    templateUrl: 'myTemplate.html',
    scope: {
        targetId: '@'
    },
    controller: MyController,
    controllerAs: 'vm',
    bindToController: true
}
Run Code Online (Sandbox Code Playgroud)

指令控制器上的函数修改目标元素的内容(输入字段):

function onSelection (value) {
    var $element = $('#' + vm.targetId);

    $element.val('calculated stuff');
    $element.trigger('input');
}
Run Code Online (Sandbox Code Playgroud)

单元测试(Jasmine/Karma/PhantomJS)当前将元素附加到页面.这有效,但它似乎是一种代码味道.

beforeEach(inject(function($rootScope, $compile) {
    var elementHtml = '<my-directive target-id="bar"></my-directive>' +
        '<input type="text" id="bar">';

    scope = $rootScope.$new();    
    angularElement = angular.element(elementHtml);
    angularElement.appendTo(document.body);  // HELP ME KILL THIS!
    element = $compile(angularElement)(scope);
    scope.$digest();
}));

afterEach(function () {
    angularElement.remove();  // HELP ME KILL THIS!
});
Run Code Online (Sandbox Code Playgroud)

我试过重写控制器函数以避免jQuery; 这没有用.

如何修改指令或测试以消除appendTo/remove?

mor*_*och 2

最好的选择是将指令迁移到属性而不是元素。这消除了对属性的需要target-id,并且您不需要寻找目标元素。

请参阅http://jsfiddle.net/morloch/621rp33L/

指示

angular.module('testApp', [])
  .directive('myDirective', function() {
    var targetElement;
    function MyController() {
      var vm = this;
      vm.onSelection = function() {
        targetElement.val('calculated stuff');
        targetElement.trigger('input');
      }
    }
    return {
      template: '<div></div>',
      restrict: 'A',
      scope: {
        targetId: '@'
      },
      link: function postLink(scope, element, attrs) {
        targetElement = element;
      },
      controller: MyController,
      controllerAs: 'vm',
      bindToController: true
    };
  });
Run Code Online (Sandbox Code Playgroud)

测试

describe('Directive: myDirective', function() {
  // load the directive's module
  beforeEach(module('testApp'));

  var element, controller, scope;

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    element = angular.element('<input my-directive type="text" id="bar">');
    $compile(element)(scope);
    scope.$digest();
    controller = element.controller('myDirective');
  }));

  it('should have an empty val', inject(function() {
    expect(element.val()).toBe('');
  }));

  it('should have a calculated val after select', inject(function() {
    controller.onSelection();
    expect(element.val()).toBe('calculated stuff');
  }));
});
Run Code Online (Sandbox Code Playgroud)