有人能解释一下为什么第三控制台日志中的数据是空的吗?
这是我在测试中遇到的一个问题的简化版本。我注意到我的测试函数中没有插入到"QUnit.test (...)“中的数据。一些由事件触发的函数会使用这些数据,并且会发生错误。
可以在JsBin上找到可执行代码
$(document).ready(function() {
$("p").data("thedata", 1);
console.log("First", $("p").data());
});
QUnit.config.autostart = false;
setTimeout(function() {
QUnit.start();
console.log("Second", $("p").data());
}, 1000);
setTimeout(function() {
console.log("Third", $("p").data());
}, 2000);<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="http://code.jquery.com/qunit/qunit-2.1.1.css" rel="stylesheet" />
<script src="http://code.jquery.com/qunit/qunit-2.1.1.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture">
<p>content</p>
</div>
</body>
</html>
发布于 2017-09-12 21:03:56
好了,在看了你的JSBin之后,我知道问题出在哪里了。部分原因是,在上面的代码中,您实际上根本没有使用QUnit (没有测试),但真正的问题是,QUnit“fixture”在每次测试后(有意地)被重置。前两个是有效的,因为QUnit必须考虑第一个测试,但第三个控制台日志的2000ms超时必须发生在“测试”之后,这意味着fixture将被重置为其原始的HTML。请注意,您在JS中添加数据,而不是在HTML中。
所以..。下面是您的选择:将数据放入实际的超文本标记语言(<p data-thedata='1'>content</p>)中,或者使用beforeEach钩子设置一个适当的QUnit测试(这是我的首选)。下面是选项二的代码和一个working JSBin。
$(document).ready(function() {
console.log("First", $("p").data());
});
QUnit.config.autostart = false;
QUnit.module('data', {
beforeEach: function() {
$("p").data("thedata", 1);
console.log("before each", $("p").data());
}
});
QUnit.test('data delay', function(assert) {
let done = assert.async();
setTimeout(function() {
console.log("Second", $("p").data());
}, 1000);
setTimeout(function() {
console.log("Third", $("p").data());
assert.ok($("p").data());
assert.equal($("p").data().thedata, 1);
done();
}, 2000);
});
QUnit.start();https://stackoverflow.com/questions/45960867
复制相似问题