-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.txt
741 lines (618 loc) · 24.1 KB
/
test.txt
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
import supertest from "supertest";
import { app, server, connectToDatabase } from "./index.test";
import { User } from "../Models/UserModel";
import bcrypt from "bcryptjs";
const request = supertest(app);
beforeAll(async () => {
await connectToDatabase();
});
// Delete all data from the database
afterAll(async () => {
await User.deleteMany({});
server.close();
});
describe("User Signup", () => {
// Test for createUser function
it("creates a new user with valid data", async () => {
// Test data
const userData = {
fullName: "John Doe",
email: "[email protected]",
gender: "male",
password: "password123",
confirmPassword: "password123",
userRole: "user",
};
// Make a request to create user
const response = await request.post("/api/user/signup").send(userData);
// Assertions
expect(response.status).toBe(201);
expect(response.body).toHaveProperty("token");
expect(response.body).toHaveProperty("user");
expect(response.body.message).toBe("User successfully added");
});
// Test for createUser function with invalid data
it("returns 400 with error message for invalid user data", async () => {
// Invalid test data
const invalidUserData = {
fullName: "John Doe",
email: "invalidemail",
gender: "male",
password: "pass",
confirmPassword: "pass",
};
// Make a request to create user with invalid data
const response = await request
.post("/api/user/signup")
.send(invalidUserData);
// Assertions
expect(response.status).toBe(400);
expect(response.text).toContain("must be a valid email");
});
// Test for createUser function with existing user
it("returns 409 with error message for existing user", async () => {
// Existing user test data
const existingUserData = {
fullName: "Existing User",
email: "[email protected]",
gender: "female",
password: "password123",
confirmPassword: "password123",
};
// Make a request to create existing user
const response = await request
.post("/api/user/signup")
.send(existingUserData);
// Assertions
expect(response.status).toBe(409);
expect(response.body.message).toBe("This user already exists");
});
// Test for getAllUsers function
it("gets all users", async () => {
// Make a request to get all users
const response = await request.get("/api/user/all");
// Assertions
expect(response.status).toBe(200);
expect(response.body.data).toBeInstanceOf(Array);
});
// Test for getUserById function
it("gets single user by ID", async () => {
// Assuming there is a user created in the database already
const existingUser = await User.findOne({});
if (!existingUser) {
throw new Error("No user found in the database");
}
// Make a request to get user by ID
const response = await request.get(`/api/user/${existingUser._id}`);
// Assertions
expect(response.status).toBe(200);
expect(response.body.data).toHaveProperty("fullName", existingUser.fullName);
expect(response.body.data).toHaveProperty("email", existingUser.email);
expect(response.body.data).toHaveProperty("gender", existingUser.gender);
expect(response.body.data).toHaveProperty("userRole", existingUser.userRole);
});
// Test for updateUser function
it("updates user data", async () => {
// Assuming there is a user created in the database already
const existingUser = await User.findOne({});
if (!existingUser) {
throw new Error("No user found in the database");
}
// Updated data
const updatedData = {
fullName: "Updated Name",
email: "[email protected]",
gender: "other",
password: "newpassword123",
confirmPassword: "newpassword123",
userRole: "admin",
};
// Make a request to update user
const response = await request
.put(`/api/user/${existingUser._id}`)
.send(updatedData);
// Assertions
expect(response.status).toBe(200);
expect(response.body.data).toHaveProperty("fullName", updatedData.fullName);
expect(response.body.data).toHaveProperty("email", updatedData.email);
expect(response.body.data).toHaveProperty("gender", updatedData.gender);
expect(response.body.data).toHaveProperty("userRole", updatedData.userRole);
});
// Test for deleteUser function
it("deletes user", async () => {
// Assuming there is a user created in the database already
const existingUser = await User.findOne({});
if (!existingUser) {
throw new Error("No user found in the database");
}
// Make a request to delete user
const response = await request.delete(`/api/user/${existingUser._id}`);
// Assertions
expect(response.status).toBe(204);
// Verify if the user was actually deleted from the database
const deletedUser = await User.findById(existingUser._id);
expect(deletedUser).toBeNull();
});
// Test for loginUser function
it("should log in a user", async () => {
// Create a user first
const userData = {
fullName: "John Doe",
email: "[email protected]",
gender: "male",
password: "password123",
confirmPassword: "password123",
userRole: "user",
};
await request.post("/api/user/signup").send(userData);
// Make a request to login
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "password123"
});
// Assertions
expect(res.status).toEqual(200);
expect(res.body).toHaveProperty("message", "Login successful");
expect(res.body).toHaveProperty("token");
});
// Test for invalid credentials
it("should return 401 for Invalid credentials", async () => {
// Make a request with invalid password
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "invalid"
});
// Assertions
expect(res.status).toEqual(401);
expect(res.body).toHaveProperty("message", "Invalid credentials");
});
// Test for email not found
it("should return 404 when an email not found", async () => {
// Make a request with non-existing email
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "password"
});
// Assertions
expect(res.status).toEqual(404);
expect(res.body).toHaveProperty("message", "User not found");
});
// Test for password does not match
it("should return 404 when a password does not match", async () => {
// Make a request with wrong password
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "wrongpassword"
});
// Assertions
expect(res.status).toEqual(401);
expect(res.body).toHaveProperty("message", "Invalid credentials");
});
});
import supertest from "supertest";
import { app, server, connectToDatabase } from "./index.test";
import { User } from "../Models/UserModel";
import bcrypt from "bcryptjs";
import { Blog } from "../Models/BlogModel";
const request = supertest(app);
import { Authorization } from "../Middlewares/Authorization";
import jwt from "jsonwebtoken";
import path from "path";
import fs from 'fs';
beforeAll(async () => {
await connectToDatabase();
});
// Delete all data from the database
afterAll(async () => {
await User.deleteMany({});
await Blog.deleteMany({});
server.close();
});
describe("User Signup", () => {
it("creates a new user with valid data", async () => {
const userData = {
fullName: "John Doe",
email: "[email protected]",
gender: "male",
password: "password123",
confirmPassword: "password123",
userRole: "user",
};
const response = await request.post("/api/user/signup").send(userData);
expect(response.status).toBe(201);
expect(response.body).toHaveProperty("token");
expect(response.body).toHaveProperty("user");
expect(response.body.message).toBe("User successfully added");
// Verify if the user was actually saved in the database
const savedUser = await User.findOne({ email: userData.email });
expect(savedUser).toBeDefined();
expect(savedUser!.fullName).toBe(userData.fullName);
expect(savedUser!.email).toBe(userData.email);
expect(savedUser!.gender).toBe(userData.gender);
expect(savedUser!.userRole).toBe(userData.userRole);
// Verify password encryption
const isPasswordValid = await bcrypt.compare(
userData.password,
savedUser!.password
);
expect(isPasswordValid).toBe(true);
});
it("returns 400 with error message for invalid user data", async () => {
const invalidUserData = {
fullName: "John Doe",
email: "invalidemail",
gender: "male",
password: "pass",
confirmPassword: "pass",
};
const response = await request
.post("/api/user/signup")
.send(invalidUserData);
expect(response.status).toBe(400);
expect(response.text).toContain("must be a valid email");
});
it("returns 409 with error message for existing user", async () => {
const existingUserData = {
fullName: "Existing User",
email: "[email protected]",
gender: "female",
password: "password123",
confirmPassword: "password123",
};
const response = await request
.post("/api/user/signup")
.send(existingUserData);
expect(response.status).toBe(409);
expect(response.body.message).toBe("This user already exists");
});
// Test for getting all users
it("gets all users", async () => {
const response = await request.get("/api/user/all");
expect(response.status).toBe(200);
expect(response.body.data).toBeInstanceOf(Array);
});
// Test for getting single user by ID
it("gets single user by ID", async () => {
// Assuming there is a user created in the database already
const existingUser = await User.findOne({});
if (!existingUser) {
throw new Error("No user found in the database");
}
const response = await request.get(`/api/user/${existingUser._id}`);
expect(response.status).toBe(200);
expect(response.body.data).toHaveProperty("fullName", existingUser.fullName);
expect(response.body.data).toHaveProperty("email", existingUser.email);
expect(response.body.data).toHaveProperty("gender", existingUser.gender);
expect(response.body.data).toHaveProperty("userRole", existingUser.userRole);
});
// Test for getting single user by ID when user is not found
it("returns 404 when user is not found", async () => {
// Generate a random non-existing user ID
const nonExistingUserId = "609df8e15715ab2374e0e29f";
// Make a request to get user by non-existing ID
const response = await request.get(`/api/user/${nonExistingUserId}`);
// Assertions
expect(response.status).toBe(404);
expect(response.body).toHaveProperty("message", "User not found");
});
// Test for updating user
it("updates user data", async () => {
// Assuming there is a user created in the database already
const existingUser = await User.findOne({});
if (!existingUser) {
throw new Error("No user found in the database");
}
const updatedData = {
fullName: "Updated Name",
email: "[email protected]",
gender: "other",
password: "newpassword123",
confirmPassword: "newpassword123",
userRole: "admin",
};
const response = await request
.put(`/api/user/${existingUser._id}`)
.send(updatedData);
expect(response.status).toBe(200);
expect(response.body.data).toHaveProperty("fullName", updatedData.fullName);
expect(response.body.data).toHaveProperty("email", updatedData.email);
expect(response.body.data).toHaveProperty("gender", updatedData.gender);
expect(response.body.data).toHaveProperty("userRole", updatedData.userRole);
// Verify that no validation errors occur
expect(response.body).not.toHaveProperty("error");
// Verify that the user is found and updated successfully
const updatedUser = await User.findById(existingUser._id);
expect(updatedUser).toBeTruthy();
expect(updatedUser!.fullName).toBe(updatedData.fullName);
expect(updatedUser!.email).toBe(updatedData.email);
expect(updatedUser!.gender).toBe(updatedData.gender);
expect(updatedUser!.userRole).toBe(updatedData.userRole);
});
// Test for updating user with invalid data
it("returns 400 with error message for invalid user data during update", async () => {
// Assuming there is a user created in the database already
const existingUser = await User.findOne({});
if (!existingUser) {
throw new Error("No user found in the database");
}
const invalidData = {
fullName: "", // invalid data
email: "[email protected]",
gender: "other",
password: "newpassword123",
confirmPassword: "newpassword123",
userRole: "admin",
};
const response = await request
.put(`/api/user/${existingUser._id}`)
.send(invalidData);
expect(response.status).toBe(400);
expect(response.text).toContain("\"fullName\" is not allowed to be empty");
// Verify that no user is updated with invalid data
const userAfterUpdate = await User.findById(existingUser._id);
expect(userAfterUpdate).toBeTruthy();
expect(userAfterUpdate!.fullName).not.toBe("");
});
// Test for updating user that doesn't exist
it("returns 404 when updating non-existing user", async () => {
// Generate a random non-existing user ID
const nonExistingUserId = "609df8e15715ab2374e0e29f";
const updatedData = {
fullName: "Updated Name",
email: "[email protected]",
gender: "other",
password: "newpassword123",
confirmPassword: "newpassword123",
userRole: "admin",
};
const response = await request
.put(`/api/user/${nonExistingUserId}`)
.send(updatedData);
expect(response.status).toBe(404);
expect(response.body).toHaveProperty("message", "User not found");
});
// it("returns 404 when user is not found", async () => {
// // Generate a random non-existing user ID
// const nonExistingUserId = "609df8e15715ab2374e0e29f";
// // Make a request to get user by non-existing ID
// const response = await request.get(`/api/user/${nonExistingUserId}`);
// // Assertions
// expect(response.status).toBe(404);
// expect(response.body).toHaveProperty("message", "User not found");
// });
it("deletes user", async () => {
// Assuming there is a user created in the database already
const existingUser = await User.findOne({});
if (!existingUser) {
throw new Error("No user found in the database");
}
const response = await request.delete(`/api/user/${existingUser._id}`);
expect(response.status).toBe(204);
// Verify if the user was actually deleted from the database
const deletedUser = await User.findById(existingUser._id);
expect(deletedUser).toBeNull();
});
// Test for attempting to delete a user that doesn't exist
it("returns 404 when attempting to delete non-existing user", async () => {
// Generate a random non-existing user ID
const nonExistingUserId = "609df8e15715ab2374e0e29f";
const response = await request.delete(`/api/user/${nonExistingUserId}`);
expect(response.status).toBe(404);
expect(response.body).toHaveProperty("message", "User not found");
});
let token:string;
// const existingUser = await User.findOne({ email: "[email protected]" });
it("should log in a user", async () => {
// Create a user first
const userData = {
fullName: "John Doe",
email: "[email protected]",
gender: "male",
password: "password123",
confirmPassword: "password123",
userRole: "user",
};
await request.post("/api/user/signup").send(userData);
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "password123"
});
console.log("Login Response:", res.body);
expect(res.status).toEqual(200);
expect(res.body).toHaveProperty("message", "Login successful");
expect(res.body).toHaveProperty("token");
});
it("should return 401 for Invalid credentials", async () => {
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "invalid"
});
console.log("Invalid Credentials Response:", res.body);
expect(res.status).toEqual(401);
expect(res.body).toHaveProperty("message", "Invalid credentials");
});
it("should return 404 when an email not found", async () => {
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "password"
});
console.log("Email Not Found Response:", res.body);
expect(res.status).toEqual(404);
expect(res.body).toHaveProperty("message", "User not found");
});
it("should return 404 when a password does not match", async () => {
const res = await request.post("/api/user/login").send({
email: "[email protected]",
password: "wrongpassword"
});
console.log("Password Does Not Match Response:", res.body);
expect(res.status).toEqual(401);
expect(res.body).toHaveProperty("message", "Invalid credentials");
});
})
describe("Blog API Testing", () => {
let adminToken:string;
let existingBlog: any;
beforeAll(async () => {
// Create an admin user
const adminUser = new User({
email: "[email protected]",
fullName: "Admin User",
gender:"male",
password: "admin123",
userRole: "admin",
});
await adminUser.save();
// Generate a JWT token for the admin user
adminToken = jwt.sign({ id: adminUser._id }, process.env.JWT_SECRET || "", {
expiresIn: "20h",
});
// Create an example blog
existingBlog = new Blog({
blogTitle: "Example Blog",
blogDescription: "This is an example blog",
blogDate: new Date().toISOString(),
blogImage: "example.png",
});
await existingBlog.save();
});
it("should create a new blog with valid data when user is an admin", async () => {
const blogData = {
blogTitle: "Test Blog",
blogDescription: "This is a test blog",
blogDate: new Date().toISOString(),
blogImage: "test.png",
};
// Ensure the file exists at the specified path
const filePath = path.join(__dirname, "test.png");
if (!fs.existsSync(filePath)) {
throw new Error("Test file not found");
}
const response = await request
.post("/api/blog/post-blog")
.set("Authorization", `${adminToken}`)
.field("blogTitle", blogData.blogTitle)
.field("blogDescription", blogData.blogDescription)
.field("blogDate", blogData.blogDate)
.attach("blogImage", filePath);
expect(response.status).toBe(201);
expect(response.body).toHaveProperty("message", "Blog successfully created");
expect(response.body).toHaveProperty("data");
expect(response.body.data).toHaveProperty("blogTitle", blogData.blogTitle);
expect(response.body.data).toHaveProperty("blogDescription", blogData.blogDescription);
expect(response.body.data).toHaveProperty("blogDate", new Date(blogData.blogDate).toISOString());
expect(response.body.data).toHaveProperty("blogImage", expect.stringContaining("https://res.cloudinary.com"));
// Find an existing blog in the database
});
// Test for updating a blog
// it("should update a blog with valid data", async () => {
// const blogData = {
// blogTitle: "Updated Blog",
// blogDescription: "This is an updated blog",
// blogDate: new Date().toISOString(),
// blogImage: "updatedTest.png",
// };
// const filePath = path.join(__dirname, "updatedTest.jpg");
// if (!fs.existsSync(filePath)) {
// throw new Error("Test file not found");
// }
// const response = await request
// .put(`/api/blog/update-blog/${existingBlog._id}`)
// .set("Authorization", `${adminToken}`)
// .field("blogTitle", blogData.blogTitle)
// .field("blogDescription", blogData.blogDescription)
// .field("blogDate", blogData.blogDate)
// .attach("blogImage", filePath);
// expect(response.status).toBe(200);
// expect(response.body).toHaveProperty("message", "Blog successfully updated");
// expect(response.body).toHaveProperty("data");
// expect(response.body.data).toHaveProperty("blogTitle", blogData.blogTitle);
// expect(response.body.data).toHaveProperty("blogDescription", blogData.blogDescription);
// expect(response.body.data).toHaveProperty("blogDate", new Date(blogData.blogDate).toISOString());
// expect(response.body.data).toHaveProperty("blogImage", expect.stringContaining("https://res.cloudinary.com"));
// }, 30000);
// Increase timeout to 30 seconds
// Test for getting all blogs
it("should retrieve all blogs and return success", async () => {
const response = await request.get("/api/blog/getall-blog");
expect(response.status).toBe(200);
expect(response.body).toHaveProperty("data");
expect(response.body.data).toBeInstanceOf(Array);
});
// Test for getting a single blog by ID
it("should retrieve a single blog and return success", async () => {
const response = await request.get(`/api/blog/getone-blog/${existingBlog._id}`);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty("data");
expect(response.body.data).toHaveProperty("blogTitle");
expect(response.body.data).toHaveProperty("blogDescription");
expect(response.body.data).toHaveProperty("blogDate");
expect(response.body.data).toHaveProperty("blogImage");
});
it("should delete a blog and return success", async () => {
const response = await request.delete(`/api/blog/delete-blog/${existingBlog._id}`)
.set("Authorization", `${adminToken}`);
expect(response.status).toBe(204);
}, 30000);
it("should return 400 if blog data is invalid", async () => {
const invalidBlogData = {
blogTitle: "", // Invalid data
blogDescription: "This is an invalid blog",
blogDate: new Date().toISOString(),
blogImage: "invalid.png",
};
const filePath = path.join(__dirname, "invalid.png");
if (!fs.existsSync(filePath)) {
throw new Error("Invalid file not found");
}
const response = await request
.post("/api/blog/post-blog")
.set("Authorization", `${adminToken}`)
.field("blogTitle", invalidBlogData.blogTitle)
.field("blogDescription", invalidBlogData.blogDescription)
.field("blogDate", invalidBlogData.blogDate)
.attach("blogImage", filePath);
expect(response.status).toBe(400);
expect(response.text).toContain("\"blogTitle\" is not allowed to be empty");
});
it("should return 400 if no file is uploaded", async () => {
const blogData = {
blogTitle: "Test Blog",
blogDescription: "This is a test blog",
blogDate: new Date().toISOString(),
blogImage: "test.png",
};
const response = await request
.post("/api/blog/post-blog")
.set("Authorization", `${adminToken}`)
.field("blogTitle", blogData.blogTitle)
.field("blogDescription", blogData.blogDescription)
.field("blogDate", blogData.blogDate);
expect(response.status).toBe(400);
expect(response.body).toHaveProperty("message", "Please upload a file");
});
// Error handling test
it("should return 500 for internal server error", async () => {
jest.spyOn(console, "error").mockImplementation(() => {});
jest.spyOn(Blog.prototype, "save").mockRejectedValue(new Error("Internal Server Error"));
const blogData = {
blogTitle: "Test Blog",
blogDescription: "This is a test blog",
blogDate: new Date().toISOString(),
blogImage: "test.png",
};
const filePath = path.join(__dirname, "test.png");
if (!fs.existsSync(filePath)) {
throw new Error("Test file not found");
}
const response = await request
.post("/api/blog/post-blog")
.set("Authorization", `${adminToken}`)
.field("blogTitle", blogData.blogTitle)
.field("blogDescription", blogData.blogDescription)
.field("blogDate", blogData.blogDate)
.attach("blogImage", filePath);
expect(response.status).toBe(500);
expect(response.body).toHaveProperty("error", "Internal Server Error");
});
});