我在Mockjax文档中看到了这个例子:
$.mockjax({
url: "/rest",
data: function ( json ) {
assert.deepEqual( JSON.parse(json), expected ); // QUnit example.
return true;
}
});
但我不确定如何将它与QUnit测试方法一起使用。 有任何想法吗?
我尝试了这个,但它说它至少有一个断言,好像它根本没有运行它,断言行:
QUnit.test("mockjax test", function (assert) {
$.mockjax({
url: "/restful/fortune",
data: function (json) {
assert.deepEqual(JSON.parse(json), expected); // QUnit example.
return true;
},
responseText: {
status: "success",
fortune: "Are you a mock turtle?"
}
});
});
答案 0 :(得分:2)
你很接近,但是Mockjax模仿了Ajax请求的异步性质,这意味着你需要tell QUnit that this test is asynchronous以及它何时完成。另外,你实际上并没有进行任何Ajax调用,所以Mock处理程序永远不会受到攻击。您需要在测试中放置代码以实际测试 ajax调用(从而点击上面的模拟处理程序):
QUnit.test("mockjax test", function (assert) {
// This is QUnit's callback for async testing
let done = assert.async();
// You also need to define the `expected` data
let expected = { foo: "bar" };
$.mockjax({
url: "/restful/fortune",
data: function (json) {
assert.deepEqual(JSON.parse(json), expected); // QUnit example.
return true;
},
responseText: {
status: "success",
fortune: "Are you a mock turtle?"
}
});
// Now add the actual function call to your SOURCE code that you're testing...
// Since I don't know your source code, I'll just put a jquery ajax call here
$.ajax({
url: "/restful/fortune",
data: { foo: "bar" },
complete: function() {
done(); // now we tell QUnit that our test is complete.
}
});
});