-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjest.environment.ts
258 lines (231 loc) · 6.97 KB
/
jest.environment.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { TestcontainersEnvironment } from '@trendyol/jest-testcontainers';
import { createPool, DatabasePoolType } from 'slonik';
import { Migration, setupSlonikMigrator, SlonikMigrator } from '@slonik/migrator';
import getPort from 'get-port';
import path from 'path';
import { Server, IncomingMessage } from 'http';
import { createApp } from './src/app';
import Koa, { Response } from 'koa';
import { mockJWT } from './src/utility/mock-jwt';
import { Transform } from 'stream';
// @ts-ignore
import MockReq from 'mock-req';
// @ts-ignore
import MockRes from 'mock-res';
import compose from 'koa-compose';
import { AppConfig } from './src/types';
import { WorkerOptions } from 'bullmq';
type NewIncomingMessage = IncomingMessage & Transform;
type MiniApi = {
get(endpoint: string): Promise<Response>;
delete(endpoint: string): Promise<Response>;
post(endpoint: string, data?: any): Promise<Response>;
put(endpoint: string, data?: any): Promise<Response>;
};
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace NodeJS {
interface Global {
postgres: DatabasePoolType;
makeRequest: (
requestOptions: {
method: string;
url: string;
headers?: Record<string, string>;
},
user?: Partial<{ name: string; scope: string; iss: string; sub: string }>,
cb?: (req: NewIncomingMessage) => void | Promise<void>
) => Promise<Koa.Response>;
setApp: (setup: (config: any) => Koa | Promise<Koa>) => Promise<void>;
asAdmin: MiniApi;
asUser: (user: Partial<{ name: string; scope: string; iss: string; sub: string }>) => MiniApi;
__TESTCONTAINERS__: Array<any>;
__TESTCONTAINERS_POSTGRES_IP__: string;
__TESTCONTAINERS_REDIS_IP__: string;
__TESTCONTAINERS_POSTGRES_NAME__: string;
__TESTCONTAINERS_POSTGRES_PORT_5432__: number;
__TESTCONTAINERS_REDIS_PORT_6379__: number;
workerOptions: WorkerOptions;
}
}
}
class TaskAPIEnvironment extends TestcontainersEnvironment {
migrator?: SlonikMigrator;
serverListener?: Server;
migrations: Migration[] = [];
app?: Koa;
postgresUri!: string;
async setup() {
await super.setup();
const pgHost = this.global.__TESTCONTAINERS_POSTGRES_IP__;
const pgPort = this.global.__TESTCONTAINERS_POSTGRES_PORT_5432__;
const redisHost = this.global.__TESTCONTAINERS_REDIS_IP__;
const redisPort = this.global.__TESTCONTAINERS_REDIS_PORT_6379__;
// @ts-ignore
this.postgresUri = `postgresql://postgres:postgres@${pgHost}:${pgPort}/postgres`;
const slonik = createPool(this.postgresUri);
this.migrator = setupSlonikMigrator({
migrationsPath: path.join(process.cwd(), '/migrations'),
slonik,
mainModule: module,
log: () => {
//...
},
});
this.migrations = await this.migrator.up();
this.global.workerOptions = {
connection: {
host: redisHost,
port: redisPort,
db: 2,
},
};
this.global.setApp = async (cb: (options: AppConfig) => Koa | Promise<Koa>) => {
await this.setApp(
await cb({
postgres: this.postgresUri,
env: 'test',
queueList: ['jest'],
migrate: false,
enableQueue: true,
redis: {
host: redisHost,
port: redisPort,
db: 2,
},
})
);
};
// Set up globals.
this.global.postgres = slonik;
this.global.makeRequest = async (
requestOptions: {
method: string;
url: string;
},
user?: Partial<{ name: string; scope: string; iss: string; sub: string }>,
cb?: (req: NewIncomingMessage) => void | Promise<void>
) => {
const req = new MockReq(requestOptions);
req.headers.Accept = req.headers.accept = 'application/json';
req.headers['content-type'] = req.headers['Content-Type'] = 'application/json';
req.headers['transfer-encoding'] = req.headers['Transfer-Encoding'] = 'chunked';
req.headers.authorization = req.headers.Authorization = `Bearer ${mockJWT({
name: 'admin',
scope: 'tasks.admin',
iss: 'urn:madoc:site:456',
sub: 'urn:madoc:user:123',
...(user || {}),
})}`;
const res = new MockRes();
req.rawHeaders.push('Authorization', 'Content-Type', 'Accept', 'Transfer-Encoding');
if (cb) {
await cb(req as NewIncomingMessage);
}
const app = await this.getApp();
const fn = compose(app.middleware);
const ctx = app.createContext(req, res);
await (app as any).handleRequest(ctx, fn);
if (ctx.response.body && ctx.response.is('application/json')) {
ctx.response.body = JSON.parse(ctx.response.body as any);
}
return ctx.response;
};
this.global.asUser = (user: Partial<{ name: string; scope: string; iss: string; sub: string }>) => {
return {
get: (url: string) => {
return this.global.makeRequest(
{
method: 'GET',
url,
},
user
);
},
put: (url: string, data?: any) => {
return this.global.makeRequest(
{
method: 'PUT',
url,
},
user,
req => {
if (data) {
req.write(data);
}
req.end();
}
);
},
post: (url: string, data?: any) => {
return this.global.makeRequest(
{
method: 'POST',
url,
},
user,
req => {
if (data) {
req.write(data);
}
req.end();
}
);
},
delete: (url: string) => {
return this.global.makeRequest(
{
method: 'DELETE',
url,
},
user
);
},
};
};
this.global.asAdmin = this.global.asUser({});
}
async setApp(app: Koa) {
// Stop existing
await this.stopApp();
const tasksPort = await getPort();
this.serverListener = app.listen(tasksPort);
this.global.tasksPort = tasksPort;
this.global.tasksApp = app;
this.app = app;
}
async getApp() {
if (!this.app) {
const app = await createApp({
postgres: this.postgresUri,
env: 'test',
queueList: [],
migrate: false,
});
await this.setApp(app);
return app;
}
return this.app as Koa;
}
async stopApp() {
await new Promise<void>(resolve => {
if (this.serverListener) {
this.serverListener.close(() => {
resolve();
});
} else {
resolve();
}
});
}
async teardown() {
await super.teardown();
await this.stopApp();
if (this.migrator) {
for (const migration of this.migrations.reverse()) {
await this.migrator.down(migration.file);
}
}
}
}
module.exports = TaskAPIEnvironment;