-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapiFunctions.test.tsx
More file actions
525 lines (454 loc) · 14.9 KB
/
apiFunctions.test.tsx
File metadata and controls
525 lines (454 loc) · 14.9 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import {
recoverPassword,
registerAccount,
resetPassword,
resetRecoveredPassword,
updateEntryName,
updateUserEmail,
} from './apiFunctions';
import { IUser } from './apiFunctions.interface';
import { account, databases, ID } from './config';
const apiFunctions = require('./apiFunctions');
import { getBaseURL } from '@/utils/getBaseUrl';
import { Collection } from './apiFunctions.enum';
import { Query } from 'appwrite';
jest.mock('./apiFunctions', () => {
const actualModule = jest.requireActual('./apiFunctions');
return {
...actualModule,
createWeeklyPicks: jest.fn(),
getUserWeeklyPick: jest.fn(),
getAllWeeklyPicks: jest.fn(),
getCurrentUserEntries: jest.fn(),
getAllLeagues: jest.fn(),
getUserDocumentId: jest.fn(),
addUserToLeague: jest.fn(),
updateEntryName: jest.fn(),
};
});
jest.mock('@/utils/getBaseUrl', () => ({
getBaseURL: jest.fn(),
}));
jest.mock('./config', () => ({
account: {
create: jest.fn(),
createRecovery: jest.fn(),
updateEmail: jest.fn(),
updatePassword: jest.fn(),
updateRecovery: jest.fn(),
},
appwriteConfig: {
databaseId: 'mock-database-id',
},
databases: {
listDocuments: jest.fn(),
updateDocument: jest.fn(),
},
ID: {
unique: jest.fn(),
},
}));
describe('apiFunctions', () => {
describe('Authentication Functions', () => {
const mockBaseURL = 'http://example.com';
const mockEmail = 'test@example.com';
const mockPassword = 'newPassword123';
const mockRecoveryToken = { userId: '123', secret: 'abc123' };
const mockToken = 'abc123';
const mockUserId = '123';
const mockUniqueId = 'unique123';
beforeEach(() => {
jest.clearAllMocks();
(getBaseURL as jest.MockedFunction<typeof getBaseURL>).mockReturnValue(
mockBaseURL,
);
});
describe('registerAccount', () => {
it('should successfully register a new account', async () => {
const mockUser: IUser = {
documentId: '123',
id: mockUniqueId,
email: mockEmail,
leagues: [],
};
(ID.unique as jest.Mock).mockReturnValue(mockUniqueId);
(account.create as jest.Mock).mockResolvedValue(mockUser);
const result = await registerAccount({
email: mockEmail,
password: mockPassword,
});
expect(account.create).toHaveBeenCalledWith(
mockUniqueId,
mockEmail,
mockPassword,
);
expect(result).toEqual(mockUser);
});
it('should throw an error if registration fails', async () => {
(account.create as jest.Mock).mockRejectedValue(
new Error('Registration failed'),
);
await expect(
registerAccount({ email: mockEmail, password: mockPassword }),
).rejects.toThrow('Error registering user');
expect(ID.unique).toHaveBeenCalledTimes(1);
expect(account.create).toHaveBeenCalledWith(
mockUniqueId,
mockEmail,
mockPassword,
);
});
});
describe('recoverPassword', () => {
it('should successfully create a recovery token', async () => {
(account.createRecovery as jest.Mock).mockResolvedValue(
mockRecoveryToken,
);
const result = await recoverPassword({ email: mockEmail });
expect(getBaseURL).toHaveBeenCalledTimes(1);
expect(account.createRecovery).toHaveBeenCalledWith(
mockEmail,
`${mockBaseURL}/account/recovery`,
);
expect(result).toEqual(mockRecoveryToken);
});
it('should throw an error if recovery creation fails', async () => {
const mockError = new Error('Recovery creation failed');
(account.createRecovery as jest.Mock).mockRejectedValue(mockError);
await expect(recoverPassword({ email: mockEmail })).rejects.toThrow();
expect(getBaseURL).toHaveBeenCalledTimes(1);
expect(account.createRecovery).toHaveBeenCalledWith(
mockEmail,
`${mockBaseURL}/account/recovery`,
);
});
});
describe('resetRecoveredPassword', () => {
it('should successfully reset the password', async () => {
(account.updateRecovery as jest.Mock).mockResolvedValue(
mockRecoveryToken,
);
const result = await resetRecoveredPassword({
userId: mockUserId,
token: mockToken,
password: mockPassword,
});
expect(account.updateRecovery).toHaveBeenCalledWith(
mockUserId,
mockToken,
mockPassword,
);
expect(result).toEqual(mockRecoveryToken);
});
it('should throw an error if password reset fails', async () => {
const mockError = new Error('Password reset failed');
(account.updateRecovery as jest.Mock).mockRejectedValue(mockError);
await expect(
resetRecoveredPassword({
userId: mockUserId,
token: mockToken,
password: mockPassword,
}),
).rejects.toThrow();
expect(account.updateRecovery).toHaveBeenCalledWith(
mockUserId,
mockToken,
mockPassword,
);
});
});
describe('updateUserEmail', () => {
const mockNewEmail = 'new@example.com';
const mockPassword = 'password123';
const mockUserId = '123';
const mockDocumentId = '456';
it("should successfully update the user's email", async () => {
(account.updateEmail as jest.Mock).mockResolvedValue({
$id: mockUserId,
});
(databases.listDocuments as jest.Mock).mockResolvedValue({
documents: [
{
$id: mockDocumentId,
name: 'Test User',
email: 'old@example.com',
labels: '',
userId: mockUserId,
leagues: [],
},
],
});
(databases.updateDocument as jest.Mock).mockResolvedValue({});
await updateUserEmail({
email: mockNewEmail,
password: mockPassword,
});
expect(account.updateEmail).toHaveBeenCalledWith(
mockNewEmail,
mockPassword,
);
expect(databases.listDocuments).toHaveBeenCalledWith(
'mock-database-id',
Collection.USERS,
[Query.equal('userId', mockUserId)],
);
expect(databases.updateDocument).toHaveBeenCalledWith(
'mock-database-id',
Collection.USERS,
mockDocumentId,
{
email: mockNewEmail,
name: 'Test User',
labels: '',
userId: mockUserId,
leagues: [],
},
);
});
it('should throw an error if updating email fails', async () => {
(account.updateEmail as jest.Mock).mockRejectedValue(new Error());
await expect(
updateUserEmail({
email: mockNewEmail,
password: mockPassword,
}),
).rejects.toThrow();
expect(account.updateEmail).toHaveBeenCalledWith(
mockNewEmail,
mockPassword,
);
expect(databases.listDocuments).not.toHaveBeenCalled();
expect(databases.updateDocument).not.toHaveBeenCalled();
});
});
describe('resetPassword', () => {
it('should successfully reset the password', async () => {
(account.updatePassword as jest.Mock).mockResolvedValue({});
await resetPassword({
newPassword: 'newPassword123',
oldPassword: 'oldPassword123',
});
expect(account.updatePassword).toHaveBeenCalledWith(
'newPassword123',
'oldPassword123',
);
});
});
it('should throw an error if resetting password fails', async () => {
(account.updatePassword as jest.Mock).mockRejectedValue(new Error());
await expect(
resetPassword({
newPassword: 'newPassword123',
oldPassword: 'oldPassword123',
}),
).rejects.toThrow();
expect(account.updatePassword).toHaveBeenCalledWith(
'newPassword123',
'oldPassword123',
);
});
});
describe('Get Weekly Picks Mock function', () => {
it('should mock getWeeklyPicks function', async () => {
const users = { $id: '663130a100297f77c3c8' };
const resp = { data: users };
apiFunctions.getUserWeeklyPick.mockResolvedValue(resp);
const result = await apiFunctions.getUserWeeklyPick({
userId: '66281d5ec5614f76bc91',
weekNumber: '6622c75658b8df4c4612',
});
expect(result).toEqual(resp);
});
});
describe('Create Weekly Picks Mock Function', () => {
it('should mock createWeeklyPicks function', async () => {
const users = { team: '66218f22b40deef340f8', correct: false };
const resp = { data: users };
apiFunctions.createWeeklyPicks.mockResolvedValue(resp);
const result = await apiFunctions.createWeeklyPicks({
gameWeekId: '6622c7596558b090872b',
gameId: '66311a210039f0532044',
userResults:
'{"66281d5ec5614f76bc91":{"team":"66218f22b40deef340f8","correct":false},"6628077faeeedd272637":{"team":"6621b30ea57bd075e9d3","correct":false}, "66174f2362ec891167be":{"team": "6621b30ea57bd075e9d3", "correct":true}}',
});
expect(result).toEqual(resp);
});
});
describe('Get All Weekly Picks Mock Function', () => {
it('should mock getAllWeeklyPicks function', async () => {
const weeklyPicks = {
'66281d5ec5614f76bc91': {
team: '66218f22b40deef340f8',
correct: false,
},
'6628077faeeedd272637': {
team: '6621b30ea57bd075e9d3',
correct: false,
},
'66174f2362ec891167be': { team: '6621b30ea57bd075e9d3', correct: true },
};
const response = { data: weeklyPicks };
apiFunctions.getAllWeeklyPicks.mockResolvedValue(response);
const result = await apiFunctions.getAllWeeklyPicks();
expect(result).toEqual(response);
});
});
describe('getCurrentUserEntries()', () => {
it('should get all user entries and check if eliminated is equal to true', async () => {
const userEntries = [
{
eliminated: true,
league: {},
name: 'name',
selectedTeams: [],
user: '000',
$id: '000',
},
];
apiFunctions.getCurrentUserEntries.mockResolvedValue(userEntries);
const result = await apiFunctions.getCurrentUserEntries();
for (const entry of result) {
expect(entry.eliminated).toEqual(true);
}
});
it('should get all user entries and check if eliminated is equal to false', async () => {
const userEntries = [
{
eliminated: false,
league: {},
name: 'name',
selectedTeams: [],
user: '000',
$id: '000',
},
];
apiFunctions.getCurrentUserEntries.mockResolvedValue(userEntries);
const result = await apiFunctions.getCurrentUserEntries();
for (const entry of result) {
expect(entry.eliminated).toEqual(false);
}
});
it('should get all user entries and check if eliminated is equal to null', async () => {
const userEntries = [
{
eliminated: null,
league: {},
name: 'name',
selectedTeams: [],
user: '000',
$id: '000',
},
];
apiFunctions.getCurrentUserEntries.mockResolvedValue(userEntries);
const result = await apiFunctions.getCurrentUserEntries();
for (const entry of result) {
expect(entry.eliminated).toEqual(null);
}
});
});
xdescribe('get all leagues', () => {
it('should return all leagues upon successful call', async () => {
const mockAllLeagues = [
{
leagueId: '1',
leagueName: 'League One',
logo: '',
participants: ['user1', 'user2'],
survivors: ['user1'],
},
{
leagueId: '2',
leagueName: 'League Two',
logo: '',
participants: ['user3', 'user4'],
survivors: ['user4'],
},
];
apiFunctions.getAllLeagues.mockResolvedValue(mockAllLeagues);
const result = await apiFunctions.getAllLeagues();
expect(result).toEqual([
{
leagueId: '1',
leagueName: 'League One',
logo: '',
participants: ['user1', 'user2'],
survivors: ['user1'],
},
{
leagueId: '2',
leagueName: 'League Two',
logo: '',
participants: ['user3', 'user4'],
survivors: ['user4'],
},
]);
});
it('should return error upon unsuccessful call', async () => {
apiFunctions.getAllLeagues.mockRejectedValue(
new Error('Error getting all leagues'),
);
await expect(apiFunctions.getAllLeagues()).rejects.toThrow(
'Error getting all leagues',
);
});
});
describe('get users id', () => {
it('should return user document ID', async () => {
const userId = '123';
const response = '456';
apiFunctions.getUserDocumentId.mockResolvedValue(response);
const result = await apiFunctions.getUserDocumentId(userId);
expect(result).toEqual(response);
});
it('should return error upon unsuccessful call', async () => {
apiFunctions.getUserDocumentId.mockRejectedValue(
new Error('Error getting user document ID'),
);
await expect(apiFunctions.getUserDocumentId('123')).rejects.toThrow(
'Error getting user document ID',
);
});
});
describe('add user to league', () => {
const response = {
userDocumentId: 'user123',
selectedLeague: 'league123',
selectedLeagues: ['league123'],
participants: ['user123', 'user456'],
survivors: ['user123'],
};
it('should add user to league', async () => {
apiFunctions.addUserToLeague.mockResolvedValue(response);
const result = await apiFunctions.addUserToLeague({ response });
expect(result).toEqual(response);
});
it('should return error upon unsuccessful call', async () => {
apiFunctions.addUserToLeague.mockRejectedValue(
new Error('Error adding user to league'),
);
await expect(apiFunctions.addUserToLeague({ response })).rejects.toThrow(
'Error adding user to league',
);
});
});
describe('update entry name', () => {
const mockEntryId = 'entry123';
const mockEntryName = 'New Entry Name';
const mockUpdatedEntry = {
$id: mockEntryId,
name: mockEntryName,
user: 'user123',
league: 'league123',
selectedTeams: [],
eliminated: false,
};
it('should successfully updateEntryName', async () => {
apiFunctions.updateEntryName.mockResolvedValue(mockUpdatedEntry);
const result = await apiFunctions.updateEntryName({
entryId: mockEntryId,
entryName: mockEntryName,
});
expect(result).toEqual(mockUpdatedEntry);
});
});
});