我有以下问题:
我想使用QUnit测试简单的JQuery代码。
// code allows selection of all checkboxes inside form using .select-all checkbox
$(function() {
$(".select-all").click(function() {
if (this.checked)
$(".robject").prop("checked", true);
else
$(".robject").prop("checked", false);
})
})
问题在于我将表单放在<div id="qunit-fixture></div>
内(原因:将来会有更多测试)我得到断言错误:
这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Javascript tests</title>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/qunit/2.4.0/qunit.min.css">
</head>
<body>
<div id="qunit">
</div>
<div id="qunit-fixture">
<form>
<input type="checkbox" class="select-all">
<input type="checkbox" class="robject r_1" name="" value="">
<input type="checkbox" class="robject r_2" name="" value="">
<input type="checkbox" class="robject r_3" name="" value="">
<button type="button" name="button">Delete</button>
</form>
<script src="test.js"></script>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qunit/2.4.0/qunit.min.js">
</script>
<script>
QUnit.test("start all unchecked, then check all", function (assert) {
assert.equal($('.robject:checked').length, 0);
$('.select-all').click();
assert.equal($('.robject:checked').length, 3);
});
</script>
</body>
</html>
这是错误:
预期:3,结果:0
提前致谢。
答案 0 :(得分:0)
你必须以编程方式将html注入qunit-fixture,然后编写断言。
例如:
QUnit.test("start all unchecked, then check all", function (assert) {
var fixture = $( "#qunit-fixture" );
fixture.append( "<form>addd your form here</form>" );
assert.equal($('.robject:checked').length, 0);
$('.select-all').click();
assert.equal($('.robject:checked').length, 3);
});