1

QunitとMockJaxを使用して、理解しやすいようにここで簡略化した2つのテストを作成しようとしています。次の2つのテストのいずれかが失敗します。これは、おそらく2つのテストが並行して実行されるため、それぞれが独自の迂回を取得しないためです$.ajax()。(唯一の違いは、それぞれのresponseTextです。)次の両方のテストに合格するように調整するための良い方法についてのアイデアはありますか?

function testAjax() {
    return $.ajax({
        type: 'POST',
        dataType: 'json', 
        url: '/fakeservice/1',
        data: {'a':'b'}
    });
}

asyncTest("testAjax 1", function () {
    $.mockjax({
        url: '/fakeservice/1',
        type: 'POST',
        dataType: 'json',
        responseText: { 'name1': 'foo' }
    });

    testAjax().then(
        function (response) {
            deepEqual(response.name1, 'foo', "no name1");
            start();
        },
        function (error) {
            ok(false, "got AJAX error");
            start(); 
        }
    );
});


asyncTest("testAjax 2", function () {
    $.mockjax({
        url: '/fakeservice/1',
        type: 'POST',
        dataType: 'json',
        responseText: { 'name1': 'bar' }
    });

    testAjax().then(
        function (response) {
            deepEqual(response.name1, "bar", "no name1");
            start();
        },
        function (error) {
            ok(false, "got AJAX error");
            start();
        }
    );
});
4

1 に答える 1

3

各テストの最後に呼び出す必要があります$.mockjaxClear()(たとえば、teardown()モジュールのメソッドで)。これにより、モックが破棄され、次のテストに備えて環境が準備されます。

function testAjax() {
    return $.ajax({
        type: 'POST',
        dataType: 'json', 
        url: '/fakeservice/1',
        data: {'a':'b'}
    });
}

module("AJAX tests", {
    teardown: function() {
        $.mockjaxClear();
    }
});
asyncTest("testAjax 1", function () {
    $.mockjax({
        url: '/fakeservice/1',
        type: 'POST',
        dataType: 'json',
        responseText: { 'name1': 'foo' }
    });

    testAjax().then(
        function (response) {
            deepEqual(response.name1, 'foo', "no name1");
            start();
        },
        function (error) {
            ok(false, "got AJAX error");
            start();
        }
    );
});


asyncTest("testAjax 2", function () {
    $.mockjax({
        url: '/fakeservice/1',
        type: 'POST',
        dataType: 'json',
        responseText: { 'name1': 'bar' }
    });

    testAjax().then(
        function (response) {
            deepEqual(response.name1, "bar", "no name1");
            start();
        },
        function (error) {
            ok(false, "got AJAX error");
            start();
        }
    );

});

jsFiddleで適合例を参照してください。

于 2013-02-12T17:01:21.090 に答える