forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjest.utils.ts
218 lines (191 loc) · 5.66 KB
/
jest.utils.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
import request from 'supertest';
import { build } from './src/app';
import { createUserInput } from './src/utils/create-user';
import { examJson } from './__mocks__/exam';
type FastifyTestInstance = Awaited<ReturnType<typeof build>>;
declare global {
// eslint-disable-next-line no-var
var fastifyTestInstance: FastifyTestInstance;
}
type Options = {
sendCSRFToken?: boolean;
} & Record<string, unknown>;
const requests = {
GET: (resource: string) => request(fastifyTestInstance?.server).get(resource),
POST: (resource: string) =>
request(fastifyTestInstance?.server).post(resource),
PUT: (resource: string) => request(fastifyTestInstance?.server).put(resource),
DELETE: (resource: string) =>
request(fastifyTestInstance?.server).delete(resource)
};
export const getCsrfToken = (setCookies: string[]): string | undefined => {
const csrfSetCookie = setCookies.find(str => str.includes('csrf_token'));
const [csrfCookie] = csrfSetCookie?.split(';') ?? [];
const [_key, csrfToken] = csrfCookie?.split('=') ?? [];
return csrfToken;
};
export const ORIGIN = 'https://www.freecodecamp.org';
export function superRequest(
resource: string,
config: {
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
setCookies?: string[];
},
options?: Options
): request.Test {
const { method, setCookies } = config;
const { sendCSRFToken = true } = options ?? {};
const req = requests[method](resource).set('Origin', ORIGIN);
if (setCookies) {
void req.set('Cookie', setCookies);
}
const csrfToken = (setCookies && getCsrfToken(setCookies)) ?? '';
if (sendCSRFToken) {
void req.set('CSRF-Token', csrfToken);
}
return req;
}
export function createSuperRequest(config: {
method: 'GET' | 'POST' | 'PUT' | 'DELETE';
setCookies?: string[];
}): (resource: string, options?: Options) => request.Test {
return (resource, options) => superRequest(resource, config, options);
}
type IndexData = {
collection: string;
indexes: {
key: Record<string, 1>;
name: string;
expireAfterSeconds?: number;
}[];
};
const indexData: IndexData[] = [
{
collection: 'AccessToken',
indexes: [
{
key: { userId: 1 },
name: 'userId_1'
}
]
},
{
collection: 'Donation',
indexes: [
{ key: { email: 1 }, name: 'email_1' },
{ key: { userId: 1 }, name: 'userId_1' }
]
},
{
collection: 'MsUsername',
indexes: [{ key: { userId: 1, id: 1 }, name: 'userId_1__id_1' }]
},
{
collection: 'Survey',
indexes: [{ key: { userId: 1 }, name: 'userId_1' }]
},
{
collection: 'UserRateLimit',
indexes: [
{
key: { expirationDate: 1 },
name: 'expirationDate_1',
expireAfterSeconds: 0
}
]
},
{
collection: 'UserToken',
indexes: [{ key: { userId: 1 }, name: 'userId_1' }]
},
{
collection: 'sessions',
indexes: [
{
key: { expires: 1 },
name: 'expires_1',
expireAfterSeconds: 0
}
]
},
{
collection: 'user',
indexes: [
{
key: { email: 1, sendQuincyEmail: 1 },
name: 'mailing-list-pull'
},
{ key: { email: 1 }, name: 'email_1' },
{ key: { isDonating: 1 }, name: 'isDonating_1' },
{ key: { username: 1, id: 1 }, name: 'username_1__id_1' }
]
}
];
export function setupServer(): void {
let fastify: FastifyTestInstance;
beforeAll(async () => {
fastify = await build();
await fastify.ready();
// Prisma does not support TTL indexes in the schema yet, so, to avoid
// conflicts with the TTL index in the sessions collection, we need to
// create it manually (before interacting with the db in any way). Also,
// to save time, we create all other indexes so we don't need to invoke
// `prisma db push` (which is relatively slow).
await Promise.all(
indexData.map(async ({ collection, indexes }) => {
await fastify.prisma.$runCommandRaw({
createIndexes: collection,
indexes
});
})
);
global.fastifyTestInstance = fastify;
// allow a little time to setup the db
}, 10000);
afterAll(async () => {
if (!global.fastifyTestInstance)
throw Error(`fastifyTestInstance was not created. Typically this means that something went wrong when building the fastify instance.
If you are seeing this error, the root cause is likely an error thrown in the beforeAll hook.`);
await fastifyTestInstance.prisma.$runCommandRaw({ dropDatabase: 1 });
// Due to a prisma bug, this is not enough, we need to --force-exit jest:
// https://github.com/prisma/prisma/issues/18146
await fastifyTestInstance.close();
});
}
export const defaultUserId = '64c7810107dd4782d32baee7';
export const defaultUserEmail = 'foo@bar.com';
export async function devLogin(): Promise<string[]> {
await fastifyTestInstance.prisma.user.deleteMany({
where: { email: 'foo@bar.com' }
});
await fastifyTestInstance.prisma.user.create({
data: {
...createUserInput(defaultUserEmail),
id: defaultUserId
}
});
const res = await superRequest('/signin', { method: 'GET' });
expect(res.status).toBe(302);
return res.get('Set-Cookie');
}
export async function seedExam(): Promise<void> {
const query = { where: { id: examJson.id } };
const testExamExists =
await fastifyTestInstance.prisma.exam.findUnique(query);
if (testExamExists) {
await fastifyTestInstance.prisma.exam.deleteMany(query);
}
await fastifyTestInstance.prisma.exam.create({
data: {
...examJson
}
});
}
export function createFetchMock({ ok = true, body = {} } = {}) {
return jest.fn().mockResolvedValue(
Promise.resolve({
ok,
json: () => Promise.resolve(body)
})
);
}