質問

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()?

役に立ちましたか?

解決

If you take a look at the code, you will see that the cleanup does not affect already "running" calls. It just makes sure that any subsequent $.ajax() will call jQuery's original method and that other internal state (but again, not affecting already pending "requests") is cleaned.

This may help to ensure that the $.ajax() call under test test is only sent once (if more are sent they will fail, moreover the start() method will be called again, reporting the error to Qunit).

It could also be this way just to keep code clean (less stuff in the callback handlers).

他のヒント

I don't think you should be running $.mockjaxClear anywhere in your tests actually. QUnit provides lifecycle hooks for tests run within a module, the important one being teardown in this case.

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

Using that, your code should be something like

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

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

If you wanted to, you could even move your mock setups into the setup lifecycle hook to make your actual test code more compact and focused just on the test itself, not setup/teardown.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top