0

my test

For easy read, I delete some code.

I send a message hello to client1:

client1.emit('chat_to_user', {user: 'user2', message: 'hello'})

And client2 listen chat_to_user event.

it('chat', function(done) {
     client2.socket.on('chat_to_user', function(data) {
         data.message.should.equal('hello')
         done()
     });
});

this above test is fine, test passed.

change my test, it should throw error (but not)

But when I change client2 code:

it('chat', function(done) {
     client2.socket.on('chat_to_user', function(data) {
         //notice here!  the `data.message` should equal `hello`
         data.message.should.equal('i am fine')
         done()
     });
});

When I run test, It should throw an error, and tell me the error reason, like follow:

AssertionError: expected 'i am fine' to be 'hello'
      + expected - actual

      +"i am fine"
      -"hello"

But It didn't throw error reason, It just throw an timeout error:

Error: timeout of 5000ms exceeded

So, How to throw error reason with Socket.io test?

I am using socket.io 1.0

Community
  • 1
  • 1
user3160143
  • 698
  • 1
  • 10
  • 15

1 Answers1

0

Socket.io 1.0 handles errors by itself, so as soon as an error is raised, it will catch it and emit the error as an "error" event.

So as a complete test example, you can check the error object like this:

it('chat', function(done) {
    //Just to make clear what I understand as client2
    var client2 = io.connect(socketUrl, options);

    client2.socket.on('chat_to_user', function(data) {
        //notice here!  the `data.message` should equal `hello`
        data.message.should.equal('i am fine')
        done();
    });

    client2.on("error", function(err){
        done(new Error(err.description.message));
    });

    client1.emit('chat_to_user', {user: 'user2', message: 'hello'})
});

The throw statement throws the error back to mocha...

Sadly this is a lot of boiler-code, but it's a good place to start for a more clean solution!

Edit: To get a nice error message (expect messages etc.) you can involve the done callback like done(err) (updated example).

ryyppy
  • 442
  • 3
  • 10