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

时间:2011-06-15 13:50:57

标签: javascript jquery qunit

如何在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'");
});

2 个答案:

答案 0 :(得分:3)

我认为,您可能希望使用.trigger()触发“点击”按钮,然后检查值,而不是直接调用您的回调函数,该函数不会限定为按钮的this独立调用时。

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

答案 1 :(得分:1)

我在QUnit中不知道,但在Javascript中你通常会这样做:

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

例如

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

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

所以我会尝试

APP.callback.apply(whateverYouWantForThis);
相关问题