<script type="text/javascript">
function check_person() {
var no_adt = document.getElementById('adult').value;
var no_chd = document.getElementById('child').value;
var no_inf = document.getElementById('infant').value;
if (no_inf > no_adt) {
alert('Number of Infants must be less than equal to number of Adults');
return false;
}
if (parseInt(no_adt) + parseInt(no_chd) + parseInt(no_inf) > 9) {
alert('Please note there is a maximum of 9 passengers permitted on the search form');
return false;
}
return true;
}
function assignValues(adult, child, infant){
document.getElementById('adult').value = adult;
document.getElementById('child').value = child;
document.getElementById('infant').value = infant;
}
test("Test check_person", function(){
assignValues(5,2,1);
ok(check_person());
assignValues(2,1,5);
ok(!check_person(), "Number of Infants is less than equal to number of Adults");
assignValues(7,2,5);
ok(!check_person(), "a maximum of 9 passengers permitted");
});
</script>
<body>
<div id="qunit-fixture">
<input id="adult" />
<input id="child" />
<input id="infant" />
</div>
<div id="qunit">
</div>
</body>
最好修改您的函数以使其更具可测试性:
function check_person(no_adt, no_chd, no_inf) {
if (no_inf > no_adt) {
alert('Number of Infants must be less than equal to number of Adults');
return false;
}
if (parseInt(no_adt) + parseInt(no_chd) + parseInt(no_inf) > 9) {
alert('Please note there is a maximum of 9 passengers permitted on the search form');
return false;
}
return true;
}
然后你就不需要 html 标记和 assignValues():
test("Test check_person", function(){
ok(check_person(5, 2, 1));
ok(!check_person(5, 2 ,1), "Number of Infants is less than equal to number of Adults");
ok(!check_person(7, 2, 5), "a maximum of 9 passengers permitted");
});