-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathjest.setup.ts
85 lines (71 loc) · 2.23 KB
/
jest.setup.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Runs INDIVIDUALLY for each test suite (each FILE, not test) before tests run
import { beforeEach, afterAll, expect, jest } from "@jest/globals";
import { MongoMemoryServer } from "mongodb-memory-server";
import * as Config from "./src/common/config.js";
import mongoose from "mongoose";
import { MatcherState } from "expect";
function mockConfig(dbUrl: string) {
jest.mock("./src/common/config.js", () => {
const actual = jest.requireActual("./src/common/config.js") as typeof Config;
const newConfig: typeof Config.default = {
...actual.default,
TEST: true,
DB_URL: dbUrl,
};
return {
...actual,
default: newConfig,
__esModule: true,
};
});
}
function getIdForState(state: MatcherState): string {
return `${state.testPath}: ${state.currentTestName}`;
}
const tests = new Set<string>();
let mongod: MongoMemoryServer | undefined = undefined;
// Need to retry because sometimes for some ports this fails randomly
// This fixes that
const MAX_RETRIES = 25;
async function makeMongod() {
let retries = 0;
while (true) {
try {
return await MongoMemoryServer.create();
} catch (e) {
if (retries == MAX_RETRIES) {
throw new Error(`Failed to create mongod server ${retries} times: ${e}`);
}
}
retries += 1;
}
}
beforeEach(async () => {
const state = expect.getState();
const id = getIdForState(state);
if (tests.has(id)) {
throw new Error(`Tests within the same file cannot have the same name, please rename: ${id}`);
} else {
tests.add(id);
}
if (!mongod) {
mongod = await makeMongod();
}
const dbName = `${tests.size}`;
const uri = `${mongod.getUri()}${dbName}`;
if (mongoose.connections.length > 0) {
await mongoose.disconnect();
}
await mongoose.connect(`${uri}${Config.default.DB_PARAMS}`);
mockConfig(uri);
});
afterAll(async () => {
for (const connection of mongoose.connections) {
await connection.dropDatabase();
await connection.destroy();
}
await mongoose.disconnect();
if (mongod) {
await mongod.stop();
}
});