简体   繁体   English

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

[英]Setting scope for $(this) in QUnit tests

How do you setup correct scoping in a QUnit test environment for testing callback functions? 您如何在QUnit测试环境中设置正确的作用域以测试回调函数?

Code to test: 要测试的代码:

<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 code: 测试代码:

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

我想,你可能需要使用.trigger()来触发“点击”按钮,然后检查值,而不是直接调用回调函数,它不会作用域按钮的this时候独立地调用。

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

I don't know about in QUnit, but in Javascript in general you do it like this: 我在QUnit中不知道,但是在Javascript中,您通常是这样的:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM