2013-02-08 16 views
1

使用Qunit和MockJax,我試圖進行兩個測試,爲便於理解,此處簡化。以下兩個測試中的一個失敗,可能是因爲兩個測試並行運行,因此它們不會各自繞道$.ajax()。 (唯一的區別是每個responseText。)任何想法,以調整它,以便下面的測試通過?Mockjax在相同的測試文件中兩次?

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

回答

3

您必須在每個測試(例如,在您的模塊teardown()方法)的末尾調用$.mockjaxClear()。這破壞了模擬併爲下一次測試準備了環境。

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

}); 

請參閱your adapted example on jsFiddle

+0

在你的例子中,不能$ .mockjaxClear()在回調之前執行,從而毀了模擬? – 2013-02-21 21:36:42

+0

@PatrickSzalapski是的,你是絕對正確的。我更新了我的代碼,並將該調用放到模塊的「teardown」中的'$ .mockjaxClear()'中。這實際上是在測試後執行的。在更新的jsFiddle中,我模擬了你描述的情況(使用'setTimeout()'推遲調用)。 – Odi 2013-02-21 23:16:32

相關問題