0

私は知っている単純なjsコードをチェックしているので、qunitを介して自分のjsコードをチェックしたいです。以下のタイプの js コードを qunit でチェックする方法を教えてください。

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 に答える