QUnit测试用例



如果我正在测试为表单编写的验证函数,那么QUnit中的测试方法会是什么样子?比方说,如果表单需要检查名称字段是否为空,并且我测试该功能的函数看起来像

function validNameCheck(form)
{
  if (document.forms["formSecond"]["nameFull"].value=="")
  {
    alert("Name Field cannot be empty")
    return false;
  }
  else
    return true;
}

对于以上内容,可能的QUnit测试用例是什么?

假设您传递给validNameCheck函数的参数是form中的name元素,您想检查它是否为空,我的意思是这样的:

var myName = document.forms["formSecond"]["nameFull"];

那么你的功能应该是这样的:

function validNameCheck(form){
    if (form.value==""){
        alert("Name Field cannot be empty")
        return false;
    }else{
        return true;
    }
}

请注意,我会更改您正在检查的硬编码元素。

那么你的QUnit测试应该是这样的:

QUnit.test( "CheckingName", function( assert ) {
  var value = false;
  assert.equal( value, validNameCheck(myName), "We expect the return to be false" );
});

我会进一步研究@Gepser的解决方案(尽管它肯定是解决方案的一部分)。如果你想按表单的名称获取表单,那么你可能想在每次测试之前使用QUnit的fixture来重置HTML。然后,您可能需要模拟alert方法,这样在测试时就不会得到一堆。

在QUnit HTML文件中:

<body>
  <div id="qunit"></div>
  <div id="qunit-fixture">
    <!-- Anything in here gets reset before each test -->
    <form name="formSecond">
      <input type="text" name="nameFull">
    </form>
  </div>
  ...
</body>

然后在你的QUnit测试中(要么在HTML文件中,要么在他们自己的JS文件中):

QUnit.begin(function() {
  // mock out the alert method to test that it was called without actually getting an alert
  window.alert = function() {
    window.alert.called++;
  };
  window.alert.called = 0;
});
QUnit.testDone(function() {
  // reset the alert called count after each test
  window.alert.called = 0;
});
...
// From @Gepser's answer...
QUnit.test( "CheckingName", function( assert ) {
  var value = false;
  assert.equal( value, validNameCheck(), "We expect the return to be false" );
  // add an assertion to make sure alert was called
  assert.equal( 1, window.alert.called, "alert was called only once" );
});

最新更新