经过进一步的摸索和探索,我发现了一些非常有用的信息。在作者的示例中,他指出了在 before
钩子中建立套接字侦听器的关键步骤。
此示例有效:
假设一个服务器监听的套接字连接
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()在
beforeEach,
socket.on('connect'...)监听器是具有连接得到建立至关重要。例如,如果您done()在侦听器中将其注释掉,然后将其添加到一个作用域中(
就在退出之前
beforeEach),则会看到 “ no connection to break …” 消息,而不是 “
disconnecting …” 消息。像这样:
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();});我是Mocha的新手,因此可能有一个很明显的原因要让启动程序放置
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)



