HTML and CSS Reference
In-Depth Information
the same problems when we want to simply explore an interface to learn. For this
purpose we can write learning tests, i.e., unit tests written with the goal of learning,
not with the goal of testing the exercised interface per se.
As an example, let us take the built-in Array.prototype.splice method
for a spin. This method accepts two or more arguments: an index to start with, a
number of items to remove, and optional elements to insert into the array. We are
curious as to whether or not this method alters the original array. We could look
up the answer, or we could simply ask JavaScript to tell us, as the learning test in
Listing 4.1 shows. To run the test, set up a JsTestDriver project as explained in
Chapter 3, Tools of the Trade, with a test directory and save the test in a file in
that directory. Add a configuration file that loads test/*.js .
Listing 4.1 Expecting Array.prototype.splice to modify the array
TestCase("ArrayTest", {
"test array splice should not modify array": function () {
var arr = [1, 2, 3, 4, 5];
var result = arr.splice(2, 3);
assertEquals([1, 2, 3, 4, 5], arr);
}
});
Because we don't really know what the answer is, we roll with the assumption
that the splice method is not destructive. Note how this contrasts with traditional
unit testing—when testing production code we should always write assertions on
firm expectation about the result. However, we are now learning by observing what
the implementation can tell us, and so whatever answer we are assuming before run-
ning the test is not of grave importance. Running the test proves us wrong anyway:
“expected [1, 2, 3, 4, 5] but was [1, 2]. ” So we have learned something
new. To record our findings, Listing 4.2 updates the test to state what we now know
to be true.
Listing 4.2 Array.prototype.splice modifies the receiving array
TestCase("ArrayTest", {
"test array splice should modify array": function () {
var arr = [1, 2, 3, 4, 5];
var result = arr.splice(2, 3);
assertEquals([1, 2], arr);
}
});
 
Search WWH ::




Custom Search