2013-10-18 37 views
1

我剛開始使用qUnit測試框架,但我堅持了非常奇怪的行爲。我想模擬DOM元素焦點事件,因爲它在我要測試的應用程序中使用。但似乎焦點事件不會傳播到訂閱的對象。例如,我有這個簡單的代碼片段:jQuery焦點事件似乎無法在qUnit測試中工作

$("#myinput").on("focus",function() 
{ 
    $("#myinput").val("focus triggered"); 
}); 
$("#myinput").trigger("focus"); 

這個工作在簡單的JavaScript文件罰款,的jsfiddle here。但是當我嘗試在qUnit測試函數中運行類似的代碼時,焦點事件處理程序從不會被調用。我qUnit測試看起來是這樣的:

test("trigger test", function() 
{ 
    expect(1); 
    $("#customerInput").on("focus", function() 
    { 
     ok(true, "focus trigerred"); 
    }); 
    $("#customerInput").focus(); 
}); 

但是OK功能,不會被調用測試總是失敗,因爲它期望一個斷言。有沒有解決方案如何模擬qUnit測試中的火災焦點事件?

編輯

我試圖觸發並捕獲自定義事件,可以說$("#customerInput").trigger("myevent")$("#customerInput").on("myevent", function() {...})和noow它的工作原理。這意味着問題直接與焦點事件有關。

+0

一些限制可能是.. – Stphane

+0

當dom準備就緒時,您確定您的測試正在運行嗎? http://jsfiddle.net/tarabyte/CHEha/1/適合我。檢查'console.log($(「#customerInput」).length);'如果這不是0. –

+0

我在jQuery DOM ready函數中調用所有測試函數。它很奇怪。我還發現了另一個奇怪的行爲,請參閱我的更新。 –

回答

4

我實現了這個使用jQuery的trigger()功能:

var focusEvent = $.Event("focus"), 
    $input = $('#id-of-input-to-focus-on'); 

$input.trigger(focusEvent); 

這使得那些專注於一個文本輸入字段時,例如觸發JavaScript函數的測試。

用於測試用戶交互的QUnit文檔是here

相關問題