经过进一步的探索和刺激,我发现了一些非常有用的信息 http://blog.foundry376.com/2012/09/connecting-to-a-socket-io-server-from-node-js-unit-tests。在作者的例子中,他指出了建立socket监听器的关键步骤before
hooks.
这个例子有效:
假设服务器正在侦听套接字连接localhost:3001
, 当然
var io = require('socket.io-client')
, assert = require('assert')
, expect = require('expect.js');
describe('Suite of unit tests', function() {
var socket;
beforeEach(function(done) {
// Setup
socket = io.connect('http://localhost:3001', {
'reconnection delay' : 0
, 'reopen delay' : 0
, 'force new connection' : true
});
socket.on('connect', function() {
console.log('worked...');
done();
});
socket.on('disconnect', function() {
console.log('disconnected...');
})
});
afterEach(function(done) {
// Cleanup
if(socket.connected) {
console.log('disconnecting...');
socket.disconnect();
} else {
// There will not be a connection unless you have done() in beforeEach, socket.on('connect'...)
console.log('no connection to break...');
}
done();
});
describe('First (hopefully useful) test', function() {
it('Doing some things with indexOf()', function(done) {
expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
done();
});
it('Doing something else with indexOf()', function(done) {
expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
done();
});
});
});
我发现放置done()
in the beforeEach
, socket.on('connect'...)
侦听器对于建立连接至关重要。例如,如果您注释掉done()
在侦听器中,然后将其添加到一个范围之外(就在退出之前beforeEach
),你会看到“没有连接可以断开……”消息而不是“断开连接……”信息。就像这样:
beforeEach(function(done) {
// Setup
socket = io.connect('http://localhost:3001', {
'reconnection delay' : 0
, 'reopen delay' : 0
, 'force new connection' : true
});
socket.on('connect', function() {
console.log('worked...');
//done();
});
socket.on('disconnect', function() {
console.log('disconnected...');
});
done();
});
我是摩卡新手,所以可能有一个非常明显的原因来发起放置done()
在套接字范围本身内。希望这个小细节能让其他跟我一样的人免于被拉扯。
对我来说,上述测试(具有正确的范围done()
)输出:
Suite of unit tests
First (hopefully useful) test
◦ Doing some things with indexOf(): worked...
✓ Doing some things with indexOf()
disconnecting...
disconnected...
◦ Doing something else with indexOf(): worked...
✓ Doing something else with indexOf()
disconnecting...
disconnected...
2 tests complete (93 ms)