0

我想通过 q​​unit 检查我的 js 代码。我正在检查我知道的简单 js 代码。谁能告诉我如何用 qunit 检查以下类型的 js 代码?这个问题的答案真的很容易,

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;
}`enter code here`
return true;

}

4

1 回答 1

1
  <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");
 });
于 2013-04-10T21:55:22.723 回答