How do I run a function before each test when using qUnit?
javascript, nunit, qunit, tdd
Solution
Registering a QUnit Callback
var mySetupFunc(details){/* setup code */}
QUnit.testStart(mySetupFunc);
Callback Details
As of QUnit version 1.10.0pre-A, each registered callback will receive a hash as the first (and only) parameter. I've named mine 'details' in the example above. The contents of the hash vary by callback. Here's a list of information in each hash.
begin (start of all tests)
{} /* empty hash */
done (end of all tests)
- failed: (int) total tests failed
- passed: (int) total tests passed
- total: (int) total tests run
- runtime: (int) how long tests took to run in milliseconds
log (called within the ok() methods, etc)
- result: (boolean) true if good, false if failed
- message: (string) whatever message you passed to ok()
testStart (called at the start of each test)
- name: the name of the test (first argument passed to test() or asyncTest())
- module: the name of the module (if you haven't called the module() method, this will be undefined)
testDone (called at the end of each test)
- name: (string) the name of the test (first argument passed to test() or asyncTest())
- module: (string) the name of the module (will be undefined if you never called module())
- failed: (int) count of assertions that failed
- passed: (int) count of assertions that succeeded
- total: (int) count of all assertions in the test
moduleStart (called at the start of each module)
- module: the name of the module
moduleDone (called at the end of each test)
- module: (string) the name of the module
- failed: (int) count of assertions that failed (total for all tests in module)
- passed: (int) count of assertions that succeeded (total for all tests in module)
- total: (int) count of all assertions in the module
Examples
// There's probably a more elegant way of doing this,
// but these two methods will add a row to a table for each test showing how long
// each test took.
var profileStartTime = null;
function startTimer(details) {
profileStartTime = new Date();
}
function stopTimer(details) {
var stopDate = new Date();
var duration = stopDate - profileStartTime;
jQuery('#profiling').append(
"<tr><td>"
+ (details.module ? details.module + ":" : "")
+ details.name
+ "<\/td><td class='duration'>"
+ duration
+ "<\/td><\/tr>");
}
QUnit.testStart(startTimer);
QUnit.testDone(stopTimer);
My html table that is reference above looks like this:
<div style='margin: 10px 0;'>
<table summary='profiling' class='profiling_table'>
<thead>
<tr>
<th>Test Name</th>
<th>Duration</th>
</tr>
</thead>
<tbody id='profiling'>
</tbody>
</table>
</div>
Problem
What is the equivalent of nUnits `[SetUp]` attribute for qUnit?