Javascript QUnit测试ajax成功函数
我知道已经有很多文章介绍了这一点,但我在Javascript方面还不是很在行,而且大多数应该有意义的文章都使用了一种让我困惑的旧语法 以下是我想使用的功能:Javascript QUnit测试ajax成功函数,javascript,jquery,unit-testing,qunit,Javascript,Jquery,Unit Testing,Qunit,我知道已经有很多文章介绍了这一点,但我在Javascript方面还不是很在行,而且大多数应该有意义的文章都使用了一种让我困惑的旧语法 以下是我想使用的功能: function getUpdateForm() { $.ajax({ url: 'test_response.html', type: 'GET', dataType: 'json', success: function(data) { $("#Form_div").html(data);
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>
目前,它甚至没有尝试运行setTimeout
函数中的assert.equal
请提供尽可能多的细节,我可能会有很多问题。首先,test是如何从
$中获得正确的函数的。ajax=function(request)
我明白你想做什么了。。。但是有一种方法就是为了这个目的!(我是维护者,但仍然…)
基本上,在您的测试(或a)中,您可以基于真实的Ajax调用创建一个mock,然后进行代码测试
首先,我将首先在源代码函数中添加一个回调,以便我们知道测试中何时完成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!
});
};
函数getUpdateForm(doneFunction){
$.ajax({
url:“test_response.html”,
键入:“GET”,
数据类型:“json”,
成功:功能(数据){
$(“#Form_div”).html(数据);
},
完成:doneFunction//我花了一点时间才弄明白,但是谢谢。你有没有可能在这一点上帮我()
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.
});
});