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.
If using Jest test framework, you can turn off all console messages by one command: jest --silent .
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.
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());
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With