-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.test.js
More file actions
343 lines (295 loc) · 10.3 KB
/
index.test.js
File metadata and controls
343 lines (295 loc) · 10.3 KB
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
process.env.ENVIRONMENT = "test";
const { main } = require("./index");
const { mocks: sheetsMocks } = require("google-spreadsheet");
const { mocks: paypalMocks } = require("@paypal/checkout-server-sdk");
const { mocks: googleApiMock } = require("googleapis");
const { mocks: sendGridMock } = require("@sendgrid/mail");
const moment = require("moment");
const validBodyAutomatic = {
first_name: "Martin",
last_name: "Last",
school: "U of T",
program_and_college: "EngSci :)",
email: "somerandom-email-jljdsf@mail.utoronto.ca",
membership_type: "student",
orderID: "0NY62877GC1270645",
};
const validBodyManual = {
first_name: "Martin",
last_name: "Last",
school: "U of T",
program_and_college: "EngSci :)",
email: "somerandom-email-jljdsf@mail.utoronto.ca",
membership_type: "student",
manual_sign_up_password: "test-password",
};
const runFunction = (body) =>
main({ data: Buffer.from(JSON.stringify(body), "utf8") });
const last = (array) => array[array.length - 1];
/**
* This replaces the entire paypal library with our own functions
*/
jest.mock("@paypal/checkout-server-sdk", () => {
const mocks = {
getOrderAmount: jest.fn(() => {
return "25";
}),
buildClient: jest.fn(),
captureRequest: jest.fn(),
};
return {
mocks,
core: {
SandboxEnvironment: class SandboxEnvironment {
// noinspection JSUnusedGlobalSymbols
constructor(clientId, clientSecret) {
return mocks.buildClient(clientId, clientSecret);
}
},
LiveEnvironment: class LiveEnvironment {
// noinspection JSUnusedGlobalSymbols
constructor(clientId, clientSecret) {
return mocks.buildClient(clientId, clientSecret);
}
},
PayPalHttpClient: class PayPalHttpClient {
execute(request) {
if (request.name === "getOrderRequest")
return {
result: {
purchase_units: [
{ amount: { value: mocks.getOrderAmount(request) } },
],
},
};
else return mocks.captureRequest(request);
}
},
},
orders: {
OrdersGetRequest: class OrdersGetRequest {
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
constructor(orderID) {
this.name = "getOrderRequest";
}
},
OrdersCaptureRequest: class OrdersCaptureRequest {
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
constructor(orderID) {
this.name = "captureOrderRequest";
}
},
},
};
});
jest.mock("google-spreadsheet", () => {
const mocks = {
createDocConnection: jest.fn(),
addRow: jest.fn((data) => data),
};
return {
mocks,
GoogleSpreadsheet: class GoogleSpreadsheet {
// noinspection JSUnusedGlobalSymbols
constructor(spreadsheet_Id) {
this.sheetsByIndex = [{}, { addRow: mocks.addRow }];
return mocks.createDocConnection(spreadsheet_Id);
}
// noinspection JSUnusedGlobalSymbols
loadInfo() {}
},
};
});
jest.mock("@sendgrid/mail", () => {
const mocks = {
sendEmail: jest.fn(),
setApiKey: jest.fn(),
};
return {
mocks,
send: mocks.sendEmail,
setApiKey: mocks.setApiKey,
};
});
jest.mock("@google-cloud/secret-manager", () => {
const mocks = {
getSecretJson: jest.fn(() => ({
gSheetsServiceAccountEmail: null,
gSheetsServiceAccountPrivateKey: null,
payPalClientSecret: null,
payPalClientId: null,
databaseSpreadsheetId: null,
useSandbox: true,
directoryApiServiceAccountEmail: null,
directoryApiServiceAccountKey: null,
adminEmail: null,
sendGridApiKey: null,
googleGroupEmail: null,
manualSignUpPassword: "test-password",
})),
};
const versions = [
{ payload: { data: JSON.stringify(mocks.getSecretJson()) } },
];
const client = { accessSecretVersion: () => versions };
return {
mocks,
SecretManagerServiceClient: class SecretManagerServiceClient {
constructor() {
return client;
}
},
};
});
jest.mock("googleapis", () => {
const mocks = {
createAuthClient: jest.fn(),
insertMemberToGroup: jest.fn(),
};
return {
mocks,
google: {
auth: {
JWT: class JWT {
constructor(options) {
return mocks.createAuthClient(options);
}
},
},
admin: (options) => ({
members: {
insert: mocks.insertMemberToGroup,
},
}),
},
};
});
// TODO test expiry values
describe("all tests", () => {
beforeEach(() => {
jest.clearAllMocks();
});
test("should complete all steps on valid request", async () => {
await runFunction(validBodyAutomatic);
// Captures paypal payment
expect(paypalMocks.captureRequest).toHaveBeenCalledTimes(1);
// Adds the data to the database
expect(sheetsMocks.addRow).toHaveBeenCalledTimes(1);
const dataAdded = sheetsMocks.addRow.mock.calls[0][0];
expect(dataAdded).toMatchObject(validBodyAutomatic);
expect(dataAdded.creation_time).toBeCloseTo(moment().unix(), -1);
expect(dataAdded.expiry).toBeGreaterThan(moment().unix());
expect(dataAdded.payment_method).toBe("Website");
// Add the user to the google group
expect(googleApiMock.insertMemberToGroup).toHaveBeenCalledTimes(1);
const insertMemberOptions =
googleApiMock.insertMemberToGroup.mock.calls[0][0];
expect(insertMemberOptions.requestBody.email).toStrictEqual(
validBodyAutomatic.email
);
// Send the success email
// expect(sendGridMock.sendEmail).toHaveBeenCalledTimes(1);
// const sendEmailOptions = sendGridMock.sendEmail.mock.calls[0][0];
// expect(sendEmailOptions.to).toStrictEqual(validBodyAutomatic.email);
});
test("should fail if request is not a POST request or if missing orderId / membership_type / manual password", async () => {
const invalidBodies = [
{},
{ ...validBodyAutomatic, membership_type: undefined },
{ ...validBodyAutomatic, orderID: undefined },
{ ...validBodyManual, manual_sign_up_password: "wrong-password" },
{ ...validBodyManual, manual_sign_up_password: undefined },
{ ...validBodyAutomatic, membership_type: "lifetime" },
];
// Run the function for each one
await Promise.all(invalidBodies.map((body) => runFunction(body)));
expect(paypalMocks.captureRequest).not.toHaveBeenCalled();
expect(sheetsMocks.addRow).not.toHaveBeenCalled();
expect(googleApiMock.insertMemberToGroup).not.toHaveBeenCalled();
expect(sendGridMock.sendEmail).not.toHaveBeenCalled();
});
test("should fail without capturing order if order amount is different than membership_type", async () => {
paypalMocks.getOrderAmount.mockReturnValueOnce(13.3333);
await runFunction(validBodyAutomatic);
expect(paypalMocks.getOrderAmount).toHaveBeenCalledTimes(1);
expect(paypalMocks.captureRequest).not.toHaveBeenCalled();
expect(sheetsMocks.addRow).not.toHaveBeenCalled();
expect(sendGridMock.sendEmail).not.toHaveBeenCalled();
});
test("should fail without capturing order if PayPal validation request fails", async () => {
paypalMocks.getOrderAmount.mockImplementationOnce(() => {
throw new Error();
});
await runFunction(validBodyAutomatic);
expect(paypalMocks.getOrderAmount).toHaveBeenCalledTimes(1);
expect(paypalMocks.captureRequest).not.toHaveBeenCalled();
expect(sheetsMocks.addRow).not.toHaveBeenCalled();
expect(sendGridMock.sendEmail).not.toHaveBeenCalled();
});
test("should not write user to database if capturing payment fails", async () => {
paypalMocks.captureRequest.mockImplementationOnce(() => {
throw new Error();
});
await runFunction(validBodyAutomatic);
expect(paypalMocks.getOrderAmount).toHaveBeenCalledTimes(1);
expect(paypalMocks.captureRequest).toHaveBeenCalledTimes(1);
expect(sheetsMocks.addRow).not.toHaveBeenCalled();
expect(sendGridMock.sendEmail).not.toHaveBeenCalled();
});
test("should return an error if some fields are dropped when writing to database", async () => {
sheetsMocks.addRow.mockReturnValueOnce({
...validBodyAutomatic,
firstName: undefined, // override name to not exist in return value
});
await runFunction(validBodyAutomatic);
expect(paypalMocks.getOrderAmount).toHaveBeenCalledTimes(1);
expect(paypalMocks.captureRequest).toHaveBeenCalledTimes(1);
expect(sheetsMocks.addRow).toHaveBeenCalledTimes(1);
});
test("should success if email is already in google group", async () => {
class ConflictError {
constructor() {
this.response = {
status: 409,
};
}
}
googleApiMock.insertMemberToGroup.mockReturnValueOnce(new ConflictError());
await runFunction(validBodyAutomatic);
expect(googleApiMock.insertMemberToGroup).toHaveBeenCalledTimes(1);
// expect(sendGridMock.sendEmail).toHaveBeenCalledTimes(1);
});
test("should display body when error occur", async () => {
paypalMocks.getOrderAmount.mockReturnValueOnce(new Error());
console.error = jest.fn();
console.log = jest.fn();
await runFunction(validBodyAutomatic);
expect(last(console.log.mock.calls)[0]).toContain(
JSON.stringify(validBodyAutomatic)
);
});
test("should succeed if given a manual signup password", async () => {
await runFunction(validBodyManual);
// Adds the data to the database
expect(sheetsMocks.addRow).toHaveBeenCalledTimes(1);
const dataAdded = sheetsMocks.addRow.mock.calls[0][0];
expect(dataAdded).toMatchObject({
...validBodyManual,
manual_sign_up_password: undefined,
});
expect(dataAdded.creation_time).toBeCloseTo(moment().unix(), -1);
expect(dataAdded.expiry).toBeGreaterThan(moment().unix());
expect(dataAdded.payment_method).toBe("Manual (via System)");
// Add the user to the google group
expect(googleApiMock.insertMemberToGroup).toHaveBeenCalledTimes(1);
const insertMemberOptions =
googleApiMock.insertMemberToGroup.mock.calls[0][0];
expect(insertMemberOptions.requestBody.email).toStrictEqual(
validBodyAutomatic.email
);
// Send the success email
// expect(sendGridMock.sendEmail).toHaveBeenCalledTimes(1);
// const sendEmailOptions = sendGridMock.sendEmail.mock.calls[0][0];
// expect(sendEmailOptions.to).toStrictEqual(validBodyAutomatic.email);
});
});