1

I'm testing my frontend code using qunit and mockjax. The structure of AJAX tests in mockjax's own test code looks like this (jsfiddle):

var testURL = "/test/data",
    testData = { a: 1, b: "c" };

asyncTest("AJAX response test", 1, function() {
    $.mockjax({
        url: testURL,
        responseText : JSON.stringify(testData)
    });

    $.ajax({
        url: testURL,
        dataType: "json",
        success: function(data) {
            deepEqual(data, testData, 'AJAX response is OK');
        },
        complete: function() {
            start();
        }
    });

    $.mockjaxClear();
});

According to the mockjax documentation:

* $.mockjaxClear() 
    Removes all mockjax handlers.

What I don't understand is why mockjaxClear is called right after the $.ajax() call. The problem is if it does some sort of cleanup, as the documentation says, this cleanup will run before the AJAX response arrives (pls. see the console of this jsfiddle). It seems more logical for me to do the cleanup in the handler of the complete event. Can anyone explain me why it is better to call mockjaxClear after $.ajax()?

4

2 回答 2

3

如果你看一下代码,你会发现清理不会影响已经“运行”的调用。它只是确保任何后续$.ajax()都将调用 jQuery 的原始方法,并清除其他内部状态(但同样,不影响已经挂起的“请求”)。

这可能有助于确保$.ajax()被测调用 test 只发送一次(如果发送更多,它们将失败,而且该start()方法将被再次调用,向 Qunit 报告错误)。

也可能只是为了保持代码干净(回调处理程序中的内容更少)。

于 2013-09-13T13:32:50.520 回答
2

$.mockjaxClear我认为您实际上不应该在测试中的任何地方运行。QUnit 为在模块中运行的测试提供了生命周期钩子,在这种情况下重要的是拆解。

http://api.qunitjs.com/module/

使用它,您的代码应该类似于

module( "myapi", {
    teardown: function() {
        $.mockjaxClear();
    }
});

asyncTest( "sometest", function() {
    // test definition
});

如果您愿意,您甚至可以将您的模拟设置移动到setup生命周期挂钩中,以使您的实际测试代码更加紧凑,并且只关注测试本身,而不是设置/拆卸。

于 2013-09-16T04:59:02.800 回答