Javascript 在同一测试文件中模拟JAX两次?
使用Qunit和MockJax,我试图进行两个测试,为了便于理解,在这里进行了简化。以下两个测试中的一个失败,可能是因为这两个测试并行运行,因此它们没有各自绕行Javascript 在同一测试文件中模拟JAX两次?,javascript,unit-testing,qunit,mockjax,Javascript,Unit Testing,Qunit,Mockjax,使用Qunit和MockJax,我试图进行两个测试,为了便于理解,在这里进行了简化。以下两个测试中的一个失败,可能是因为这两个测试并行运行,因此它们没有各自绕行$.ajax()。(唯一的区别是每个测试中的responseText。)有什么好办法可以调整它,使下面两个测试都通过吗 function testAjax() { return $.ajax({ type: 'POST', dataType: 'json', url: '/fake
$.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();
}
);
});
您必须在每个测试结束时调用
$.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();
}
);
});
请参见。在您的示例中,$.mockjaxClear()不能在回调之前执行,从而破坏模拟吗?@PatrickSzalapski是的,您完全正确。我更新了我的代码,并将对
$.mockjaxClear()
的调用放在模块的拆卸中。这实际上是在测试之后执行的。在更新的JSFIDLE中,我模拟了您描述的情况(使用setTimeout()
延迟调用)。