我正在研究用于JavaScript单元测试的QUnit。我在一个奇怪的情况下,我正在检查从Ajax调用返回的值。
对于以下测试,我故意试图让它失败。
// test to check if the persons are returned!
test("getPersons", function() {
getPersons(function(response) {
// persons = $.evalJSON(response.d);
equals("boo", "Foo", "The name is valid");
});
});
但它总是一直在传递。这是进行Ajax调用的getPersons方法。
function getPersons(callback) {
var persons = null;
$.ajax({
type: "POST",
dataType: "json",
data: {},
contentType: "application/json",
url: "AjaxService.asmx/GetPersons",
success: function(response) {
callback(response);
}
});
}
答案 0 :(得分:25)
启动和停止使用QUnit库似乎正在运行!
// test to check if the persons are returned!
test("getPersons", function() {
stop();
getPersons(function(response) {
persons = $.evalJSON(response.d);
equals(persons[0].FirstName, "Mohammad");
start();
});
});
答案 1 :(得分:13)
这里真正的问题是不需要调用start()和stop()方法 - 事实上,如果你不小心在回调结束时再次调用stop(),你可能会遇到麻烦如果你有其他.ajax()方法。这意味着你发现自己处于一些混乱的状态,如果所有的回调都被触发,就必须跟踪,知道你是否还需要再次调用stop()。
问题的根源涉及异步请求的默认行为 - 简单的解决方案是通过将 async 属性设置为false来使.ajax()请求同步发生:
test("synchronous test", function() {
$.ajax({
url:'Sample.asmx/Service',
async:false,
success: function(d,s,x) { ok(true, "Called synchronously"); }
});
});
即便如此,最好的方法是允许异步行为并使用正确的测试方法调用: asyncTest() 。根据文档“异步测试排队并一个接一个地运行。相当于调用正常测试()并立即调用stop()。”
asyncTest("a test", function() {
$.ajax({
url: 'Sample.asmx/Service',
success: function(d,s,x) {
ok(true, "asynchronous PASS!");
start();
}
});
});
答案 2 :(得分:3)
我的项目中有很多qunit测试。像:
module("comment");
asyncTest("comment1", function() {
expect(6);
$.ajax({
url: 'http://xxx.com/comment',
dataType: "json",
type: "GET",
timeout: 1000
}).done(function(data) {
ok(true, "loaded");
ok(data.data.length>1, "array size");
ok(data.total, "attr total");
var c = data.data[0];
ok(c.id, "attr c.id");
ok(c.user_id, "attr c.user_id");
ok(c.type == 4, "attr c.type equal 4");
}).fail(function(x, text, thrown) {
ok(false, "ajax failed: " + text);
}).always(function(){
start();
});
});
答案 3 :(得分:2)
我用ajax做了一些qunit测试。它不漂亮。我可以带来的最好的事情是在ajax被触发时停止测试,并在成功回调中再次启动它。 (使用start()和stop())方法。这意味着一次一个ajax请求,但我可以忍受。祝你好运