HTML and CSS Reference
In-Depth Information
Note how both the wording and the assertion changed. Because we have dis-
covered that the method in question is in fact destructive, we now wonder: Does it
also return the result? Listing 4.3 investigates.
Listing 4.3 Expecting Array.prototype.splice to return the spliced array
"test array splice should return modified array":
function () {
var arr = [1, 2, 3, 4, 5];
var result = arr.splice(2, 3);
assertEquals(arr, result);
Running this test proves us wrong yet again: “expected [1, 2] but was
[3, 4, 5]. ” Apparently, the splice method returns the removed items. Time
to update the wording of our test, as seen in Listing 4.4.
Listing 4.4 Expecting Array.prototype.splice to return removed items
"test array splice should return removed items":
function () {
var arr = [1, 2, 3, 4, 5];
var result = arr.splice(2, 3);
assertEquals([3, 4, 5], result);
Rather than playing with an array and the splice method in a browser console,
we put the test in a file. With a minimum of added overhead, we now have a
repeatable experiment that documents what we just learned, perfect for later review.
Using the JsTestDriver test runner, we could even send this test out to an army of
browsers to verify that the two tests run consistently across browsers.
Testing built-in functionality like this might seem to contradict our usual attitude
toward unit testing: never to test code that we didn't write ourselves, and to mock or
stub external dependencies while testing. These are still valuable pieces of advice,
but they do not apply to learning tests. Learning tests aren't a part of production
code; they live in a separate repository, a personal repository, and they help us
document our knowledge and our learning experience.
Still, in contrast to traditional applications of unit testing, learning tests cannot
be successfully collaborated on. Everyone should keep their own suite of learning
tests. The reason for this advice is simply that it is not the tests themselves that
Search WWH ::

Custom Search