2014-09-02 135 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

相關問題