在Qunit测试中触发JavaScript事件

时间:2015-04-26 03:47:18

标签: javascript jquery qunit

我正在尝试测试当用户点击我的表单时,现有的错误消息将消失。由于某种原因,最后一次测试失败了,我不知道为什么。我是jQuery和Qunit的新手。

的test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Javascript tests</title>
    <link rel="stylesheet" href="qunit.css">
</head>

<body>
<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 type="text/javascript">

 test("errors should be hidden on key press", function() {
     $('input[name="text"]').trigger('keypress');
     equal($('.has-error').is(':visible'), false);
});

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

test("errors should be hidden on click", function() {
     $('input[name="text"]').click();
     equal($('.has-error').is(':visible'), false);
 });

</script>

</body>
</html>

list.js

 jQuery(document).ready(function ($) {
     $('input[name="text"]').on('keypress', function() {
         $('.has-error').hide();
     });

     $('input[name="text"]').on('click', function() {
         $('.has-error').hide();

     });
 })

2 个答案:

答案 0 :(得分:2)

function setupModule() {
    $('input[name="text"]').on('click', function() {
         $('.has-error').hide();
    })
    $('input[name="text"]').on('keypress', function() {
        $('.has-error').hide();
    });
}

module('tests', {setup:setupModule});

test("errors should be hidden on key press", function() {
     $('input[name="text"]').trigger('keypress')
     equal($('.has-error').is(':visible'), false);
});

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


test("errors should be hidden on click", function() {
     $('input[name="text"]').click()
     equal($('.has-error').is(':visible'),false);
 });

http://jsfiddle.net/u3v08v1e/13/

答案 1 :(得分:0)

这就是我的工作方式。

<link href="https://code.jquery.com/qunit/qunit-2.0.0.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="https://code.jquery.com/qunit/qunit-2.0.0.js"></script>

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

<script src="./inventory.js"></script>
<script src="./tests.js"></script>
var babelQuery = {
  presets: ['es2015-loose'],
  plugins: [
    "transform-runtime",
    "transform-proto-to-assign",
    "transform-es3-modules-literals",
    "transform-es3-member-expression-literals",
    "transform-es3-property-literals"
  ]
}