-
Notifications
You must be signed in to change notification settings - Fork 0
/
vitest.global-setup.ts
65 lines (53 loc) · 1.77 KB
/
vitest.global-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
/* eslint-disable functional/no-let */
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable no-undef */
import type { ChildProcessWithoutNullStreams } from 'child_process';
import { spawn } from 'child_process';
import fetch from 'cross-fetch';
const getRandomInt = (min, max) => {
const ceiledMin = Math.ceil(min);
const flooredMax = Math.floor(max);
return Math.floor(Math.random() * (flooredMax - ceiledMin + 1)) + ceiledMin;
};
const testServerHost = '127.0.0.1';
const testServerPort = getRandomInt(49152, 65535);
const timeout = 20000;
const iterationTimeout = 500;
const startServer = async () => {
console.log(process.argv[0]);
const child = spawn(process.argv[0], ['--loader', 'ts-node/esm', 'bootstrap/index.ts'], {
env: {
NODE_ENV: 'test',
MONGO_URI: process.env.MONGO_URI,
SERVER_HOST: testServerHost,
SERVER_PORT: `${testServerPort}`,
},
detached: true,
}).once('error', (e) => {
throw e;
});
for (let i = timeout; i > 0; i -= iterationTimeout) {
try {
await fetch(`http://${testServerHost}:${testServerPort}`);
return child;
} catch (e) {
if (e.code === 'ECONNREFUSED') {
console.log('wait for test server to be up and running...');
await new Promise((resolve) => setTimeout(resolve, iterationTimeout));
} else {
throw e;
}
}
}
throw new Error('Timeout in starting the server');
};
// eslint-disable-next-line functional/no-let
let httpServer: ChildProcessWithoutNullStreams;
export const setup = async () => {
httpServer = await startServer();
// eslint-disable-next-line functional/immutable-data
process.env.HTTP_URI = `http://${testServerHost}:${testServerPort}`;
};
export const teardown = async () => {
httpServer.kill();
};