Archan Lagoo
Archan Lagoo

Reputation: 5

Unable to run socket.io server in jest for testing client-side socket communication in React

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

Answers (1)

Alan Friedman
Alan Friedman

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

Related Questions