Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Jest from hanging when testing WebSockets?

Tags:

node.js

jestjs

ws

I created an app in node.js which gives me a WebSocket interface using the 'ws' package from NPM on the server. Now I want to test this interface with Jest. The test runs successful but Jest does not exit and gives me the error:

Jest did not exit one second after the test run has completed.

I read the documentation and found that I have to use the done parameter in the test and call it when the test has finished.

The server will be started in the beforeAll function and stopped in the afterAll function given by Jest.

describe('app', () => {
    it('connect websockets response' (done), => {
        expect.assertions(1);

        new WebSocket(`ws://localhost:${port}`).on('message' (msg), => {
                expect(JSON.parse(msg).id).toEqual(0);
                done();
            })
    });
});

I expect that Jest stops successful after the test has finished.

like image 575
FleMo Avatar asked May 03 '19 05:05

FleMo


People also ask

How do I stop jest test?

If using Jest test framework, you can turn off all console messages by one command: jest --silent .

What causes WebSocket disconnect?

By default, if a ping has not been received in 60 seconds, and the connection has been otherwise inactive, the platform will close the WebSocket. This timeout is configurable in the WS Communication Subsystem configuration, Idle Connection Timeout (sec) parameter.


1 Answers

I have learned that I have to close the WebSocket connection in the test itself, and wait for the closing event.

describe('app', () => {
    it('connect websockets response', (done) => {
        expect.assertions(1);

        const ws = new WebSocket(`ws://localhost:${port}`)
            .on('message', (msg) => {
                expect(JSON.parse(msg).id).toEqual(0);
                ws.close();
            })
            .on('close', () => done());
    });
});
like image 171
FleMo Avatar answered Sep 21 '22 04:09

FleMo