Unit tests make it a lot easier to change
scripts you haven't touched in a long time. I wrote the first
version of this script a long time ago, and when I recently picked
it up again, I quickly broke it, and spent a lot of time figuring
out how it was meant to work - without tests, it's obvious that the
code is not working, but it can be hard to figure out how it ever
worked.
QUnit Tips
QUnit makes it very easy to a script is (and will) still (be)
doing what's expected.
Put the expected default HTML inside the #qunit-fixture element
- QUnit will restore this to the state it was in just before QUnit
started,
but all events will be lost! Use the QUnit.module()
before/beforeEach hooks to setup events.
Use QUnit.test() to provide a scope for each test - as long as
the test only depends on the static content in #qunit-fixture and
dynamic setup in the module hooks, tests can run in any order
without messing each other up.
Give modules, tests, and assertions good names, avoiding
repetition. Assertions run inside a test, which run inside a
module, so each of them can assume the context is clear.
Using the appropriate assertion enables better failure feedback
from QUnit: assert.ok(!false) => assert.notOk(false),
assert.ok(2===2) => assert.equal(2, 2), assert.ok(1 != 2) =>
assert.notEqual(1, 2).
Use assert.expect() to indicate the expected assertion count.
With callbacks and generally passing functions around for
execution, assertions might not always get to run:
$(".something").each(function() {
assert.ok(condition);});- if there should have been matches,
but by mistake, no elements match, no asserts will run, and the
test passes. Or there might be more matches than expected, and the
assertion happens to pass for the undesired matches as well. If two
assertions are expected for 5 elements, use
assert.expect(2*5);
QUnit Test Results
Test Data
Simple
Unordered List
Red
Green
Green and Red
Orange
Ordered List
Red
Green
Green and Red
Definition List
Red Title
Red
Green Title
Green
Also Green
Ignored
Does not have the class
"item", and hence it is ignored.