-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathuser.test.js
421 lines (385 loc) · 11 KB
/
user.test.js
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
const app = require('../app').app
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const request = require('supertest')
const User = require('../app/models/User')
const redis = require('../config/redis').redisClient
const HttpStatus = require('http-status-codes')
let token = ''
let passwordToken = ''
let inviteLink = ''
let unAuthUserId = ''
const demoUser = {
name: {
firstName: 'test',
lastName: 'test'
},
email: 'test3@mailinator.com',
phone: '1234567890',
password: 'abc12345',
info: {
about: {
shortDescription: 'this is short description',
longDescription: 'this is a very long description',
website: 'https://www.google.com',
designation: 'software engg',
skills: [
'c++',
'java'
],
education: [{
school: {
schoolName: 'firstSchoolName',
year: '2017-2021'
}
},
{
school: {
schoolName: 'secondSchoolName',
year: '2007-2014'
}
}
],
location: 'location'
}
}
}
const testUserId = new mongoose.Types.ObjectId()
const testFollowUserId = new mongoose.Types.ObjectId()
console.log('testUserID ', testUserId)
console.log('testFollowUserID ', testFollowUserId)
const testUser = {
_id: testUserId,
...demoUser,
email: 'test@mailinator.com',
phone: '1234567891',
isAdmin: true,
followers: [],
followings: [],
blocked: [],
tokens: [{
token: jwt.sign({
_id: testUserId
}, process.env.JWT_SECRET)
}]
}
const testFollowUser = {
_id: testFollowUserId,
...demoUser,
...demoUser.name.firstName = 'follow_user',
...demoUser.name.lastName = 'test',
email: 'test43@mailinator.com',
phone: '1274567391',
isAdmin: false,
followers: [],
followings: [],
blocked: [],
tokens: [{
token: jwt.sign({
_id: testFollowUserId
}, process.env.JWT_SECRET)
}]
}
let server
/**
* This will pe performed once at the beginning of the test
*/
beforeAll(async (done) => {
await User.deleteMany()
await redis.flushall()
server = app.listen(4000, () => {
global.agent = request.agent(server)
done()
})
})
/**
* This deletes all the existing user in database,
* and creates a new user in database with the provided details.
*/
beforeEach(async () => {
await User.deleteMany()
await new User(testUser).save()
await new User(testFollowUser).save()
await redis.flushall()
})
/**
* Testing user signup
*/
test('Should signup new user', async () => {
const response = await request(app)
.post('/user')
.send(demoUser)
.expect(HttpStatus.CREATED)
// Assert that db was changed
unAuthUserId = response.body.user._id
const user = await User.findById(response.body.user._id)
expect(user).not.toBeNull()
// Assertions about the response
// expect(response.body.user.name.firstName).toBe('Rupesh')
// OR
expect(response.body).toMatchObject({
user: {
name: {
firstName: demoUser.name.firstName,
lastName: demoUser.name.lastName
},
email: demoUser.email,
phone: demoUser.phone,
info: {
about: {
skills: demoUser.info.about.skills,
shortDescription: demoUser.info.about.shortDescription,
longDescription: demoUser.info.about.longDescription,
website: demoUser.info.about.website,
designation: demoUser.info.about.designation,
education: demoUser.info.about.education,
location: demoUser.info.about.location
}
}
},
token: user.tokens[0].token
})
expect(user.password).not.toBe('abc12345') // to check hashing
})
/** Testing user login */
test('Login existing user', async () => {
const response = await request(app)
.post('/auth/login')
.send({
email: testUser.email,
password: testUser.password
})
.expect(HttpStatus.OK)
token = response.body.token
const user = await User.findById(testUserId)
expect(response.body.token).toBe(user.tokens[1].token)
})
/** Testing non existing user login */
test('Should not login non-existing user', async () => {
await request(app).post('/auth/login').send({
email: 'random@random.com',
password: 'random@123'
}).expect(HttpStatus.BAD_REQUEST)
})
/** Fetch authenticated user profile */
test('Should get profile for user', async () => {
await request(app)
.get(`/user/${testUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send()
.expect(HttpStatus.OK)
})
/** Fail in getting unathenticated user profile */
test('Should not get profile for unauthenticated user', async (done) => {
await request(app)
.get(`/user/${unAuthUserId}`)
.send()
.expect(HttpStatus.UNAUTHORIZED)
done()
})
/** Should update user profile */
test('Should update profile or authenticated user', async () => {
await request(app)
.patch(`/user/${testUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send({
email: 'updated@example.com'
})
.expect(HttpStatus.OK)
})
/** Should fail to make updates that are not allowed to user profile */
test('Should be able to make only allowed updates to authenticated user', async () => {
await request(app)
.patch(`/user/${testUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send({
gender: 'Male'
})
.expect(HttpStatus.BAD_REQUEST)
})
/** Should Fail updating profile of unauthenticate user */
test('Should not update profile or unauthenticated user', async () => {
await request(app)
.patch(`/user/${unAuthUserId}`)
.send({
email: 'updated@example.com'
})
.expect(HttpStatus.UNAUTHORIZED)
})
/** Should update user profile */
test('Should update profile or authenticated user', async () => {
await request(app)
.patch('/user/me')
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send({
email: 'updated@example.com'
})
.expect(HttpStatus.OK)
})
/** Should fail to make updates that are not allowed to user profile */
test('Should be able to make only allowed updates to authenticated user', async () => {
await request(app)
.patch('/user/me')
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send({
gender: 'Male'
})
.expect(HttpStatus.BAD_REQUEST)
})
/** Should Fail updating profile of unauthenticate user */
test('Should not update profile or unauthenticated user', async () => {
await request(app)
.patch('/user/me')
.send({
email: 'updated@example.com'
})
.expect(HttpStatus.UNAUTHORIZED)
})
/** Delete authenticated user profile */
test('Should delete profile of authenticated user', async () => {
await request(app)
.delete('/user/me')
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send()
.expect(HttpStatus.OK)
// Assert that user was deleted
const user = await User.findById(testUserId)
expect(user).toBeNull()
})
/** Fail deleting user profile of unauthenticated user */
test('Should not delete profile of unauthenticated user', async () => {
await request(app)
.delete('/user/me')
.send()
.expect(HttpStatus.UNAUTHORIZED)
})
/** Forgot password request **/
test('Should send the request to change the password ', async () => {
const response = await request(app)
.patch('/user/password_reset/request')
.send({
email: `${testUser.email}`
})
.expect(200)
passwordToken = response.body.token
expect(passwordToken).not.toBeNull()
})
/* Password update */
test('Should update the password ', async () => {
await request(app)
.patch(`/user/password_reset/${passwordToken}`)
.send({
password: 'newPassword',
id: testUserId
})
.expect(200)
})
/* Activate account */
test('Should activate the account ', async (done) => {
await request(app)
.get(`/user/activate/${token}`)
.send({
token: `${token}`
})
.expect(HttpStatus.OK)
done()
})
/* Get invite link */
test('Should generate an invite link and send', async () => {
const response = await request(app)
.get('/user/link/invite?role=user')
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send()
.expect(HttpStatus.OK)
inviteLink = response.body.inviteLink
// check the response
expect(response.body.inviteLink).not.toBeNull()
})
/* Process invite link */
test('Should validate the invite link token ', async () => {
const inviteToken = inviteLink.split('/').slice(-1)[0].trim()
await request(app)
.get(`/user/invite/${inviteToken}`)
.send()
.expect(HttpStatus.MOVED_TEMPORARILY)
})
/* Follow the user */
test('Should follow the user', async (done) => {
await request(app)
.patch(`/user/follow/${testFollowUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.expect(HttpStatus.OK)
// Assert the db change
const user = await User.findById(testFollowUserId)
expect(user.followers[0] === testUserId)
done()
})
/* unFollow the user */
test('Should unFollow the user', async (done) => {
await request(app)
.patch(`/user/unfollow/${testFollowUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.expect(HttpStatus.OK)
// Assert that db change
const user = await User.findById(testFollowUserId)
expect(user.followers === [])
done()
})
/* Block the user */
test('Should block the user', async (done) => {
const response = await request(app)
.patch(`/user/block/${testFollowUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send()
.expect(HttpStatus.OK)
// Assert the db changed
expect(response.body.user.blocked[0]._id === testFollowUserId)
done()
})
/* UnBlock the user */
test('Should UnBlock the user', async (done) => {
const response = await request(app)
.patch(`/user/unblock/${testFollowUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send()
// Assert the db changed
expect(response.body.user.blocked === [])
done()
})
/* Get user activity on the platform */
test('Should fetch all the activities of a user on the platform', async (done) => {
const response = await request(app)
.get(`/activity/user/${testUserId}`)
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send()
.expect(HttpStatus.OK)
// Assert the db changed
expect(response.body).not.toBeNull()
done()
})
/* Logout the user */
test('Should logout the user ', async (done) => {
await request(app)
.post('/user/logout')
.set('Authorization', `Bearer ${testUser.tokens[0].token}`)
.send()
.expect(HttpStatus.OK)
done()
})
/**
* TODO: FIX ERROR
* This is a temporary fix to issue:
* Jest has detected the following 1 open handle potentially keeping Jest from exiting
*/
afterAll(async () => {
// avoid jest open handle error
await new Promise((resolve) => setTimeout(() => resolve(), 500))
// close server
await server.close()
// delete all the users post testing
await User.deleteMany()
// flush redis
await redis.flushall()
// Closing the DB connection allows Jest to exit successfully.
await mongoose.connection.close()
})