我有以下TypeScript和nodeJS文件,它注册了一系列socket.io名称空间。然后,我有一些测试这些名称空间的mocha测试,但是,我的第一次测试总是失败,除非我正在重新加载,在这种情况下第二次测试将通过。注意:db.Line.findAll()
和类似的函数是返回promise的sequelize函数。
export class RealTimeStations {
public complete: Promise<boolean>;
server: any;
constructor(io: any) {
this.server = io;
this.complete = Promise.resolve(db.Line.findAll()).then(lines => {
// do some mapping to generate routes and cells
this.registerEndPoints(routes, [], cells);
}).catch(err => console.log(err))
}
registerEndPoints(routes: Array<string>, nsps: Array<any>, cells: Array<string>) {
for (let i = 0; i < routes.length; i++) {
nsps.push(this.server.of('/api/testNamespace/' + routes[i]));
let that = this;
nsp.on('connection', function (socket) {
that.emitInitialPackage(nsps[i], routes[i], cells[i]);
});
}
}
emitInitialPackage(nsp: any, name: string, cell: any) {
return db.Line.find({/* Some sequelize params*/}).then(results => {
nsp.emit('value', results);
}).catch(err => console.log(err));
}
}
之前我已经看到过这个问题,在执行测试之前没有完成socketio设置,因此我转向了基于promise的方法,但是,这个测试现在第一次失败但是第二次和之后livereloads,它通过......
describe('Stations Socket /api/getLine/stations', function () {
beforeEach(function (done) {
models.sequelize.sync({ force: true }).then(function () { //setup SQLite db
sequelize_fixtures.loadFile('C:/Users/George/Source/Repos/Coty%20Monitoring%20System/server/seeders/default.json', db) //seed the db
.then(function () {
app.set('port', '3000');
server = http.createServer(app);
server.listen('3000', function () { });
var io = require('socket.io').listen(server);
new RealTimeStations(io).complete.then(() => { //config socketio namespaces
socket = require('socket.io-client')('http://localhost:3000/api/testNamespace/2');
done();
});
});
})
})
describe('Setup', () => {
it('Should connect and receive correct state', function (done) {
socket.on('connect', function () {
socket.on('value', function (test) {
test.stations.should.equal('"expected value"');
done();
});
});
});
});
afterEach(function () {
socket.disconnect();
server.close();
socket = null;
})
})
问题是nsp.emit('value', results);
行未在complete
承诺解决之前执行。这意味着当测试开始并连接到服务器时,不会触发值事件,并且由于connect事件仅发送一次,因此测试只是超时。
所以我需要一种方法将完整的承诺链接到emitInitialPackage
承诺。