【问题标题】:Why is this directive not finding it's children in unit test为什么这个指令在单元测试中没有找到它的孩子
【发布时间】:2014-04-15 11:18:03
【问题描述】:

指令:

angular.module('uiApp')
  .directive('restMenu', () ->
    templateUrl: 'views/dir_rest_menu.html'
    transclude: true
    restrict: 'E'
    link: (scope, element, attrs) ->
)

查看:

<div class="rest-nav">
  <button>1</button>
  <button>2</button>
  <button>3</button>
</div>

测试:

'use strict'

describe 'Directive: restMenu', () ->

  # load the directive's module
  beforeEach module 'uiApp'

  scope = {}

  beforeEach inject ($controller, $rootScope) ->
    scope = $rootScope.$new()
    element = angular.element '<rest-menu></rest-menu>'

  it 'should have three buttons', inject ($compile) ->
    element = angular.element '<rest-menu></rest-menu>'
    element = $compile(element) scope
    nav = element.find('.rest-nav')
    expect(nav.children().length).toEqual(3)

我也尝试过在已编译元素上寻找子元素。两者都说:

Chrome 31.0.1650 (Linux) Directive: restMenu should have buttons if options are added FAILED
        Expected 0 to be 3.
        Error: Expected 0 to be 3.
            at null.<anonymous> (/home/zeus/Projects/hmc/working/UI/test/spec/directives/rest_menu.js:21:46)
            at Object.invoke (/home/zeus/Projects/hmc/working/UI/app/bower_components/angular/angular.js:3697:17)
            at workFn (/home/zeus/Projects/hmc/working/UI/app/bower_components/angular-mocks/angular-mocks.js:2102:20)
Chrome 31.0.1650 (Linux): Executed 29 of 29 (1 FAILED) (0.762 secs / 0.228 secs)

【问题讨论】:

  • 你有没有想过这个问题?
  • 我遇到了同样的问题,你能帮我解决这个问题吗?

标签: javascript angularjs coffeescript karma-runner directive


【解决方案1】:

虽然测试指令使用 jquery,但它可以轻松执行和模拟来自 jasmine 的指令事件。按照下面的代码sn-p。

describe('Directive: restMenu',function(){
  var rootScope;
  var scope;
  var $body;
  var restMenuHTML= '<rest-menu></rest-menu>';
  var restMenuDirective;
  var restMenuElement;
  var $compile;
beforeEach(module('uiApp')));

 beforeEach(function(){
 inject(function($injector){
     rootScope=$injector.get('$rootScope');
     scope=rootScope.$new();
     $compile=$injector.get('$compile');
     restMenuDirective=$compile(angular.element(restMenuHTML))(scope);
 });
   scope.$digest();
   describe('Test cases for directive:',function(){
       beforeEach(function(){
           $body.append(restMenuDirective); 
         restMenuElement=$('.rest-nav');
       });
       it('Expect directive to be exist in dom',function(){
           expect(restMenuElement.length).toBe(1);
           expect(restMenuElement.children().length).toBe(3);
       });
   });
 });
});

【讨论】:

    【解决方案2】:

    你能去掉 transclude 选项吗?如果这不能解决问题,请在编译元素后尝试设置断点,并检查 element 变量!

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      相关资源
      最近更新 更多