HTML and CSS Reference
In-Depth Information
Listing 14.16
Expecting
post
to add message
"should add message from request body": function (test) {
var data = { data: { user: "cjno", message: "hi" } };
this.controller.chatRoom = { addMessage: stub() };
this.controller.post();
this.req.emit("data", encodeURI(JSON.stringify(data)));
this.req.emit("end");
test.ok(this.controller.chatRoom.addMessage.called);
var args = this.controller.chatRoom.addMessage.args;
test.equals(args[0], data.data.user);
test.equals(args[1], data.data.message);
test.done();
}
As before, we call the
post
method to have it add its request body listeners,
then we emit some fake request data. Finally we expect the controller to have called
chatRoom.addMessage
with the correct arguments.
To pass this test we need to access
this.chatRoom
from inside the anony-
mous “end” event handler. To achieve this we can bind it to avoid having to manu-
ally keep local references to
this
. At the time of writing, V8 does not yet support
Function.prototype.bind
, but we can use the custom implementation from
Listing 6.7 in Chapter 6,
Applied Functions and Closures.
Save the implementation
in
deps/function-bind.js
and Listing 14.17 should run as expected.
Listing 14.17
Adding messages on POST
require("function-bind");
var chatRoomController = {
/* ... */
post: function () {
/* ... */
this.request.addListener("end", function () {
var data = JSON.parse(decodeURI(body)).data;
this.chatRoom.addMessage(data.user, data.message);
}.bind(this));
}
};