aza*_*arp 14 javascript ajax jquery unit-testing qunit
我正在研究QUnit for JavaScript单元测试.我在一个奇怪的情况下,我正在检查从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");
});
});
Run Code Online (Sandbox Code Playgroud)
但它最终总是在传递.这是进行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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
aza*_*arp 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();
});
});
Run Code Online (Sandbox Code Playgroud)
Goy*_*uix 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"); }
});
});
Run Code Online (Sandbox Code Playgroud)
即便如此,最好的方法是允许异步行为并使用正确的测试方法调用:asyncTest().根据文档" 异步测试排队并一个接一个地运行.相当于调用正常测试()并立即调用stop(). "
asyncTest("a test", function() {
$.ajax({
url: 'Sample.asmx/Service',
success: function(d,s,x) {
ok(true, "asynchronous PASS!");
start();
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10250 次 |
| 最近记录: |