This weekend I’ve been playing around with JavaScript unit testing. Since most of my JavaScript work is based off jQuery I quickly ended up at its QUnit test runner, which turned out to be pretty decent stuff.
That was not enough though. A while back I had stumbled upon John Resig’s work on FireUnit — a FireBug extension for unit testing — and I liked the idea. The main reason for my excitement was an opportunity to link FireUnit to FireBug’s JavaScript profiling features. That would make for an extremely powerful JavaScript testing and optimization tool. I even posted a comment with this idea to John’s article announcing FireUnit.
This weekend I jumped back on the FireUnit train to find out that my prayers have been answered! It turned out that FireUnit has been extended with some profiling goodness, exactly like I had imagined.
All that was needed now was an easy way of hooking in FireUnit and its profiling capabilities into existing QUnit test pages. Therefore I wrote a quick and dirty QUnit extension which does exactly that. You can simply load the plugin from any page and the QUnit tests on that page will be automatically run through FireUnit. On top of that, with just a few minor changes to the test code you can automatically run all units through FireBug’s profiler and get a nice ranking of their efficiency.
Check out the code and let me know what you think! (Disclaimer: it’s all très fraîche, so do not expect it to be flawless. Please contribute if you can!)
How to use
Behavior is configured using two setting variables:
QUnit.profiling (boolean)
Set to true in order to enable profiling. This will only work for tests that supply their test code (first argument to ok, equals or same) as a function, rather than a value which is QUnit’s default behavior. Also you will need to have QUnit.testIsFunction set to true.
QUnit.testIsFunction (boolean)
This settings enables you to plug in any existing QUnit test code and not run into problems. By setting it to false you signal the fact that no functions should be expected as test code. This also implies that profiling is not possible.
Make sure you set these variables after including QUnit (testrunner.js) but before including my plugin (qunit.fireunit+profiling.js).
Example:
<script type="text/javascript" src="jquery-latest.js"></script>
<script type="text/javascript" src="code-you-want-to-test.js"></script>
<script type="text/javascript" src="testrunner.js"></script>
<script type="text/javascript">
jQuery(function() {
QUnit.profiling = true;
QUnit.testIsFunction = true;
});
</script>
<script type="text/javascript" src="qunit.fireunit+profiling.js"></script>
<script type="text/javascript">
jQuery(function() {
// Your tests go here, for example:
equals(function() {
return "test value";
}, "test value", "test message");
});
</script>