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