2011-06-15 32 views
0

如何在QUnit測試環境中設置測試回調函數的正確範圍?

代碼來測試:

<script type="text/javascript"> 
    APP = {}; 
    APP.callBack = function() { 
     $(this).closest("input").val('foobar'); 
    }; 

    $(function() { 
     $("#button").click(APP.callBack); 
    }); 
</script> 
<div> 
    <a id="button" href="#"></a> 
    <input id="id-for-testing-only" name="test" type="text" value="barfoo" /> 
</div> 

測試代碼:

test("try callback with 'this' scope", function() { 
    APP.callBack(); 
    equals($("#id-for-testing-only").val(), "foobar", "should set value to 'foobar'"); 
}); 

回答

3

我想,你可能需要使用.trigger()觸發「點擊」按鈕,然後檢查值,而不是直接調用你的回調函數,這個函數在被獨立調用時不會被限制在按鈕的this

$("#button").trigger("click"); 
1

我不知道在QUnit,但在Javascript一般你做這樣的:

func.apply((this), [arguments]); 

例如

function foo(x) { return this + x; } 

foo.apply(1, [2]) == 3 

所以我會嘗試

APP.callback.apply(whateverYouWantForThis); 
+0

這是問題的直接解決方案。主要榮譽。然而,@ mahesh-velaga的想法是_this_例子的解決方案。謝謝你們倆! – Sukima 2011-06-15 18:56:17

+0

我同意,他的解決方案在這裏更加相關 – configurator 2011-06-16 15:03:39