2

注:建議的環節是回答有關服務的問題,並沒有就如何解決這個問題AngularJS:如何測試指向哪個元素的焦點?

我試圖建立一個業力測試我的一個簡單明確的解釋(和工作)AngularJS autofocus指令:

app.directive('autofocus', function ($timeout) { 
    return { 
    replace: false, 
    link: function (scope, element, attr) { 
     scope.$watch(attr.autofocus, 
     function (value) { 
      if (value) { 
      $timeout(function() { 
       element[0].focus(); 
       console.log('focus called'); 
      }); 
      } 
     } 
    ); 
    } 
    }; 
}); 

這是我目前的測試:

describe('The autofocus directive', function() { 
    var timeout; 
    beforeEach(module('myApp')); 
    beforeEach(inject(function($timeout) { 
    timeout = $timeout; 
    })); 

    it('should set focus to first autofocus element', function() { 
    var form = angular.element('<form />'); 
    var input1 = angular.element('<input type="text" name="first" />'); 
    var input2 = angular.element('<input type="text" name="second" autofocus="true" />'); 
    form.append(input1); 
    form.append(input2); 
    spyOn(input2[0], 'focus'); 
    timeout.flush(); 
    expect(input2[0].focus).toHaveBeenCalled(); 
    }); 

這是失敗)從輸出( 10:

$ node_modules /人緣/斌/因緣開始測試/ karma.conf.js
INFO [人緣]:噶v0.12.23服務器開始在http://本地主機:8080/
INFO [發射]:啓動瀏覽器PhantomJS
INFO [PhantomJS 1.9.8(Linux)的]:連接於插座U34UATs8jZDPB74AXpqR ID爲96802943個
PhantomJS 1.9.8(Linux)的:執行的20 SUCCESS的0(0秒/ 0秒)
PhantomJS 1.9.8(Linux)自動對焦指令應該將焦點設置爲第一個自動對焦元素FAILED
預計的間諜焦點已被調用。
PhantomJS 1.9.8(Linux)的:執行的20的20(1 FAILED)(0.156秒/ 0.146秒)


只是添加

input[0].focus(); 

spyOn(input[0], 'focus')後測試成功,當然,但它不是我想要的...


最後一個問題是:我如何karma測試一個指令,將焦點設置爲一個元素?

+0

可能重複[如何測試焦點AngularJS?](http://stackoverflow.com/questions/24196072/how -to-test-focus-in-angularjs) – glepretre 2014-10-30 08:12:15

+0

這個問題是針對服務的,對我來說答案不是那麼清楚...... :-( – MarcoS 2014-10-30 09:34:45

+0

把它扔到jsfiddle中?如果可以的話,更容易處理看到它失敗 – deitch 2014-10-30 09:40:22

回答

5

當您僅在單元​​測試中調用angular.element時,Angular將不理解「自動聚焦」是指令。因此,在你的代碼:

var form = angular.element('<form />'); 
var input1 = angular.element('<input type="text" name="first" />'); 
var input2 = angular.element('<input type="text" name="second" autofocus="true" />'); 
form.append(input1); 
form.append(input2); 

角將不設置自動聚焦的指令,並不會指派有關你已經宣佈了「自動對焦」指令anythings。 爲了在單元測試中做到這一點,你必須使用$ compile來爲它指定一個範圍。 您可以更換小提琴來通過測試:

http://jsfiddle.net/ksqhmkqm/1/

正如你所看到的,我創建了一個新的範圍

scope = $rootScope.$new(); 

並創建一個新的模板

element = angular.element('<form><input type="text" name="first" /><input type="text" name="second" autofocus="true" /></form>'); 

和創建的範圍分配給該新模板

$compile(element)(scope); 
scope.$digest(); 

通過這種方式,angular會理解「自動對焦」是一個指令,並將您創建的所有事件都分配給該「自動對焦」正在處理的元素。

的焦點事件,我按照這個基準測試:

How do I check if my element has been focussed in a unit test