我编写了一个小应用程序来学习Socket.IO以及如何对其进行测试。该应用程序仅包含一个服务器文件和一个测试文件。
这是服务器文件:
const app = require('express')();
const http = require('http').createServer(app);
const socketio = require('socket.io')(http);
const io = socketio.listen(http);
io.on('connection', (socket) => {
delete io.sockets.connected[socket.id];
const auth_timeout = setTimeout(() => {
socket.disconnect('unauthorized');
}, 1000);
function authenticate(data) {
clearTimeout(auth_timeout);
if (!data.uName || data.uName !== 'Bill') {
socket.emit('disconnectAlert', 'Unauthorized: uName is not Bill');
socket.disconnect('unauthorized');
} else {
io.sockets.connected[socket.id] = socket;
socket.on('disconnect', () => {
console.log('Disconnected');
});
socket.emit('authenticated');
}
}
socket.on('authenticate', authenticate);
});
function close() {
io.close();
http.close();
}
module.exports = {
server: http,
close
};
测试文件如下:
const { expect } = require('chai');
const io = require('socket.io-client');
const app = require('./app');
const socketURL = 'http://localhost:3000';
describe('Socket.IO authentication', function() {
let client;
before(async function(){
await app.server.listen(3000);
console.log('server started');
});
after(function(){
app.close();
});
afterEach(function(){
client.disconnect();
client.close();
});
it('Should connect in two steps', function(done){
client = io.connect(socketURL);
let passed = false;
client.on('connect', () => {
client.emit('authenticate', { uName: 'Bill' });
});
client.on('authenticated', () => {
expect(true, 'Authenticated').to.be.true;
passed = true;
done();
});
client.on('disconnect', () => {
expect(passed, 'Not Authenticated').to.be.true;
if (!passed) {
done();
}
});
});
it('Should be rejected if uName is not Bill', function(done) {
client = io.connect(socketURL);
client.on('connect', () => {
client.emit('authenticate', { uName: 'Mariko' });
});
client.on('authenticated', () => {
expect(false, 'Was authenticated').to.be.true;
done();
});
client.on('disconnectAlert', (msg) => {
console.log('Inside the test');
expect(msg).to.be.equal('Unauthorized: uName is not Bill');
done();
});
});
});
两个测试均通过。但是,在第二项测试中使摩卡无法退出。当我仅运行第一个测试时,一切都会顺利进行-测试通过,摩卡退出。但是,当我运行两个测试或仅运行第二个测试时,尽管它通过了,但摩卡卡住了。
有人能看到我在这里做错了什么导致此问题吗?谢谢。