HTML and CSS Reference
In-Depth Information
14.3.3 Adding Messages
As dictated by the controller using it, the chatRoom object should have an ad-
dMessage method that accepts a username and a message. Dealing with Bad Data
For basic data consistency, the addMessage method should err if either the user-
name or message is missing. However, as an asynchronous I/O interface, it cannot
simply throw exceptions. Rather, we will expect errors to be passed as the first ar-
gument to the callback registered with addMessage , as is the Node way. Listing
14.29 shows the test for missing username. Save it in test/chapp/chat _ room _
test.js .
Listing 14.29 addMessage should require username
var testCase = require("nodeunit").testCase;
var chatRoom = require("chapp/chat_room");
testCase(exports, "chatRoom.addMessage", {
"should require username": function (test) {
var room = Object.create(chatRoom);
room.addMessage(null, "a message", function (err) {
test.inherits(err, TypeError);
The test fails as expected, and so we add a check on the user parameter, as
Listing 14.30 shows.
Listing 14.30 Checking the username
var chatRoom = {
addMessage: function (user, message, callback) {
if (!user) {
callback(new TypeError("user is null"));
Search WWH ::

Custom Search