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'");
});
4

2 回答 2

3

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

$("#button").trigger("click");
于 2011-06-15T13:55:57.573 回答
1

我不知道在 QUnit 中,但在一般的 Javascript 中,你会这样做:

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

例如

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

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

所以我会尝试

APP.callback.apply(whateverYouWantForThis);
于 2011-06-15T13:59:14.360 回答