[英]socket.io with mocha test, The Should assert not throw error
For easy read, I delete some code. 为了便于阅读,我删除了一些代码。
I send a message hello
to client1
: 我向client1
发送消息hello
:
client1.emit('chat_to_user', {user: 'user2', message: 'hello'})
And client2 listen chat_to_user
event. 和chat_to_user
监听chat_to_user
事件。
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. 上面的测试很好,测试通过了。
But when I change client2 code: 但是,当我更改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()
});
});
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? 那么,如何用Socket.io测试抛出错误原因呢?
I am using socket.io 1.0 我正在使用socket.io 1.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. Socket.io 1.0自行处理错误,因此,一旦引发错误,它就会捕获该错误并将错误作为“错误”事件发出。
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... throw
语句将错误返回给机器。
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). 编辑:要获得一个不错的错误消息(期望消息等),您可以像done(err)
这样涉及done
回调(更新示例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.