开发者

Setting scope for $(this) in QUnit tests

开发者 https://www.devze.com 2023-03-13 16:10 出处:网络
How do you setup correct scoping in a QUnit test environment for testing callback functions? Code to test:

How do you setup correct scoping in a QUnit test environment for testing callback functions?

Code to test:

<script type="text/javascript">
    APP = {};
    APP.callBack = functio开发者_开发技巧n() {
        $(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 code:

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


I think, you might want to use .trigger() to trigger 'click' on button and then check the values, instead of directly calling your callback function, which would not be scoped to the button's this when called independently.

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


I don't know about in QUnit, but in Javascript in general you do it like this:

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

for example

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

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

so I would try

APP.callback.apply(whateverYouWantForThis);
0

精彩评论

暂无评论...
验证码 换一张
取 消