I have a Faye publish/subscribe server that sends a message to new subscribers only if a message has already been sent to the other subscribers. I am using mocha for unit testing.
This test works to confirm the basic functionality:
it('should send a special message to new subscribers', function(done){
testerPubSub.setLastJsonContent('some arbitrary content');
var subscription = client.subscribe("/info", function(message) {
assert.equal(true, message.text.indexOf('some arbitrary content') !== -1, 'new subscriber message not sent');
done();
});
subscription.cancel();
});
But I would now like to test the case where there has not been a message sent to previous subscribers. This test would be something like:
it('should not send a special message to new subscribers if no data has been retrieved', function(done){
testerPubSub.setLastJsonContent(null);
var messageReceived = false;
var subscription = client.subscribe("/sales", function(message) {
messageReceived = true;
});
////need to magically wait 2 seconds here for the subscription callback to timeout
assert.equal(false, messageRecieved, 'new subscriber message received');
subscription.cancel;
done();
});
Of course, the magic sleep function is problematic. Is there a better way to be doing this sort of "I expect the callback to never get fired" test?
Thanks, Mike
I thought of one possible solution, but it is a bit too dependent on timing for me to think of it as THE solution:
it('should not send a special message to new subscribers if no data has been retrieved', function(done){
testerPubSub.setLastJsonContent(null);
var messageReceived = false;
var subscription = client.subscribe("/sales", function(message) {
assert.fail(message.text, '', 'Should not get message', '=');
});
setTimeout(function(){
done();
}, 1500);
subscription.cancel;
});
This test passes, but the 1500ms pause just seems rather arbitrary. I'm really saying "right before I think it's going to timeout, jump in and say it's OK.