HTML and CSS Reference
In-Depth Information
Listing 14.60
Proxying
getMessagesSince
chatRoom.waitForMessagesSince = function (id) {
return this.getMessagesSince(id);
};
Now to the interesting part. If the attempt to fetch existing methods does not
succeed, the method should add a listener for the “message” event and go to sleep.
Listing 14.61 tests this by stubbing
addListener
.
Listing 14.61
Expecting the wait method to add a listener
"should add listener when no messages": function (test) {
this.room.addListener = stub();
var promise = new Promise();
promise.resolve([]);
this.room.getMessagesSince = stub(promise);
this.room.waitForMessagesSince(0);
process.nextTick(function () {
test.equals(this.room.addListener.args[0], "message");
test.isFunction(this.room.addListener.args[1]);
test.done();
}.bind(this));
}
Again we stub the
getMessagesSince
method to control its output. We
then resolve the promise it's stubbed to return, passing an empty array. This
should cause the
waitForMessagesSince
method to register a listener for
the “message” event. Seeing as
waitForMessagesSince
does not add a lis-
tener, the test fails. To pass it, we need to change the implementation as seen in
Listing 14.62.
Listing 14.62
Adding a listener if no messages are available
chatRoom.waitForMessagesSince = function (id) {
var promise = new Promise();
this.getMessagesSince(id).then(function (messages) {
if (messages.length > 0) {
promise.resolve(messages);
} else {
this.addListener("message", function () {});
}