使用 Qunit 和 MockJax,我寻求进行两个测试,为了便于理解,在此处进行了简化。以下两个测试之一失败,大概是因为这两个测试并行运行,因此它们不会各自绕过 $.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();
}
);
});
关于javascript - Mockjax 在同一个测试文件中两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14780749/