-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-db-setup.js
55 lines (50 loc) · 1.5 KB
/
test-db-setup.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
50
51
52
53
54
55
const mongoose = require("mongoose");
mongoose.set("useCreateIndex", true);
mongoose.promise = global.Promise;
async function removeAllCollections() {
const collections = Object.keys(mongoose.connection.collections);
for (const collectionName of collections) {
const collection = mongoose.connection.collections[collectionName];
await collection.deleteMany();
}
}
async function dropAllCollections() {
const collections = Object.keys(mongoose.connection.collections);
for (const collectionName of collections) {
const collection = mongoose.connection.collections[collectionName];
try {
await collection.drop();
} catch (error) {
// Sometimes this error happens, but you can safely ignore it
if (error.message === "ns not found") return;
// This error occurs when you use it.todo. You can
// safely ignore this error too
if (error.message.includes("a background operation is currently running"))
return;
console.log(error.message);
}
}
}
module.exports = {
setupDB(databaseName) {
// Connect to Mongoose
beforeAll(async () => {
const url = process.env.DB_URL ?? `mongodb://127.0.0.1/${databaseName}`;
await mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
});
// Clear collections after each test
afterEach(() => {
return removeAllCollections();
});
// Disconnect Mongoose
afterAll(async () => {
await dropAllCollections();
await mongoose.connection.close();
});
},
removeAllCollections,
};