QUnit没有运行外部JavaScript文件

时间:2016-07-31 19:10:36

标签: javascript jquery unit-testing qunit

我正在尝试修改教程here以使用QUnit v2.x,但它似乎没有拿起我想要测试的JavaScript文件。

的test.html

$fruit = "apple";

$questions = array(
    "1" => array(
        "question" => "Is it good?",
        "answers" => ["Fantastic", "So-so", "Never again"]
    ),
    "2" => array(
        "question" => "Where is it from?",
        "answers" => ["South America", "Africa", "Australia"]
    ),
    "3" => array(
        "question" => "Which color does it have",
        "answers" => ["Yellow", "Red", "Orange"]
    ), //...etc
);
$questionsForFruits = array(
    "apple" => [1, 3],
    "banana" => [1, 2],
    "pineapple" => [2]
);

$fruit = "apple";

foreach($questionsForFruits[$fruit] as $questionNo) {
    $q = $questions[$questionNo];
    echo "<div>{$q['question']}</div>
          <select>";
    foreach($q['answers'] as $index =>$answer) {
        echo "<option value = '$index'>$answer</option>";
    }
    echo "</select><br>
          <input type='text' value='submit'/>";
}

list.js

<div id="qunit"></div>
<div id="qunit-fixture">
  <form>
    <input name="text" />
    <div class="has-error">Error text</div>
  </form>
</div>

<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="qunit.js"></script>
<script src="../list.js"></script>
<script>

    QUnit.test("errors should be hidden on keypress", function (assert) {
        $('input').trigger('keypress');
        assert.equal($('.has-error').is(':visible'), false);
    });

</script>

测试失败,结果为真

本教程中提供的代码适用于QUnit 1.23

jQuery(document).ready(function ($) {
    $('input').on('keypress', function () {
        $('.has-error').hide();
    });
});

编辑:使用QUnit v1.23,两个版本的测试都有效!

1 个答案:

答案 0 :(得分:3)

所以,这个问题出现在multiple other places的SO上。基本上发生的事情是QUnit 2以不同的方式处理灯具。您的代码会向原始HTML添加一个事件处理程序,但随后QUnit会杀死该HTML并重建它,从而删除您的处理程序。解决方案是在您的测试中进行事件绑定 ,而不是在页面加载上。这里有a fiddle,但代码如下:

  function init() {
    $('.username').on('keypress', function() {
      console.log('hiding error!');
      $('.has-error').hide();
    });
  }

  QUnit.test("errors should be hidden on keypress", function(assert) {
    init();
    $('.username').trigger('keypress');
    assert.strictEqual($('.has-error').is(':visible'), false);
  });

  QUnit.test("errors not be hidden unless there is a keypress", function(assert) {
    init();
    assert.strictEqual($('.has-error').is(':visible'), true);
  });