简体   繁体   中英

QUnit Testing Test Case

How would a test method look in QUnit if I am testing validation functions written for a form? Say, if the form needs to check for name field not being null and my function that tests this functionality looks like

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

What would be a possible QUnit test case for the above?

Lets say that the parameter you are passing to the validNameCheck function is the name element in a form that you want to check if is empty or not, I mean something like this:

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

Then your function should look like this:

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

Note that I'd change the hardcoded element that you were checking.

Then your QUnit test should look like this:

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

I would take @Gepser's solution a bit further (although it is certainly part of the solution). If you want to grab the form by it's name, then you probably want to use QUnit's fixture for resetting HTML before each test. Then you might want to mock out the alert method so that you don't get a bunch of them while you're testing.

In the QUnit HTML file:

<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>

Then in your QUnit tests (either in that HTML file our in their own JS file):

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" );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM