How to test a event in Jasmine node.js?

I'm writing a node module that uses serial port communication. All outgoing messages are called with write(), and all for all incoming messages, events are raised.

I would like to be able to test the incoming messages. When a write is called, it takes a very short time (less than a 1/10 second in good conditions) for the incoming message.

Snippet:

it("can receive", function() {
    btReader.on('dataReceived', function(data){
        console.log(data);
        expect(data).toBeDefined();
    });
});

This way it will only make the event handler, but the complete test will be done before any event is raised. Then, when an event is raised, the code will execute, but it will not be really tested.

Will I have to use the waitsFor method, and then set a bool to true inside the eventhandler?

Since your event is asynchronous, yes, you will need to use the waitsFor method to test that the handler has been called. You are exactly right that you will need to create a variable to test. So what you end up with are 3 parts to the test:

  1. The initial setup and event call (i.e. write and some variable set to false).
  2. The waitsFor method where the variable is set to true.
  3. The final expectation test that makes sure the variable has been set to true.

The waitsFor method expects a timeout parameter, so if it takes 200ms to run your function, then give the timeout a reasonable value to make sure it never fails unexpectedly. Of course, you don't have to do a simple test like the one above, you could set the variable to whatever the write method does and make sure that it has done what it was supposed to do.