Reputation: 5
I'm writing tests for client-side socket communication with socket.io. I'm trying to test connection and other effects that rely on the socket receiving events from the server. I tried to write a server for my jest tests, but the server doesn't start.
Here's a sample of the code:
describe('App Communication', () => {
/* Testing flags */
let hasConnected = false;
/* Create server */
const httpServer = createServer();
const sampleMessage = 'Hello world!';
const io = new Server(httpServer);
beforeAll(() => {
httpServer.listen('4000', () => {
console.log('listening on 4000');
io.on('connection', (socket) => {
hasConnected = true;
socket.emit('message', sampleMessage);
socket.on('message', (message) => {
...
});
});
});
});
...
Is there any way to get the server up and running?
Upvotes: 0
Views: 924
Reputation: 1610
httpServer.listen
is asynchronous, so you need to tell Jest to wait until the server starts before running test cases:
beforeAll((done) => { // Jest will wait until `done` is called
httpServer.listen('4000', () => {
console.log('listening on 4000');
io.on('connection', (socket) => {
hasConnected = true;
socket.emit('message', sampleMessage);
socket.on('message', (message) => {
...
});
});
done();
});
});
it('should connect to socket', () => {
// Connect to localhost:4000 here
});
Upvotes: 1