I am setting up a test suite using jest for a node/socket.io app.
When I test server -> client communication, everything works as expected.
When I test client -> server communication, my test suite is passing with a false positive:
This is the test that is producting a false positive:
test('should communicate with waiting for socket.io handshakes', (done) => {
client.emit('example', 'some message');
setTimeout(() => {
server.on('example', (message) => {
expect(message).toBe('some message')
})
done();
}, 50);
});
This is my entire test suite:
import io from 'socket.io-client';
import * as http from 'http';
import ioBack from 'socket.io';
let client;
let httpServer;
let httpServerAddr;
let server;
/**
* Setup WS & HTTP servers
*/
beforeAll((done) => {
httpServer = http.createServer().listen();
httpServerAddr = httpServer.address();
server = ioBack(httpServer);
done();
});
/**
* Cleanup WS & HTTP servers
*/
afterAll((done) => {
server.close();
httpServer.close();
done();
});
/**
* Run before each test
*/
beforeEach((done) => {
// Setup
// Do not hardcode server port and address, square brackets are used for IPv6
client = io.connect(`http://[${httpServerAddr.address}]:${httpServerAddr.port}`, {
'reconnection delay': 0,
'reopen delay': 0,
'force new connection': true,
transports: ['websocket'],
});
client.on('connect', () => {
done();
});
});
/**
* Run after each test
*/
afterEach((done) => {
// Cleanup
if (client.connected) {
client.disconnect();
}
done();
});
describe('basic socket.io example', () => {
test('should communicate', (done) => {
// once connected, emit Hello World
server.emit('echo', 'Hello World');
client.on('echo', (message) => {
// Check that the message matches
expect(message).toBe('Hello World');
done();
});
server.on('connection', (mySocket) => {
expect(mySocket).toBeDefined();
});
});
test('should communicate with waiting for socket.io handshakes', (done) => {
client.emit('example', 'some message');
setTimeout(() => {
server.on('example', (message) => {
expect(message).toBe('some incorrect message')
})
done();
}, 50);
});
});
I am not sure why I am getting a false positive.
Aucun commentaire:
Enregistrer un commentaire