2014-09-02 105 views
1

最近我正在尝试编写指令的测试用例。如何通过编写测试用例来测试指令?

例如,这是一个在浏览器中处理DOM的指令。

var demoApp = module('demoApp', ['']); 
demoApp.directive('tabTo', function(){ 
    var linkFunc = function(scope, element, attrs, controllers){ 
     element.bind('keyup', function(e){ 
      var maxLength = attrs['maxlength'] || attrs['ng-maxlength']; 
      if(maxLength && this.value.length === length){ 
       var tabTarget = angular.element.find('#' + attrs['tab-to']); 
       if(tabTarget){ 
        tabTarget.focus(); 
       } 
      }   

     } 
    } 
    return { 
     restrict: 'A', 
     link: linkFunc  
    }  

}); 

然后我在这里实现的测试用例:

describe('Unit testing great quotes', function() { 
    var $compile; 
    var $rootScope; 

    beforeEach(module('myAppdemoApp')); 
    beforeEach(inject(function(_$compile_, _$rootScope_){ 

     $compile = _$compile_; 
     $rootScope = _$rootScope_; 
    })); 

    it('Replaces the element with the appropriate content', function() { 
     var element = $compile('<input type="text" maxlength="8" id="input1" tab-to="input2" /><input type="text" id="input2" maxlength="8" tab-to="input3"/> <input type="text" id="input3" max-length="8" />')($rootScope); 
     element.appendTo(document.body); //appendTo to document so that in directive can find it by 'angular.element.find()' 
     $rootScope.$digest(); 

     var tmpInputs = angular.element.find('#input1'); 
     var input1 = tmpInputs[0]; 

     tmpInputs = angular.element.find('#input2'); 
     var input2 = tmpInputs[0]; 

     spyOn(input2, 'focus'); 

     input1.val('12345678'); 
     input1.keyup(); 

     expect(input2.focus).haveBeenCalled(); 

    }); 
}); 

我的问题是,它编写测试用例的正确方法?因为我对单元测试不太了解。 我刚刚和我的同事谈过了,他告诉我这看起来像是端到端的测试。那么这是否意味着要测试指令,我们必须编写端到端测试?

有人能帮助我吗? Thx很多...

回答

1

你的指令操纵DOM(焦点,绑定)。所以在你的测试中,你可以简单地检查DOM是否以预期的方式发生了变化。你不需要端到端的测试。我会说你的测试有点太大了。我认为你不需要spyOnappendTo,只是:

  1. 使用$compile与指令建立DOM
  2. 的范围和/或DOM更改属性触发预期的指令行为
  3. 触发角(如scope.$apply()
  4. 验证DOM

,你可以在这里找到样本:http://blog.piotrturski.net/2014/11/nesting-angular-directives.html

+0

虽然我在6个月前得到了这个,但是,thx为您的答案。 :) – 2015-04-26 13:26:47