gpt4 book ai didi

javascript - 在 QUnit 中使用 Mockjax?

转载 作者:行者123 更新时间:2023-11-30 15:08:24 26 4
gpt4 key购买 nike

我在 Mockjax 文档中看到了这个例子:

$.mockjax({
url: "/rest",
data: function ( json ) {
assert.deepEqual( JSON.parse(json), expected ); // QUnit example.
return true;
}
});

但我不确定我应该如何将它与 QUnit 测试方法一起使用。有任何想法吗?

mockjax docs

我试过了,但它说它至少需要一个断言,就好像它根本没有运行它一样,断言行:

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?"
}
});
});

最佳答案

你很接近,但 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.
}
});
});

我鼓励您阅读 QUnit's guide to unit testing , 和 async documentation .

关于javascript - 在 QUnit 中使用 Mockjax?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45418496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com