如何在Quit中模拟.load函数

How to mock-up the .load function in Qunit?

本文关键字:模拟 load 函数 Quit      更新时间:2023-09-26

我有一个javascript函数要测试,它包含.load

function getPane(divId) {
    $("#" + divId).load(
                    "Pane.html",
                    function () {
                        //do some work here
                        });
                    });
}

我想用Quit测试一下,但我不知道如何嘲笑这种行为。

我也不知道如何模拟一个同时具有.load和.get-的函数

 function getPane(divId) {
    $("#" + divId).load("Pane.html", function () {
            $.get("/Config/Pane", function (data) {
                //do work here
                }
            });
        });
    }

我只使用QUnit,没有Mockjax或Sinon.js或任何东西(我知道,我知道我应该这样做)。如有任何帮助,我们将不胜感激。谢谢

由于OP建议他们可以使用Mockjax,我想我应该添加那个解决方案。请注意,我在一个设置方法中添加了mock,然后将其拆下。这允许每个测试都是幂等的。此外,getPane()函数需要回调,以便在测试中添加断言。

function getPane(divId, cb) {
    $("#" + divId).load("Pane.html", function () {
        $.get("/Config/Pane", function (data) {
            // do work here
            cb(); // callback executed for any additional actions (like tests)
                  // you may want to add some error handling with callback as well
        });
    });
}

然后在qunit测试文件的#qunit-fixture中添加div以将内容放入:

<html>
    ...
    <body>
        <div id="qunit"></div>
        <div id="qunit-fixture">
            <div id="foobar"></div> <!-- our test element -->
        </div>
    ...
    </body>
</html>

现在写你的模拟和测试:

QUnit.module("some tests", {
    setup: function() {
        $.mockjax({
            url: "Pane.html",
            responseText: "<div>Some HTML content</div>"
        });
    },
    teardown: function() {
        $.mockjax.clear(); // new in 1.6
    }
});
QUnit.asyncTest("test it out", function(assert) {
    getPane("foobar", function() {
        assert.equal($("#foobar div").length, 0, "A new div was added to the page!");
        QUnit.start();
    });
});