Skip to content

Commit 4e56482

Browse files
authored
test(NODE-5724): heartbeat started is emitted before socket is connected (#3960)
1 parent 3fdac52 commit 4e56482

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { expect } from 'chai';
2+
import { once } from 'events';
3+
import { createServer, type Server } from 'net';
4+
5+
import { MongoClient, SERVER_HEARTBEAT_FAILED, SERVER_HEARTBEAT_STARTED } from '../../mongodb';
6+
7+
describe('Heartbeat tests', function () {
8+
let client: MongoClient;
9+
// Mock server
10+
let server: Server;
11+
// Shared array
12+
const events: string[] = [];
13+
const PORT = 9999;
14+
const CONN_STRING = `mongodb://localhost:${PORT}`;
15+
16+
beforeEach(async function () {
17+
// Create TCP server that responds to hellos by closing the connection
18+
// and pushing "client connection created" to shared array
19+
server = createServer(clientSocket => {
20+
events.push('client connected');
21+
22+
clientSocket.once('data', () => {
23+
events.push('client hello received');
24+
clientSocket.destroy();
25+
});
26+
});
27+
server.listen(PORT);
28+
29+
await once(server, 'listening');
30+
31+
// set up client to connect to mock server with the following configuration
32+
// {
33+
// serverSelectionTimeoutMS: 500,
34+
// }
35+
client = new MongoClient(CONN_STRING, {
36+
serverSelectionTimeoutMS: 500
37+
});
38+
39+
// Listen to `ServerHeartbeatStartedEvent` and `ServerHeartbeatSucceededEvent`, pushing the
40+
// event name to the shared array when event is emitted
41+
for (const e of [SERVER_HEARTBEAT_STARTED, SERVER_HEARTBEAT_FAILED]) {
42+
client.on(e, () => {
43+
events.push(e);
44+
});
45+
}
46+
});
47+
48+
afterEach(async function () {
49+
if (server.listening) server.close();
50+
});
51+
52+
it('emits the first HeartbeatStartedEvent before the monitoring socket was created', async function () {
53+
// Attempt to connect to mock server
54+
const maybeError = await client.connect().catch(e => e);
55+
// Catch error
56+
expect(maybeError).to.be.instanceOf(Error);
57+
58+
expect(events).to.deep.equal([
59+
SERVER_HEARTBEAT_STARTED,
60+
'client connected',
61+
'client hello received',
62+
SERVER_HEARTBEAT_FAILED
63+
]);
64+
});
65+
});

0 commit comments

Comments
 (0)