2013-02-08 51 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

相关问题