10

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.

FleMo
  • 539
  • 6
  • 20

2 Answers2

20

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());
    });
});
Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
FleMo
  • 539
  • 6
  • 20
2

This is what worked for me using TypeScript

  test('connect websockets response', (done) => {
    const ws = new WebSocket(`ws://localhost:${port}`);

    const listener = (msg: MessageEvent) => {
      console.log(JSON.parse(msg.data));
      // Put you expect statement here
      ws.removeEventListener('message', listener);
      ws.close();
    };

    ws.addEventListener('message', listener);

    ws.addEventListener('close', () => done());
  }, 30000);
klugjo
  • 19,422
  • 8
  • 57
  • 75