开发者

javascript (node.js): unit testing code that fires multiple events

I am attempting to write unit test code (caolan's nodeunit) that will test for multiple event firings.

So, I am testing

function A() {
  this.fireaway = function() {
    send_message_开发者_如何学JAVAA_to_queue();
    send_message_B_to_a_different_queue();
    send_message_C_to_a_web_service();
  };
}

So, unit testing only 1 event is easy.

exports.A = function(test) {
  a = new A();

  queue = new Queue();
  queue.on('message', function(err, message) {
     test.ok(true, "got message");
     test.done();
  };

  a.fireaway();
};

Right now, I'm using setTimer() to do a count down and force completion by X amount of time, but is there a better way of doing this?


You could try something like this:

var status = {
    'message1': false,
    'message2': false,
    'message3': false,
    'message4': false
};
var my_test_queue = new Queue();
function caught_one(arg)
{
    status.arg = true;
    // if status.message1, message2, message3 and message4 == true,
    my_test_queue.emit('done');
}

queue1.on('message1', function(err, message) {
    test.ok(something);
    caught_one('message1');
};

queue2.on('message2', function(err, message) {
    test.ok(something);
    caught_one('message2');
};

queue3.on('message3', function(err, message) {
    test.ok(something);
    caught_one('message3');
};

queue4.on('message4', function(err, message) {
    test.ok(something);
    caught_one('message4');
};

my_test_queue.on('done', function() {
    test.done();
});

Basically, I'm keeping track of the events that have fired, and when I find all of them, emit my own, so test.done() can be called on that event.


One possible answer is to encode callbacks for each event.

IE:

send_message_A_to_queue(callback1);
send_message_B_to_a_different_queue(callback2);
send_message_C_to_a_web_service(callback3);

This works great for single usage instances, I haven't tried multiple ones yet.

callback1

function(response) { 
    test.equals('ok', response.obj);
    test.done();
}

urhm...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜