HTML and CSS Reference
In-Depth Information
Listing 14.44
Expecting
addMessage
to be asynchronous
"should be asynchronous": function (test) {
var id;
this.room.addMessage("cjno", "Hey", function (err, msg) {
id = msg.id;
});
this.room.getMessagesSince(id - 1, function (err, msgs) {
test.equals(msgs.length, 0);
test.done();
});
}
This test fails because the method indeed is synchronous at this point.
Listing 14.45 updates
addMessage
to utilize the
nextTick
method.
Listing 14.45
Making
addMessage
asynchronous
require("function-bind");
var id = 0;
var chatRoom = {
addMessage: function (user, message, callback) {
process.nextTick(function () {
/* ... */
}.bind(this));
},
/* ... */
}
The test now passes. However, it only passes because
getMessagesSince
is still synchronous. The moment we make this method asynchronous as well (as we
should), the test will not pass. That leaves us with checking the
messages
array
directly. Testing implementation details is usually frowned upon, as it ties the tests
too hard to the implementation. I think the test for the asynchronous behavior falls
under the same category; thus, I'd rather remove that test than to add yet another
one that digs inside the implementation.