在QUnit测试中设置$(this)的范围

|| 您如何在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\'\");
});
    
已邀请:
        我认为,您可能想使用
.trigger()
来触发按钮上的'click \'然后检查值,而不是直接调用您的回调函数,当单独调用该函数时,回调函数的作用域不限于按钮的
this
$(\"#button\").trigger(\"click\");
    
        我在QUnit中不知道,但是在Javascript中,您通常是这样的:
func.apply((this), [arguments]);
例如
function foo(x) { return this + x; }

foo.apply(1, [2]) == 3
所以我会尝试
APP.callback.apply(whateverYouWantForThis);
    

要回复问题请先登录注册