HTML and CSS Reference
In-Depth Information
test.equals(JSON.parse.args[0], stringData);
test.done();
}
});
setUp and tearDown take care of restoring JSON.parse after the test has
stubbed it out. We then create a controller object using fake request and response
objects along with some test data to POST. Because the tddjs.ajax tools built
in the two previous chapters currently only support URL encoded data, we must
encode the test data to fit.
The test then emits a simple URL encoded JSON string in two chunks, the
“end” event, and finally expects the JSON.parse method to have been called.
Phew! Listing 14.14 shows one way to pass the test.
Listing 14.14 Reading the request body and parsing it as JSON
var chatRoomController = {
/* ... */
post: function () {
var body = "";
this.request.addListener("data", function (chunk) {
body += chunk;
});
this.request.addListener("end", function () {
JSON.parse(decodeURI(body));
});
}
};
As the test passes it is time to remove duplication. Aggressively removing dupli-
cation is the key to a flexible code base that is easy to change and mold any way we
see fit. The tests are part of code base, and need constant refactoring and improve-
ment too. Both the test cases for create and post create a controller instance
using stub request and response objects, and sure enough, the get test case will do
just the same. We can extract this into a function that can be used as a shared setup
method. Listing 14.15 has the lowdown.
 
Search WWH ::




Custom Search