HTML and CSS Reference
In-Depth Information
Now we can immediately rerun the test file in a browser and inspect the console
to verify that the change fixed the “y” format specifier. In all its simplicity, we've
now written a unit test. We're targeting the smallest unit possible in JavaScript—the
function. You have probably done something like this many times without being
aware of the fact that it is a unit test.
While automating the process of creating test objects and calling some methods
on them is nice, we still need to manually check which calls are OK and which are
not. For a unit test to be truly automated, it needs to be self-checking.
1.2 Assertions
At the heart of a unit test is the assertion. An assertion is a predicate that states the
programmer's intended state of a system. When debugging the broken “y” format
in the previous section, we carried out a manual assertion: when the strftime
method is called on a date from 2009 with the format of "%y" , we expect it to
return the string "09" . If it doesn't, our system is not working correctly. Assertions
are used in unit tests to perform these checks automatically. When an assertion
fails, the test is aborted and we're notified of the failure. Listing 1.7 shows a simple
assert function.
Listing 1.7 A simple assert function
function assert(message, expr) {
if (!expr) {
throw new Error(message);
return true;
assert.count = 0;
The assert function simply checks that its second argument is truthy (i.e.,
any value except false , null , undefined , 0 , "" , and NaN ). If it is, it incre-
ments the assertion counter, otherwise an error is thrown, using the first argument
as error message. We can leverage assert in our tests from before, as seen in
Listing 1.8.
Search WWH ::

Custom Search