0

我的测试

为了便于阅读,我删除了一些代码。

我发消息helloclient1

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

和client2监听chat_to_user事件。

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

上面这个测试很好,测试通过了。

改变我的测试,它应该抛出错误(但不是)

但是当我更改 client2 代码时:

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()
     });
});

当我运行测试时,它应该会抛出一个错误,并告诉我错误原因,如下所示:

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

      +"i am fine"
      -"hello"

但它没有抛出错误原因,它只是抛出一个超时错误:

Error: timeout of 5000ms exceeded

那么,如何使用 Socket.io 测试抛出错误原因?

我正在使用 socket.io 1.0

4

1 回答 1

0

Socket.io 1.0 自己处理错误,因此一旦出现错误,它就会捕获它并将错误作为“错误”事件发出。

因此,作为一个完整的测试示例,您可以像这样检查错误对象:

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'})
});

throw语句将错误返回给 mocha ...

可悲的是,这是很多锅炉代码,但它是开始一个更干净的解决方案的好地方!

编辑: 要获得一个很好的错误消息(期望消息等),您可以涉及done回调done(err)(更新示例)。

于 2014-12-05T12:31:18.053 回答