-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathjest.setup.mongo-repl-set.js
49 lines (37 loc) · 1.27 KB
/
jest.setup.mongo-repl-set.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const { MongoClient } = require('mongodb');
let admin;
let connection;
beforeAll(async () => {
connection = await MongoClient.connect("mongodb://127.0.0.1:55010/hawk?", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
admin = connection.db().admin();
try {
let status = await admin.command({ replSetGetStatus: 1 }).catch(() => null);
if (status && status.ok) {
console.log("✅ Replica set already initialized");
} else {
await admin.command({ replSetInitiate: {} });
console.log("✅ Replica set initiated");
}
const startTime = Date.now();
const timeout = 15000;
/**
* Wait for the replica set to initialize all nodes
*/
do {
await new Promise(resolve => setTimeout(resolve, 1000));
status = await admin.command({ replSetGetStatus: 1 });
const primary = status.members.find(member => member.stateStr === "PRIMARY");
const secondary = status.members.find(member => member.stateStr === "SECONDARY");
if (primary && secondary) break;
} while (Date.now() - startTime < timeout);
console.log("✅ Replica set is stable");
} catch (err) {
console.error('❌ Failed to initiate replica set:', err);
}
}, 30000);
afterAll(async () => {
await connection.close();
});