我知道已经有很多帖子介绍了这一点,但我在基线时并不擅长 Javascript,而且大多数应该有意义的帖子都使用了让我感到困惑的旧语法。
这是我想要工作的功能:
function getUpdateForm() {
$.ajax({
url: 'test_response.html',
type: 'GET',
dataType: 'json',
success: function(data) {
$("#Form_div").html(data);
},
});
};
这是我的响应文件:
<html>
<head>
<title>Test Response</title>
</head>
<body>
<h1>Test Page</h1>
</body>
</html>
这是我的 QUnit 测试:
QUnit.test('getUpdateForm ajax request', function(assert) {
$.ajax = function(request) {
assert.equal(
request.url,
'test_response.html',
'request url is correct'
);
assert.equal(request.type, 'GET',
'request type is correct'
);
assert.equal(request.dataType, 'json',
'request dataType is correct'
);
};
getUpdateForm();
setTimeout(function() {
assert.equal($("#Form_div").html(), '',// not exactly sure what to put
'Received correct html in response'
);
assert.async();
}, 1000);
});
目前它甚至不尝试在 setTimeout
函数中运行 assert.equal
。
请尽可能提供详细信息,我可能会有很多问题。第一个问题是,测试如何从 $.ajax = function(request)
获得正确的函数?
最佳答案
我明白你想做什么...但是有一个 tool to mock out Ajax requests为了这个目的! (我是它的维护者,但仍然......)
基本上,在您的测试(或 beforeEach
hook )中,您根据真实的 Ajax 调用创建一个模拟,然后进行代码测试。
首先,我将首先在您的源代码函数中添加一个回调,以便我们知道在测试中何时完成 ajax 调用:
function getUpdateForm(doneFunction) {
$.ajax({
url: 'test_response.html',
type: 'GET',
dataType: 'json',
success: function(data) {
$("#Form_div").html(data);
},
complete: doneFunction // <-- this is new!
});
};
现在使用模拟设置您的测试,并执行断言...
QUnit.test('getUpdateForm ajax request', function(assert) {
let done = assert.async(); // set up an async test
$.mockjax({
url: "test_response.html",
responseText: "<h1>Test Page</h1>"
});
getUpdateForm(function() { // this is our callback function
// now do your assertions on the content in the form div...
assert.equal($("#Form_div h1").text(), 'Test Page', 'Received correct title in html response');
done(); // then tell QUnit you are done testing.
});
});
除了 QUnit JS 文件之外,不要忘记包含 Mockjax JS 文件!
关于javascript - QUnit测试ajax成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53974271/