我正在尝试设置 Karma 来测试我正在构建的 Angular 应用程序。我已经围绕我的服务和控制器设置了测试,但我发现指令的测试有些复杂。
指令:
angular.module('Directives',[])
  .directive('tooltip', function factory(){
    return {
      link: {
        post: function(scope, $element, instanceAttrs, controller){
          $element.parent().append('<span class="tooltip-wrapper"><aside class="tooltip-container"></aside></span>');
          var $tooltipWrapper = $element.next()
            , $tooltip        = angular.element($tooltipWrapper.children()[0]);
          if(instanceAttrs.icon){
            $tooltipWrapper.addClass('help icon standalone');
            $element = $tooltipWrapper;
          }
          if(instanceAttrs.position){
            $tooltip.addClass('tooltip-position-' + instanceAttrs.position);
          } else {
            $tooltip.addClass('tooltip-position-bottom-center');
          }
          if(instanceAttrs.position === 'right'){
            $tooltipWrapper.addClass('tooltip-wrapper-right');
          }
          if(typeof instanceAttrs.message === 'undefined'){
            $tooltip.html(instanceAttrs.$$element[0].childNodes[0].data);
            $element.parent().children('tooltip').remove();
          }
          else {
            $tooltip.html(instanceAttrs.message);
          }
          $tooltip.hide();  // <--- this is where the error gets thrown
          $element.on('mouseover', goTooltip);
          function goTooltip(){
            $tooltip.show();
            $element.on('mouseleave', killTooltip);
            $element.off('mouseover');
          }
          function killTooltip(){
            $tooltip.hide();
            $element.off('mouseleave');
            $element.on('mouseover', goTooltip);
          }
        }
      },
      scope: false,
      replace: false,
      restrict:'EA'
    };
  });
考试:
describe("The tooltip", function(){
  var elm
    , scope;
  beforeEach(module("RPMDirectives"));
  beforeEach(inject(function($rootScope, $compile){
    elm = angular.element(
      '<div>' +
        '<a></a>' +
        '<tooltip icon="true" position="bottom-center-left">bar</tooltip>' +
      '</div>' );
    scope = $rootScope;
    $compile(elm)(scope);
    scope.$digest();
  }));
  it('should do something', inject(function($compile, $rootScope){
    expect(elm.find('aside')).toBe('bar');
  }))
});
当我运行测试时,它说 Object [object Object]($tooltip,由指令中的注释指示)没有方法隐藏。当我在浏览器中使用该指令时,该指令工作正常,而 jqlite 肯定有一个 hide 方法,所以我很茫然。我确信我可以通过在测试环境中包含 jquery 来使其工作,但我不想这样做,因为我正在我们的生产应用程序中删除 jquery 以支持 Angular,并在此处证明该场景很关键。