From e66ade843553742def993a5edb72cd8a8b029228 Mon Sep 17 00:00:00 2001 From: Devesh Date: Thu, 17 Jun 2021 20:44:35 +0530 Subject: [PATCH 01/13] added internal server error exception using httpexception filter --- src/modules/assignment/assignment.service.ts | 87 ++++++++--- src/modules/course/course.service.ts | 16 +- src/modules/doubt/doubt.service.ts | 31 +++- src/modules/user/user.service.ts | 148 ++++++++++++++++--- 4 files changed, 231 insertions(+), 51 deletions(-) diff --git a/src/modules/assignment/assignment.service.ts b/src/modules/assignment/assignment.service.ts index 84b6f0a..02b0849 100644 --- a/src/modules/assignment/assignment.service.ts +++ b/src/modules/assignment/assignment.service.ts @@ -14,16 +14,37 @@ export class AssignmentService { // fetch all Assignments async getAllAssignment(): Promise { - const Assignments = await this.AssignmentModel.find().exec(); - return Assignments; + try { + const Assignments = await this.AssignmentModel.find().exec(); + return Assignments; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // Get a single Assignment async getAssignment(AssignmentId): Promise { - const Assignment = await this.AssignmentModel.findById(AssignmentId).exec(); - - if (Assignment) { - return Assignment; + try { + const Assignment = await this.AssignmentModel.findById( + AssignmentId, + ).exec(); + if (Assignment) { + return Assignment; + } + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } throw new HttpException( @@ -39,8 +60,18 @@ export class AssignmentService { async addAssignment( CreateAssignmentDTO: CreateAssignmentDTO, ): Promise { - const newAssignment = await new this.AssignmentModel(CreateAssignmentDTO); - return newAssignment.save(); + try { + const newAssignment = await new this.AssignmentModel(CreateAssignmentDTO); + return newAssignment.save(); + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // Edit Assignment details @@ -48,19 +79,39 @@ export class AssignmentService { AssignmentID, updateAssignmentDTO: UpdateAssignmentDTO, ): Promise { - const updatedAssignment = await this.AssignmentModel.findByIdAndUpdate( - AssignmentID, - updateAssignmentDTO, - { new: true }, - ); - return updatedAssignment; + try { + const updatedAssignment = await this.AssignmentModel.findByIdAndUpdate( + AssignmentID, + updateAssignmentDTO, + { new: true }, + ); + return updatedAssignment; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // Delete a Assignment async deleteAssignment(AssignmentID): Promise { - const deletedAssignment = await this.AssignmentModel.findByIdAndRemove( - AssignmentID, - ); - return deletedAssignment; + try { + const deletedAssignment = await this.AssignmentModel.findByIdAndRemove( + AssignmentID, + ); + return deletedAssignment; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } } diff --git a/src/modules/course/course.service.ts b/src/modules/course/course.service.ts index fef7dad..d941bdf 100644 --- a/src/modules/course/course.service.ts +++ b/src/modules/course/course.service.ts @@ -22,7 +22,9 @@ export class CourseService { // fetch all courses async getAllCourses(): Promise { - return await this.CourseModel.find().exec(); + try { + return await this.CourseModel.find().exec(); + } catch (e) {} } // fetch selected course by id @@ -43,8 +45,10 @@ export class CourseService { // add course async addCourse(createCourseDto: CreateCourseDto): Promise { - const newCourse = new this.CourseModel(createCourseDto); - return await newCourse.save(); + try { + const newCourse = new this.CourseModel(createCourseDto); + return await newCourse.save(); + } catch (e) {} } // edit course by Id @@ -66,8 +70,10 @@ export class CourseService { // Delete a Course by Id async deleteCourse(courseId): Promise { - const deletedCourse = await this.CourseModel.findByIdAndRemove(courseId); - return deletedCourse; + try { + const deletedCourse = await this.CourseModel.findByIdAndRemove(courseId); + return deletedCourse; + } catch (e) {} } // Create a Schedule diff --git a/src/modules/doubt/doubt.service.ts b/src/modules/doubt/doubt.service.ts index b910383..0cbbf89 100644 --- a/src/modules/doubt/doubt.service.ts +++ b/src/modules/doubt/doubt.service.ts @@ -1,6 +1,7 @@ import { + HttpException, + HttpStatus, Injectable, - InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; @@ -15,7 +16,17 @@ export class DoubtService { ) {} async getAllDoubts(): Promise { - return await this.DoubtModel.find().exec(); + try { + return await this.DoubtModel.find().exec(); + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } async findDoubtById(id: string): Promise { @@ -26,7 +37,13 @@ export class DoubtService { return doubt; } } catch (e) { - throw new NotFoundException('doubt not found!'); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } throw new NotFoundException('doubt not found!'); @@ -36,7 +53,13 @@ export class DoubtService { try { return await new this.DoubtModel(newDoubt).save(); } catch (e) { - throw new InternalServerErrorException(); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } } diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 6dc778b..7c08bb6 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -1,5 +1,6 @@ import { - BadRequestException, + HttpException, + HttpStatus, Injectable, NotFoundException, } from '@nestjs/common'; @@ -23,8 +24,18 @@ export class UserService { // fetch all Users async getAllUser(): Promise { - const users = await this.userModel.find().exec(); - return users; + try { + const users = await this.userModel.find().exec(); + return users; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // Get a single User @@ -36,15 +47,31 @@ export class UserService { return user; } } catch (e) { - throw new NotFoundException('User Not Found!'); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } throw new NotFoundException('Error'); } // post a single User async addUser(CreateUserDTO: CreateUserDTO): Promise { - const newUser = await new this.userModel(CreateUserDTO); - return newUser.save(); + try { + const newUser = await new this.userModel(CreateUserDTO); + return newUser.save(); + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // Edit User details @@ -60,7 +87,13 @@ export class UserService { { new: true, useFindAndModify: false }, ); } catch (e) { - throw new BadRequestException(e); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } finally { return updatedUser; } @@ -71,8 +104,15 @@ export class UserService { let deletedUser; try { deletedUser = await this.userModel.findByIdAndRemove(userID); - } finally { return deletedUser; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } @@ -81,19 +121,39 @@ export class UserService { userId: Schema.Types.ObjectId, courseId: Schema.Types.ObjectId, ) { - const enrolledCourses = await this.enrolledModel.findOne({ - studentId: userId, - courseId: courseId, - }); - return enrolledCourses; + try { + const enrolledCourses = await this.enrolledModel.findOne({ + studentId: userId, + courseId: courseId, + }); + return enrolledCourses; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // gets all Enrolled courses async getEnrolledCourses(userId: Schema.Types.ObjectId) { - const enrolledCourses = await this.enrolledModel.findOne({ - studentId: userId, - }); - return enrolledCourses; + try { + const enrolledCourses = await this.enrolledModel.findOne({ + studentId: userId, + }); + return enrolledCourses; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // adds Enrolled Course @@ -120,7 +180,13 @@ export class UserService { /*const newF = await this.enrolledModel.find({}).populate('students'); return newF;*/ } catch (e) { - throw new NotFoundException('User or Course does not exist'); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } @@ -128,8 +194,18 @@ export class UserService { async getWishList( userId: Schema.Types.ObjectId, ): Promise { - const userWishList = await this.findUserById(userId); - return userWishList.wishlist; + try { + const userWishList = await this.findUserById(userId); + return userWishList.wishlist; + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // adds wishlisted course @@ -143,7 +219,13 @@ export class UserService { return UserWishList; } } catch (e) { - throw new NotFoundException('User or Course does not exist'); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } throw new NotFoundException('course could not be wishlisted'); @@ -167,7 +249,13 @@ export class UserService { throw new NotFoundException('not found'); } } catch (e) { - throw new NotFoundException('Failed to deleted'); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } @@ -188,7 +276,13 @@ export class UserService { ); return updatedCourse; } catch (e) { - throw new BadRequestException(e); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } @@ -209,7 +303,13 @@ export class UserService { throw new NotFoundException('not found'); } } catch (e) { - throw new NotFoundException('Failed to deleted'); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } } From 1a8c0262a757cf9c69f8f6b5928119fac3b30754 Mon Sep 17 00:00:00 2001 From: Devesh Date: Thu, 17 Jun 2021 21:04:31 +0530 Subject: [PATCH 02/13] added httpserver exception in rest of the routes to check for 500 errors --- src/modules/assignment/assignment.service.ts | 23 +++++- src/modules/course/course.service.ts | 81 +++++++++++++++++--- 2 files changed, 90 insertions(+), 14 deletions(-) diff --git a/src/modules/assignment/assignment.service.ts b/src/modules/assignment/assignment.service.ts index 02b0849..c1327aa 100644 --- a/src/modules/assignment/assignment.service.ts +++ b/src/modules/assignment/assignment.service.ts @@ -1,4 +1,9 @@ -import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; +import { + HttpException, + HttpStatus, + Injectable, + NotFoundException, +} from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { AssignmentDocument as Assignment } from './schema/assignment.schema'; @@ -62,7 +67,11 @@ export class AssignmentService { ): Promise { try { const newAssignment = await new this.AssignmentModel(CreateAssignmentDTO); - return newAssignment.save(); + await newAssignment.save(); + if (newAssignment) { + return newAssignment; + } + throw new NotFoundException('doubt not found!'); } catch (e) { throw new HttpException( { @@ -85,7 +94,9 @@ export class AssignmentService { updateAssignmentDTO, { new: true }, ); - return updatedAssignment; + if (updatedAssignment) { + return updatedAssignment; + } } catch (e) { throw new HttpException( { @@ -95,6 +106,7 @@ export class AssignmentService { HttpStatus.INTERNAL_SERVER_ERROR, ); } + throw new NotFoundException('doubt not found!'); } // Delete a Assignment @@ -103,7 +115,10 @@ export class AssignmentService { const deletedAssignment = await this.AssignmentModel.findByIdAndRemove( AssignmentID, ); - return deletedAssignment; + if (deletedAssignment) { + return deletedAssignment; + } + throw new NotFoundException('doubt not found!'); } catch (e) { throw new HttpException( { diff --git a/src/modules/course/course.service.ts b/src/modules/course/course.service.ts index d941bdf..106d1eb 100644 --- a/src/modules/course/course.service.ts +++ b/src/modules/course/course.service.ts @@ -1,6 +1,7 @@ import { + HttpException, + HttpStatus, Injectable, - InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; @@ -24,7 +25,15 @@ export class CourseService { async getAllCourses(): Promise { try { return await this.CourseModel.find().exec(); - } catch (e) {} + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // fetch selected course by id @@ -38,8 +47,14 @@ export class CourseService { } else { throw new NotFoundException('course not found'); } - } catch { - throw new NotFoundException('course not found'); + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } @@ -47,8 +62,20 @@ export class CourseService { async addCourse(createCourseDto: CreateCourseDto): Promise { try { const newCourse = new this.CourseModel(createCourseDto); - return await newCourse.save(); - } catch (e) {} + await newCourse.save(); + if (newCourse) { + return newCourse; + } + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } + throw new NotFoundException('doubt not found!'); } // edit course by Id @@ -63,6 +90,14 @@ export class CourseService { updateCourseDTO, { new: true }, ); + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } finally { return updatedCourse; } @@ -73,7 +108,15 @@ export class CourseService { try { const deletedCourse = await this.CourseModel.findByIdAndRemove(courseId); return deletedCourse; - } catch (e) {} + } catch (e) { + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); + } } // Create a Schedule @@ -95,7 +138,13 @@ export class CourseService { ); } } catch (e) { - throw new InternalServerErrorException(e); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } @@ -121,7 +170,13 @@ export class CourseService { ); } } catch (e) { - throw new InternalServerErrorException(e); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } @@ -144,7 +199,13 @@ export class CourseService { ); } } catch (e) { - throw new InternalServerErrorException(e); + throw new HttpException( + { + status: HttpStatus.INTERNAL_SERVER_ERROR, + error: `${e}`, + }, + HttpStatus.INTERNAL_SERVER_ERROR, + ); } } } From c0b1652ec2c98cebcf04db8887bbae3c3a987951 Mon Sep 17 00:00:00 2001 From: Devesh Date: Sat, 19 Jun 2021 11:20:06 +0530 Subject: [PATCH 03/13] fix wishlist course add and delete method --- src/modules/user/dto/create-wishlist.dto.ts | 4 ++++ src/modules/user/user.controller.ts | 5 +++-- src/modules/user/user.service.ts | 15 ++++++++++----- 3 files changed, 17 insertions(+), 7 deletions(-) create mode 100644 src/modules/user/dto/create-wishlist.dto.ts diff --git a/src/modules/user/dto/create-wishlist.dto.ts b/src/modules/user/dto/create-wishlist.dto.ts new file mode 100644 index 0000000..c5ddff1 --- /dev/null +++ b/src/modules/user/dto/create-wishlist.dto.ts @@ -0,0 +1,4 @@ +import { Schema } from 'mongoose'; +export class CreateWishlistDTO { + cId?: Schema.Types.ObjectId; +} diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index 337b6ee..ec035d0 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -22,6 +22,7 @@ import { UpdateEnrolledDTO } from './dto/update-enrolled.dto'; import { Schema } from 'mongoose'; import responsedoc from './docUtils/apidoc'; import { userId } from './docUtils/user.paramdocs'; +import { CreateWishlistDTO } from './dto/create-wishlist.dto'; @ApiTags('User') @Controller('user') @@ -103,9 +104,9 @@ export class UserController { @ApiCreatedResponse(responsedoc.addWishlist) async addWishlist( @Param('userId') userId: Schema.Types.ObjectId, - @Body() cId: Schema.Types.ObjectId, + @Body() createWishlistDto: CreateWishlistDTO, ) { - return await this.userService.addWishlist(userId, cId); + return await this.userService.addWishlist(userId, createWishlistDto); } // Fetch a particular User using ID diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 7c08bb6..291b600 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -13,6 +13,7 @@ import { CourseDocument as Course } from '../course/schema/course.schema'; import { EnrolledCourseDocument as Enrolled } from '../course/schema/enrolledCourse.schema'; import { CreateEnrolledDTO } from './dto/create-enrolled.dto'; import { UpdateEnrolledDTO } from './dto/update-enrolled.dto'; +import { CreateWishlistDTO } from './dto/create-wishlist.dto'; @Injectable() export class UserService { @@ -209,10 +210,13 @@ export class UserService { } // adds wishlisted course - async addWishlist(userId: Schema.Types.ObjectId, cId: Schema.Types.ObjectId) { + async addWishlist( + userId: Schema.Types.ObjectId, + createWishlistDto: CreateWishlistDTO, + ) { try { const UserWishList = await this.findUserById(userId); - + const { cId } = createWishlistDto; if (UserWishList) { UserWishList.wishlist.push(cId); await UserWishList.save(); @@ -236,13 +240,14 @@ export class UserService { userID: Schema.Types.ObjectId, wishId: Schema.Types.ObjectId, ): Promise { - let deletedFrom; try { - deletedFrom = await this.userModel.findById(userID); + const deletedFrom = await this.userModel.findById(userID); + console.log(wishId); if (deletedFrom) { deletedFrom.wishlist = deletedFrom.wishlist.filter( - (wishlist) => wishlist.id != wishId, + (wishlist) => wishlist != wishId, ); + console.log(deletedFrom); await deletedFrom.save(); return deletedFrom; } else { From 2d2e5a71618a127275ed53094a82dc87064c6b11 Mon Sep 17 00:00:00 2001 From: Devesh Date: Sat, 19 Jun 2021 11:35:51 +0530 Subject: [PATCH 04/13] remove console.logs --- src/modules/user/user.service.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 291b600..90a34a1 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -242,12 +242,10 @@ export class UserService { ): Promise { try { const deletedFrom = await this.userModel.findById(userID); - console.log(wishId); if (deletedFrom) { deletedFrom.wishlist = deletedFrom.wishlist.filter( (wishlist) => wishlist != wishId, ); - console.log(deletedFrom); await deletedFrom.save(); return deletedFrom; } else { From 8b43a7a5c0380f1baff4b8e6e6980cb14de2c3ce Mon Sep 17 00:00:00 2001 From: Devesh Date: Sat, 19 Jun 2021 12:21:18 +0530 Subject: [PATCH 05/13] the apidoc fiel updated with wishlist delete --- src/modules/user/docUtils/apidoc.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/modules/user/docUtils/apidoc.ts b/src/modules/user/docUtils/apidoc.ts index bb6cedd..7787c87 100644 --- a/src/modules/user/docUtils/apidoc.ts +++ b/src/modules/user/docUtils/apidoc.ts @@ -44,6 +44,11 @@ const addWishlist: ApiResponseOptions = { type: UserResponseBody, }; +const deleteWishList: ApiResponseOptions = { + description: 'Delete Wishlist Course', + type: UserResponseBody, +}; + const responses = { addUser, getAllUser, @@ -53,6 +58,7 @@ const responses = { updateEnrolledCourses, getWishlist, addWishlist, + deleteWishList, }; export default responses; From 0cfef6e507dfef1b6c023278309ac43e7089df83 Mon Sep 17 00:00:00 2001 From: Devesh Date: Sat, 19 Jun 2021 15:46:18 +0530 Subject: [PATCH 06/13] use internalserver error nestjs exception instead of httpexception --- src/modules/assignment/assignment.service.ts | 51 ++------- src/modules/course/course.service.ts | 67 ++---------- src/modules/doubt/doubt.service.ts | 27 +---- src/modules/user/user.service.ts | 107 +++---------------- 4 files changed, 34 insertions(+), 218 deletions(-) diff --git a/src/modules/assignment/assignment.service.ts b/src/modules/assignment/assignment.service.ts index c1327aa..0b2ebb8 100644 --- a/src/modules/assignment/assignment.service.ts +++ b/src/modules/assignment/assignment.service.ts @@ -1,7 +1,6 @@ import { - HttpException, - HttpStatus, Injectable, + InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { Model } from 'mongoose'; @@ -23,13 +22,7 @@ export class AssignmentService { const Assignments = await this.AssignmentModel.find().exec(); return Assignments; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -43,22 +36,10 @@ export class AssignmentService { return Assignment; } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } - throw new HttpException( - { - status: HttpStatus.NOT_FOUND, - error: 'Assignment Not Found', - }, - HttpStatus.NOT_FOUND, - ); + throw new NotFoundException('Assignment not found'); } // post a single Assignment @@ -73,13 +54,7 @@ export class AssignmentService { } throw new NotFoundException('doubt not found!'); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -98,13 +73,7 @@ export class AssignmentService { return updatedAssignment; } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } throw new NotFoundException('doubt not found!'); } @@ -120,13 +89,7 @@ export class AssignmentService { } throw new NotFoundException('doubt not found!'); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } } diff --git a/src/modules/course/course.service.ts b/src/modules/course/course.service.ts index 106d1eb..47034ed 100644 --- a/src/modules/course/course.service.ts +++ b/src/modules/course/course.service.ts @@ -1,7 +1,6 @@ import { - HttpException, - HttpStatus, Injectable, + InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; @@ -26,13 +25,7 @@ export class CourseService { try { return await this.CourseModel.find().exec(); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -48,13 +41,7 @@ export class CourseService { throw new NotFoundException('course not found'); } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -67,13 +54,7 @@ export class CourseService { return newCourse; } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } throw new NotFoundException('doubt not found!'); } @@ -91,13 +72,7 @@ export class CourseService { { new: true }, ); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } finally { return updatedCourse; } @@ -109,13 +84,7 @@ export class CourseService { const deletedCourse = await this.CourseModel.findByIdAndRemove(courseId); return deletedCourse; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -138,13 +107,7 @@ export class CourseService { ); } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -170,13 +133,7 @@ export class CourseService { ); } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -199,13 +156,7 @@ export class CourseService { ); } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } } diff --git a/src/modules/doubt/doubt.service.ts b/src/modules/doubt/doubt.service.ts index 0cbbf89..267a595 100644 --- a/src/modules/doubt/doubt.service.ts +++ b/src/modules/doubt/doubt.service.ts @@ -1,7 +1,6 @@ import { - HttpException, - HttpStatus, Injectable, + InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; @@ -19,13 +18,7 @@ export class DoubtService { try { return await this.DoubtModel.find().exec(); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -37,13 +30,7 @@ export class DoubtService { return doubt; } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } throw new NotFoundException('doubt not found!'); @@ -53,13 +40,7 @@ export class DoubtService { try { return await new this.DoubtModel(newDoubt).save(); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } } diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 90a34a1..3632761 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -1,7 +1,6 @@ import { - HttpException, - HttpStatus, Injectable, + InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { Model, Schema } from 'mongoose'; @@ -29,13 +28,7 @@ export class UserService { const users = await this.userModel.find().exec(); return users; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -48,13 +41,7 @@ export class UserService { return user; } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } throw new NotFoundException('Error'); } @@ -65,13 +52,7 @@ export class UserService { const newUser = await new this.userModel(CreateUserDTO); return newUser.save(); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -88,13 +69,7 @@ export class UserService { { new: true, useFindAndModify: false }, ); } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } finally { return updatedUser; } @@ -107,13 +82,7 @@ export class UserService { deletedUser = await this.userModel.findByIdAndRemove(userID); return deletedUser; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -129,13 +98,7 @@ export class UserService { }); return enrolledCourses; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -147,13 +110,7 @@ export class UserService { }); return enrolledCourses; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -181,13 +138,7 @@ export class UserService { /*const newF = await this.enrolledModel.find({}).populate('students'); return newF;*/ } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -199,13 +150,7 @@ export class UserService { const userWishList = await this.findUserById(userId); return userWishList.wishlist; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -223,13 +168,7 @@ export class UserService { return UserWishList; } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } throw new NotFoundException('course could not be wishlisted'); @@ -252,13 +191,7 @@ export class UserService { throw new NotFoundException('not found'); } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -279,13 +212,7 @@ export class UserService { ); return updatedCourse; } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } @@ -306,13 +233,7 @@ export class UserService { throw new NotFoundException('not found'); } } catch (e) { - throw new HttpException( - { - status: HttpStatus.INTERNAL_SERVER_ERROR, - error: `${e}`, - }, - HttpStatus.INTERNAL_SERVER_ERROR, - ); + throw new InternalServerErrorException(e); } } } From 3a28342a52005eebbd84ce12a21768edf4d007df Mon Sep 17 00:00:00 2001 From: Devesh Date: Sun, 20 Jun 2021 22:24:59 +0530 Subject: [PATCH 07/13] user tests and course controller tests and other fixes in dtos --- src/modules/course/course.controller.spec.ts | 51 +++- src/modules/user/dto/create-user.dto.ts | 6 + src/modules/user/dto/update-user.dto.ts | 2 +- .../interfaces/user-document.interface.ts | 25 ++ src/modules/user/interfaces/user.interface.ts | 28 ++ src/modules/user/user.service.spec.ts | 245 +++++++++++++++++- 6 files changed, 352 insertions(+), 5 deletions(-) create mode 100644 src/modules/user/interfaces/user-document.interface.ts create mode 100644 src/modules/user/interfaces/user.interface.ts diff --git a/src/modules/course/course.controller.spec.ts b/src/modules/course/course.controller.spec.ts index f650ed3..b204c87 100644 --- a/src/modules/course/course.controller.spec.ts +++ b/src/modules/course/course.controller.spec.ts @@ -1,9 +1,42 @@ import { Test, TestingModule } from '@nestjs/testing'; import { CourseController } from './course.controller'; import { CourseService } from './course.service'; +import * as mongoose from 'mongoose'; +const mockCourse = { + schedule: ['60cda21c44ce7c2e3c4a43e8', '60cdb0f4a358e5603c6bedd4'], + assignments: [], + mentor: [], + active: false, + name: 'devesh K', + price: 0, + coupons: 0, + video_num: 0, + duration: '11.5 hours', + start_date: '2020-02-05T06:35:22.000Z', + end_date: '2020-02-05T06:35:22.000Z', + sharable_link: '88900xyz.com', + id: '60c5eafba5940a4964d5ea96', +}; describe('CourseController', () => { let controller: CourseController; + let service: CourseService; + + const mockCoursevalue = { + getAllCourses: jest.fn().mockResolvedValue([mockCourse]), + findCourseById: jest + .fn() + .mockImplementation((id: string) => ({ ...mockCourse, id })), + editCourse: jest.fn().mockImplementation((uid, body) => ({ + ...mockCourse, + id: uid, + ...body, + })), + // deleteCourse: jest.fn().mockResolvedValue([mockCourse]), + // getEnrolledCourses: jest.fn().mockResolvedValue([mockCourse]), + // addCourse: jest.fn().mockResolvedValue([mockCourse]), + // getWishList: jest.fn().mockResolvedValue([mockCourse]), + }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -11,15 +44,31 @@ describe('CourseController', () => { providers: [ { provide: CourseService, - useValue: {}, + useValue: mockCoursevalue, }, ], }).compile(); controller = module.get(CourseController); + service = module.get(CourseService); }); it('should be defined', () => { expect(controller).toBeDefined(); }); + + describe('Course', () => { + it('should be created', async () => { + await expect(controller.getAllCourses()).resolves.toEqual([mockCourse]); + }); + + it('should be found by ID', async () => { + const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); + await expect(controller.getSelectedCourse(id)).resolves.toEqual({ + ...mockCourse, + id, + }); + expect(service.findCourseById).toHaveBeenCalledWith(id); + }); + }); }); diff --git a/src/modules/user/dto/create-user.dto.ts b/src/modules/user/dto/create-user.dto.ts index 7712a59..e297bda 100644 --- a/src/modules/user/dto/create-user.dto.ts +++ b/src/modules/user/dto/create-user.dto.ts @@ -40,6 +40,12 @@ export class CreateUserDTO { */ readonly description?: string; + /** + * score of user + * @example 100 + */ + readonly score: number; + /** * The field to show whether the students is Admin or not * @example false diff --git a/src/modules/user/dto/update-user.dto.ts b/src/modules/user/dto/update-user.dto.ts index 664b5d4..9afeae6 100644 --- a/src/modules/user/dto/update-user.dto.ts +++ b/src/modules/user/dto/update-user.dto.ts @@ -43,7 +43,7 @@ export class UpdateUserDTO { readonly description: string; /** - * Number of user + * score of user * @example 100 */ readonly score: number; diff --git a/src/modules/user/interfaces/user-document.interface.ts b/src/modules/user/interfaces/user-document.interface.ts new file mode 100644 index 0000000..829041a --- /dev/null +++ b/src/modules/user/interfaces/user-document.interface.ts @@ -0,0 +1,25 @@ +import { Document, Schema as SchemaTypes } from 'mongoose'; + +export interface UserDoc extends Document { + first_name: string; + + last_name: string; + + email: string; + + phone: string; + + address?: string; + + description?: string; + + isAdmin: boolean; + + photoUrl?: string; + + score: number; + + coverPhotoUrl?: string; + + wishlist: SchemaTypes.Types.ObjectId[]; +} diff --git a/src/modules/user/interfaces/user.interface.ts b/src/modules/user/interfaces/user.interface.ts new file mode 100644 index 0000000..f50863a --- /dev/null +++ b/src/modules/user/interfaces/user.interface.ts @@ -0,0 +1,28 @@ +import { Schema } from 'inspector'; +import { Document, Schema as SchemaTypes } from 'mongoose'; + +export interface User { + first_name: string; + + last_name: string; + + email: string; + + phone: string; + + address?: string; + + description?: string; + + isAdmin: boolean; + + photoUrl?: string; + + coverPhotoUrl?: string; + + score: number; + + _id: string; + + wishlist: SchemaTypes.Types.ObjectId[]; +} diff --git a/src/modules/user/user.service.spec.ts b/src/modules/user/user.service.spec.ts index 0edc3ca..d00c516 100644 --- a/src/modules/user/user.service.spec.ts +++ b/src/modules/user/user.service.spec.ts @@ -1,9 +1,94 @@ import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; import { UserService } from './user.service'; +import { createMock } from '@golevelup/nestjs-testing'; +import { Model, Mongoose, Query } from 'mongoose'; +import * as mongoose from 'mongoose'; +import { User } from './interfaces/user.interface'; +import { UserDoc } from './interfaces/user-document.interface'; +import { Document, Schema as SchemaTypes } from 'mongoose'; +import { UpdateUserDTO } from './dto/update-user.dto'; + +const mockUser = ( + wishlist: [], + isAdmin: false, + _id: '6079f573062890a5e2cad207', + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', +): User => ({ + wishlist, + isAdmin, + _id, + first_name, + last_name, + email, + phone, + photoUrl, + address, + description, + score, + coverPhotoUrl, +}); + +const mockUserDoc = (mock?: Partial): Partial => ({ + wishlist: mock?.wishlist || [], + isAdmin: mock?.isAdmin || false, + _id: mock?._id || '6079f573062890a5e2cad207', + first_name: mock?.first_name || 'John', + last_name: mock?.last_name || 'Doe', + email: mock?.email || 'john@example.com', + phone: mock?.phone || '9909999099', + photoUrl: mock?.photoUrl || 'https://google.com/john', + address: mock?.address || 'Block C Amsterdam', + description: mock?.description || 'Aspiring Software Developer', + score: mock?.score || 0, + coverPhotoUrl: mock?.coverPhotoUrl || 'https://google.com/john', +}); + +const userArray = [ + mockUser( + [], + false, + '6079f573062890a5e2cad207', + 'John', + 'Doe', + 'john@example.com', + '9909999099', + 'https://google.com/john', + 'Block C Amsterdam', + 'Aspiring Software Developer', + 0, + 'https://google.com/john', + ), +]; + +const userDocArray = [ + mockUserDoc({ + wishlist: [], + isAdmin: false, + _id: '6079f573062890a5e2cad207', + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }), +]; describe('UserService', () => { let service: UserService; + let model: Model; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -11,7 +96,17 @@ describe('UserService', () => { UserService, { provide: getModelToken('User'), - useValue: {}, + useValue: { + new: jest.fn().mockResolvedValue(mockUser), + constructor: jest.fn().mockResolvedValue(mockUser), + find: jest.fn(), + findOne: jest.fn(), + findById: jest.fn(), + update: jest.fn(), + create: jest.fn(), + remove: jest.fn(), + exec: jest.fn(), + }, }, { provide: getModelToken('Course'), @@ -25,15 +120,159 @@ describe('UserService', () => { }).compile(); service = module.get(UserService); + model = module.get>(getModelToken('User')); }); it('should be defined', () => { expect(service).toBeDefined(); }); + + afterEach(() => { + jest.clearAllMocks(); + }); + describe('Testing userService after mock', () => { //const id = new mongoose.Schema.Types.ObjectId('60bca010d17d463dd09baf9b'); - it('testing get all method', () => { - expect(typeof service.getAllUser).not.toEqual(null); + + it('should return all users', async () => { + jest.spyOn(model, 'find').mockReturnValue({ + exec: jest.fn().mockResolvedValueOnce(userDocArray), + } as any); + const users = await service.getAllUser(); + // console.log(users); + expect(users).toEqual(userArray); + }); + + it('should getOne user by id', async () => { + jest.spyOn(model, 'findById').mockReturnValueOnce( + createMock>({ + exec: jest.fn().mockResolvedValueOnce( + mockUserDoc({ + wishlist: [], + isAdmin: false, + _id: '6079f573062890a5e2cad207', + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }), + ), + }), + ); + const findMockUser = mockUser( + [], + false, + '6079f573062890a5e2cad207', + 'John', + 'Doe', + 'john@example.com', + '9909999099', + 'https://google.com/john', + 'Block C Amsterdam', + 'Aspiring Software Developer', + 0, + 'https://google.com/john', + ); + const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); + const foundUser = await service.findUserById(id); + expect(foundUser).toEqual(findMockUser); + }); + + /*it('should insert a new user', async () => { + jest.spyOn(model, 'create').mockImplementationOnce(() => + Promise.resolve({ + wishlist: [], + isAdmin: false, + _id: '6079f573062890a5e2cad207', + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + }), + ); + const newUser = await service.addUser({ + isAdmin: false, + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + }); + expect(newUser).toEqual( + mockUser( + [], + false, + '6079f573062890a5e2cad207', + 'John', + 'Doe', + 'john@example.com', + '9909999099', + 'https://google.com/john', + 'Block C Amsterdam', + 'Aspiring Software Developer', + ), + ); + });*/ + + it.skip('should update a User successfully', async () => { + jest.spyOn(model, 'findOneAndUpdate').mockReturnValueOnce( + createMock>({ + exec: jest.fn().mockResolvedValueOnce({ + wishlist: [], + isAdmin: false, + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }), + }), + ); + const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); + const updateUserdto: UpdateUserDTO = { + wishlist: [], + isAdmin: false, + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }; + const updatedUser = await service.updateUser(id, updateUserdto); + expect(updatedUser).toEqual( + mockUser( + [], + false, + '6079f573062890a5e2cad207', + 'John', + 'Doe', + 'john@example.com', + '9909999099', + 'https://google.com/john', + 'Block C Amsterdam', + 'Aspiring Software Developer', + 0, + 'https://google.com/john', + ), + ); }); }); }); From 732de69d61805f16538d6a143efe19008ce7f9d1 Mon Sep 17 00:00:00 2001 From: Devesh Date: Tue, 22 Jun 2021 00:17:07 +0530 Subject: [PATCH 08/13] fixed some error messages --- src/modules/assignment/assignment.service.ts | 9 +++------ src/modules/course/course.service.ts | 5 +---- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/modules/assignment/assignment.service.ts b/src/modules/assignment/assignment.service.ts index 0b2ebb8..f4d6cb0 100644 --- a/src/modules/assignment/assignment.service.ts +++ b/src/modules/assignment/assignment.service.ts @@ -49,10 +49,7 @@ export class AssignmentService { try { const newAssignment = await new this.AssignmentModel(CreateAssignmentDTO); await newAssignment.save(); - if (newAssignment) { - return newAssignment; - } - throw new NotFoundException('doubt not found!'); + return newAssignment; } catch (e) { throw new InternalServerErrorException(e); } @@ -75,7 +72,7 @@ export class AssignmentService { } catch (e) { throw new InternalServerErrorException(e); } - throw new NotFoundException('doubt not found!'); + throw new NotFoundException('Assignment not found!'); } // Delete a Assignment @@ -87,7 +84,7 @@ export class AssignmentService { if (deletedAssignment) { return deletedAssignment; } - throw new NotFoundException('doubt not found!'); + throw new NotFoundException('Assignment not found!'); } catch (e) { throw new InternalServerErrorException(e); } diff --git a/src/modules/course/course.service.ts b/src/modules/course/course.service.ts index 47034ed..8f98254 100644 --- a/src/modules/course/course.service.ts +++ b/src/modules/course/course.service.ts @@ -50,13 +50,10 @@ export class CourseService { try { const newCourse = new this.CourseModel(createCourseDto); await newCourse.save(); - if (newCourse) { - return newCourse; - } + return newCourse; } catch (e) { throw new InternalServerErrorException(e); } - throw new NotFoundException('doubt not found!'); } // edit course by Id From b0d89ad2b72060ae3a72965918f0d36cfc9a17f8 Mon Sep 17 00:00:00 2001 From: Devesh Date: Tue, 22 Jun 2021 00:22:40 +0530 Subject: [PATCH 09/13] installed package --- package-lock.json | 11 +++++++++++ package.json | 1 + 2 files changed, 12 insertions(+) diff --git a/package-lock.json b/package-lock.json index 9cfbf87..e8b864b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.1", "license": "MIT", "dependencies": { + "@golevelup/nestjs-testing": "^0.1.2", "@nestjs/common": "^7.6.17", "@nestjs/core": "^7.6.17", "@nestjs/mongoose": "^7.2.4", @@ -842,6 +843,11 @@ "tslib": "^2.1.0" } }, + "node_modules/@golevelup/nestjs-testing": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@golevelup/nestjs-testing/-/nestjs-testing-0.1.2.tgz", + "integrity": "sha512-7TOpI6E86GBE93DJoCqavOfycAMPjnZDfcpdBrm/aWUoR/oDxHjhTr1R8NGVY4+iHY5wDwEXG7mcDkDEWQznfQ==" + }, "node_modules/@google-cloud/common": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/@google-cloud/common/-/common-3.6.0.tgz", @@ -13767,6 +13773,11 @@ "tslib": "^2.1.0" } }, + "@golevelup/nestjs-testing": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@golevelup/nestjs-testing/-/nestjs-testing-0.1.2.tgz", + "integrity": "sha512-7TOpI6E86GBE93DJoCqavOfycAMPjnZDfcpdBrm/aWUoR/oDxHjhTr1R8NGVY4+iHY5wDwEXG7mcDkDEWQznfQ==" + }, "@google-cloud/common": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/@google-cloud/common/-/common-3.6.0.tgz", diff --git a/package.json b/package.json index c5712a4..c58114d 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "test:e2e": "jest --config ./test/jest-e2e.json" }, "dependencies": { + "@golevelup/nestjs-testing": "^0.1.2", "@nestjs/common": "^7.6.17", "@nestjs/core": "^7.6.17", "@nestjs/mongoose": "^7.2.4", From fb5e3273906eefdc4c3dcd9ebefe811e8a70753a Mon Sep 17 00:00:00 2001 From: Devesh Date: Tue, 22 Jun 2021 00:25:44 +0530 Subject: [PATCH 10/13] remove commented out code --- src/modules/user/user.service.spec.ts | 41 --------------------------- 1 file changed, 41 deletions(-) diff --git a/src/modules/user/user.service.spec.ts b/src/modules/user/user.service.spec.ts index d00c516..9ac903b 100644 --- a/src/modules/user/user.service.spec.ts +++ b/src/modules/user/user.service.spec.ts @@ -183,47 +183,6 @@ describe('UserService', () => { expect(foundUser).toEqual(findMockUser); }); - /*it('should insert a new user', async () => { - jest.spyOn(model, 'create').mockImplementationOnce(() => - Promise.resolve({ - wishlist: [], - isAdmin: false, - _id: '6079f573062890a5e2cad207', - first_name: 'John', - last_name: 'Doe', - email: 'john@example.com', - phone: '9909999099', - photoUrl: 'https://google.com/john', - address: 'Block C Amsterdam', - description: 'Aspiring Software Developer', - }), - ); - const newUser = await service.addUser({ - isAdmin: false, - first_name: 'John', - last_name: 'Doe', - email: 'john@example.com', - phone: '9909999099', - photoUrl: 'https://google.com/john', - address: 'Block C Amsterdam', - description: 'Aspiring Software Developer', - }); - expect(newUser).toEqual( - mockUser( - [], - false, - '6079f573062890a5e2cad207', - 'John', - 'Doe', - 'john@example.com', - '9909999099', - 'https://google.com/john', - 'Block C Amsterdam', - 'Aspiring Software Developer', - ), - ); - });*/ - it.skip('should update a User successfully', async () => { jest.spyOn(model, 'findOneAndUpdate').mockReturnValueOnce( createMock>({ From d385a0a1f74cd49265396f6318d1b3f20a4374a2 Mon Sep 17 00:00:00 2001 From: Devesh Date: Tue, 22 Jun 2021 00:46:02 +0530 Subject: [PATCH 11/13] remove unused imports --- src/modules/user/interfaces/user.interface.ts | 3 +-- src/modules/user/user.controller.ts | 1 - src/modules/user/user.service.spec.ts | 3 +-- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/modules/user/interfaces/user.interface.ts b/src/modules/user/interfaces/user.interface.ts index f50863a..a297436 100644 --- a/src/modules/user/interfaces/user.interface.ts +++ b/src/modules/user/interfaces/user.interface.ts @@ -1,5 +1,4 @@ -import { Schema } from 'inspector'; -import { Document, Schema as SchemaTypes } from 'mongoose'; +import { Schema as SchemaTypes } from 'mongoose'; export interface User { first_name: string; diff --git a/src/modules/user/user.controller.ts b/src/modules/user/user.controller.ts index 8ad7697..e9b446c 100644 --- a/src/modules/user/user.controller.ts +++ b/src/modules/user/user.controller.ts @@ -22,7 +22,6 @@ import { UpdateEnrolledDTO } from './dto/update-enrolled.dto'; import { Schema } from 'mongoose'; import responsedoc from './docUtils/apidoc'; import { userId } from './docUtils/user.paramdocs'; -import { CreateWishlistDTO } from './dto/create-wishlist.dto'; @ApiTags('User') @Controller('user') diff --git a/src/modules/user/user.service.spec.ts b/src/modules/user/user.service.spec.ts index 9ac903b..7f55822 100644 --- a/src/modules/user/user.service.spec.ts +++ b/src/modules/user/user.service.spec.ts @@ -2,11 +2,10 @@ import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; import { UserService } from './user.service'; import { createMock } from '@golevelup/nestjs-testing'; -import { Model, Mongoose, Query } from 'mongoose'; +import { Model, Query } from 'mongoose'; import * as mongoose from 'mongoose'; import { User } from './interfaces/user.interface'; import { UserDoc } from './interfaces/user-document.interface'; -import { Document, Schema as SchemaTypes } from 'mongoose'; import { UpdateUserDTO } from './dto/update-user.dto'; const mockUser = ( From a18fb3f42f9e56fbad30a2baaa8e2d4996a27af0 Mon Sep 17 00:00:00 2001 From: Devesh Date: Tue, 22 Jun 2021 21:56:41 +0530 Subject: [PATCH 12/13] reverted testing --- src/modules/course/course.controller.spec.ts | 51 +---- .../interfaces/user-document.interface.ts | 25 --- src/modules/user/interfaces/user.interface.ts | 27 --- src/modules/user/user.service.spec.ts | 203 +----------------- 4 files changed, 4 insertions(+), 302 deletions(-) delete mode 100644 src/modules/user/interfaces/user-document.interface.ts delete mode 100644 src/modules/user/interfaces/user.interface.ts diff --git a/src/modules/course/course.controller.spec.ts b/src/modules/course/course.controller.spec.ts index b204c87..f650ed3 100644 --- a/src/modules/course/course.controller.spec.ts +++ b/src/modules/course/course.controller.spec.ts @@ -1,42 +1,9 @@ import { Test, TestingModule } from '@nestjs/testing'; import { CourseController } from './course.controller'; import { CourseService } from './course.service'; -import * as mongoose from 'mongoose'; -const mockCourse = { - schedule: ['60cda21c44ce7c2e3c4a43e8', '60cdb0f4a358e5603c6bedd4'], - assignments: [], - mentor: [], - active: false, - name: 'devesh K', - price: 0, - coupons: 0, - video_num: 0, - duration: '11.5 hours', - start_date: '2020-02-05T06:35:22.000Z', - end_date: '2020-02-05T06:35:22.000Z', - sharable_link: '88900xyz.com', - id: '60c5eafba5940a4964d5ea96', -}; describe('CourseController', () => { let controller: CourseController; - let service: CourseService; - - const mockCoursevalue = { - getAllCourses: jest.fn().mockResolvedValue([mockCourse]), - findCourseById: jest - .fn() - .mockImplementation((id: string) => ({ ...mockCourse, id })), - editCourse: jest.fn().mockImplementation((uid, body) => ({ - ...mockCourse, - id: uid, - ...body, - })), - // deleteCourse: jest.fn().mockResolvedValue([mockCourse]), - // getEnrolledCourses: jest.fn().mockResolvedValue([mockCourse]), - // addCourse: jest.fn().mockResolvedValue([mockCourse]), - // getWishList: jest.fn().mockResolvedValue([mockCourse]), - }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -44,31 +11,15 @@ describe('CourseController', () => { providers: [ { provide: CourseService, - useValue: mockCoursevalue, + useValue: {}, }, ], }).compile(); controller = module.get(CourseController); - service = module.get(CourseService); }); it('should be defined', () => { expect(controller).toBeDefined(); }); - - describe('Course', () => { - it('should be created', async () => { - await expect(controller.getAllCourses()).resolves.toEqual([mockCourse]); - }); - - it('should be found by ID', async () => { - const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); - await expect(controller.getSelectedCourse(id)).resolves.toEqual({ - ...mockCourse, - id, - }); - expect(service.findCourseById).toHaveBeenCalledWith(id); - }); - }); }); diff --git a/src/modules/user/interfaces/user-document.interface.ts b/src/modules/user/interfaces/user-document.interface.ts deleted file mode 100644 index 829041a..0000000 --- a/src/modules/user/interfaces/user-document.interface.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Document, Schema as SchemaTypes } from 'mongoose'; - -export interface UserDoc extends Document { - first_name: string; - - last_name: string; - - email: string; - - phone: string; - - address?: string; - - description?: string; - - isAdmin: boolean; - - photoUrl?: string; - - score: number; - - coverPhotoUrl?: string; - - wishlist: SchemaTypes.Types.ObjectId[]; -} diff --git a/src/modules/user/interfaces/user.interface.ts b/src/modules/user/interfaces/user.interface.ts deleted file mode 100644 index a297436..0000000 --- a/src/modules/user/interfaces/user.interface.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { Schema as SchemaTypes } from 'mongoose'; - -export interface User { - first_name: string; - - last_name: string; - - email: string; - - phone: string; - - address?: string; - - description?: string; - - isAdmin: boolean; - - photoUrl?: string; - - coverPhotoUrl?: string; - - score: number; - - _id: string; - - wishlist: SchemaTypes.Types.ObjectId[]; -} diff --git a/src/modules/user/user.service.spec.ts b/src/modules/user/user.service.spec.ts index 7f55822..0edc3ca 100644 --- a/src/modules/user/user.service.spec.ts +++ b/src/modules/user/user.service.spec.ts @@ -1,93 +1,9 @@ import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; import { UserService } from './user.service'; -import { createMock } from '@golevelup/nestjs-testing'; -import { Model, Query } from 'mongoose'; -import * as mongoose from 'mongoose'; -import { User } from './interfaces/user.interface'; -import { UserDoc } from './interfaces/user-document.interface'; -import { UpdateUserDTO } from './dto/update-user.dto'; - -const mockUser = ( - wishlist: [], - isAdmin: false, - _id: '6079f573062890a5e2cad207', - first_name: 'John', - last_name: 'Doe', - email: 'john@example.com', - phone: '9909999099', - photoUrl: 'https://google.com/john', - address: 'Block C Amsterdam', - description: 'Aspiring Software Developer', - score: 0, - coverPhotoUrl: 'https://google.com/john', -): User => ({ - wishlist, - isAdmin, - _id, - first_name, - last_name, - email, - phone, - photoUrl, - address, - description, - score, - coverPhotoUrl, -}); - -const mockUserDoc = (mock?: Partial): Partial => ({ - wishlist: mock?.wishlist || [], - isAdmin: mock?.isAdmin || false, - _id: mock?._id || '6079f573062890a5e2cad207', - first_name: mock?.first_name || 'John', - last_name: mock?.last_name || 'Doe', - email: mock?.email || 'john@example.com', - phone: mock?.phone || '9909999099', - photoUrl: mock?.photoUrl || 'https://google.com/john', - address: mock?.address || 'Block C Amsterdam', - description: mock?.description || 'Aspiring Software Developer', - score: mock?.score || 0, - coverPhotoUrl: mock?.coverPhotoUrl || 'https://google.com/john', -}); - -const userArray = [ - mockUser( - [], - false, - '6079f573062890a5e2cad207', - 'John', - 'Doe', - 'john@example.com', - '9909999099', - 'https://google.com/john', - 'Block C Amsterdam', - 'Aspiring Software Developer', - 0, - 'https://google.com/john', - ), -]; - -const userDocArray = [ - mockUserDoc({ - wishlist: [], - isAdmin: false, - _id: '6079f573062890a5e2cad207', - first_name: 'John', - last_name: 'Doe', - email: 'john@example.com', - phone: '9909999099', - photoUrl: 'https://google.com/john', - address: 'Block C Amsterdam', - description: 'Aspiring Software Developer', - score: 0, - coverPhotoUrl: 'https://google.com/john', - }), -]; describe('UserService', () => { let service: UserService; - let model: Model; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -95,17 +11,7 @@ describe('UserService', () => { UserService, { provide: getModelToken('User'), - useValue: { - new: jest.fn().mockResolvedValue(mockUser), - constructor: jest.fn().mockResolvedValue(mockUser), - find: jest.fn(), - findOne: jest.fn(), - findById: jest.fn(), - update: jest.fn(), - create: jest.fn(), - remove: jest.fn(), - exec: jest.fn(), - }, + useValue: {}, }, { provide: getModelToken('Course'), @@ -119,118 +25,15 @@ describe('UserService', () => { }).compile(); service = module.get(UserService); - model = module.get>(getModelToken('User')); }); it('should be defined', () => { expect(service).toBeDefined(); }); - - afterEach(() => { - jest.clearAllMocks(); - }); - describe('Testing userService after mock', () => { //const id = new mongoose.Schema.Types.ObjectId('60bca010d17d463dd09baf9b'); - - it('should return all users', async () => { - jest.spyOn(model, 'find').mockReturnValue({ - exec: jest.fn().mockResolvedValueOnce(userDocArray), - } as any); - const users = await service.getAllUser(); - // console.log(users); - expect(users).toEqual(userArray); - }); - - it('should getOne user by id', async () => { - jest.spyOn(model, 'findById').mockReturnValueOnce( - createMock>({ - exec: jest.fn().mockResolvedValueOnce( - mockUserDoc({ - wishlist: [], - isAdmin: false, - _id: '6079f573062890a5e2cad207', - first_name: 'John', - last_name: 'Doe', - email: 'john@example.com', - phone: '9909999099', - photoUrl: 'https://google.com/john', - address: 'Block C Amsterdam', - description: 'Aspiring Software Developer', - score: 0, - coverPhotoUrl: 'https://google.com/john', - }), - ), - }), - ); - const findMockUser = mockUser( - [], - false, - '6079f573062890a5e2cad207', - 'John', - 'Doe', - 'john@example.com', - '9909999099', - 'https://google.com/john', - 'Block C Amsterdam', - 'Aspiring Software Developer', - 0, - 'https://google.com/john', - ); - const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); - const foundUser = await service.findUserById(id); - expect(foundUser).toEqual(findMockUser); - }); - - it.skip('should update a User successfully', async () => { - jest.spyOn(model, 'findOneAndUpdate').mockReturnValueOnce( - createMock>({ - exec: jest.fn().mockResolvedValueOnce({ - wishlist: [], - isAdmin: false, - first_name: 'John', - last_name: 'Doe', - email: 'john@example.com', - phone: '9909999099', - photoUrl: 'https://google.com/john', - address: 'Block C Amsterdam', - description: 'Aspiring Software Developer', - score: 0, - coverPhotoUrl: 'https://google.com/john', - }), - }), - ); - const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); - const updateUserdto: UpdateUserDTO = { - wishlist: [], - isAdmin: false, - first_name: 'John', - last_name: 'Doe', - email: 'john@example.com', - phone: '9909999099', - photoUrl: 'https://google.com/john', - address: 'Block C Amsterdam', - description: 'Aspiring Software Developer', - score: 0, - coverPhotoUrl: 'https://google.com/john', - }; - const updatedUser = await service.updateUser(id, updateUserdto); - expect(updatedUser).toEqual( - mockUser( - [], - false, - '6079f573062890a5e2cad207', - 'John', - 'Doe', - 'john@example.com', - '9909999099', - 'https://google.com/john', - 'Block C Amsterdam', - 'Aspiring Software Developer', - 0, - 'https://google.com/john', - ), - ); + it('testing get all method', () => { + expect(typeof service.getAllUser).not.toEqual(null); }); }); }); From ae56859a7afddcaf35c68d5d1ccb8d6ab15c2f65 Mon Sep 17 00:00:00 2001 From: Devesh Date: Wed, 23 Jun 2021 13:04:45 +0530 Subject: [PATCH 13/13] add user service tests with its interfaces and methods --- .../interfaces/user-document.interface.ts | 25 +++ src/modules/user/interfaces/user.interface.ts | 27 +++ src/modules/user/user.service.spec.ts | 203 +++++++++++++++++- 3 files changed, 252 insertions(+), 3 deletions(-) create mode 100644 src/modules/user/interfaces/user-document.interface.ts create mode 100644 src/modules/user/interfaces/user.interface.ts diff --git a/src/modules/user/interfaces/user-document.interface.ts b/src/modules/user/interfaces/user-document.interface.ts new file mode 100644 index 0000000..829041a --- /dev/null +++ b/src/modules/user/interfaces/user-document.interface.ts @@ -0,0 +1,25 @@ +import { Document, Schema as SchemaTypes } from 'mongoose'; + +export interface UserDoc extends Document { + first_name: string; + + last_name: string; + + email: string; + + phone: string; + + address?: string; + + description?: string; + + isAdmin: boolean; + + photoUrl?: string; + + score: number; + + coverPhotoUrl?: string; + + wishlist: SchemaTypes.Types.ObjectId[]; +} diff --git a/src/modules/user/interfaces/user.interface.ts b/src/modules/user/interfaces/user.interface.ts new file mode 100644 index 0000000..a297436 --- /dev/null +++ b/src/modules/user/interfaces/user.interface.ts @@ -0,0 +1,27 @@ +import { Schema as SchemaTypes } from 'mongoose'; + +export interface User { + first_name: string; + + last_name: string; + + email: string; + + phone: string; + + address?: string; + + description?: string; + + isAdmin: boolean; + + photoUrl?: string; + + coverPhotoUrl?: string; + + score: number; + + _id: string; + + wishlist: SchemaTypes.Types.ObjectId[]; +} diff --git a/src/modules/user/user.service.spec.ts b/src/modules/user/user.service.spec.ts index 0edc3ca..7f55822 100644 --- a/src/modules/user/user.service.spec.ts +++ b/src/modules/user/user.service.spec.ts @@ -1,9 +1,93 @@ import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; import { UserService } from './user.service'; +import { createMock } from '@golevelup/nestjs-testing'; +import { Model, Query } from 'mongoose'; +import * as mongoose from 'mongoose'; +import { User } from './interfaces/user.interface'; +import { UserDoc } from './interfaces/user-document.interface'; +import { UpdateUserDTO } from './dto/update-user.dto'; + +const mockUser = ( + wishlist: [], + isAdmin: false, + _id: '6079f573062890a5e2cad207', + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', +): User => ({ + wishlist, + isAdmin, + _id, + first_name, + last_name, + email, + phone, + photoUrl, + address, + description, + score, + coverPhotoUrl, +}); + +const mockUserDoc = (mock?: Partial): Partial => ({ + wishlist: mock?.wishlist || [], + isAdmin: mock?.isAdmin || false, + _id: mock?._id || '6079f573062890a5e2cad207', + first_name: mock?.first_name || 'John', + last_name: mock?.last_name || 'Doe', + email: mock?.email || 'john@example.com', + phone: mock?.phone || '9909999099', + photoUrl: mock?.photoUrl || 'https://google.com/john', + address: mock?.address || 'Block C Amsterdam', + description: mock?.description || 'Aspiring Software Developer', + score: mock?.score || 0, + coverPhotoUrl: mock?.coverPhotoUrl || 'https://google.com/john', +}); + +const userArray = [ + mockUser( + [], + false, + '6079f573062890a5e2cad207', + 'John', + 'Doe', + 'john@example.com', + '9909999099', + 'https://google.com/john', + 'Block C Amsterdam', + 'Aspiring Software Developer', + 0, + 'https://google.com/john', + ), +]; + +const userDocArray = [ + mockUserDoc({ + wishlist: [], + isAdmin: false, + _id: '6079f573062890a5e2cad207', + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }), +]; describe('UserService', () => { let service: UserService; + let model: Model; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -11,7 +95,17 @@ describe('UserService', () => { UserService, { provide: getModelToken('User'), - useValue: {}, + useValue: { + new: jest.fn().mockResolvedValue(mockUser), + constructor: jest.fn().mockResolvedValue(mockUser), + find: jest.fn(), + findOne: jest.fn(), + findById: jest.fn(), + update: jest.fn(), + create: jest.fn(), + remove: jest.fn(), + exec: jest.fn(), + }, }, { provide: getModelToken('Course'), @@ -25,15 +119,118 @@ describe('UserService', () => { }).compile(); service = module.get(UserService); + model = module.get>(getModelToken('User')); }); it('should be defined', () => { expect(service).toBeDefined(); }); + + afterEach(() => { + jest.clearAllMocks(); + }); + describe('Testing userService after mock', () => { //const id = new mongoose.Schema.Types.ObjectId('60bca010d17d463dd09baf9b'); - it('testing get all method', () => { - expect(typeof service.getAllUser).not.toEqual(null); + + it('should return all users', async () => { + jest.spyOn(model, 'find').mockReturnValue({ + exec: jest.fn().mockResolvedValueOnce(userDocArray), + } as any); + const users = await service.getAllUser(); + // console.log(users); + expect(users).toEqual(userArray); + }); + + it('should getOne user by id', async () => { + jest.spyOn(model, 'findById').mockReturnValueOnce( + createMock>({ + exec: jest.fn().mockResolvedValueOnce( + mockUserDoc({ + wishlist: [], + isAdmin: false, + _id: '6079f573062890a5e2cad207', + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }), + ), + }), + ); + const findMockUser = mockUser( + [], + false, + '6079f573062890a5e2cad207', + 'John', + 'Doe', + 'john@example.com', + '9909999099', + 'https://google.com/john', + 'Block C Amsterdam', + 'Aspiring Software Developer', + 0, + 'https://google.com/john', + ); + const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); + const foundUser = await service.findUserById(id); + expect(foundUser).toEqual(findMockUser); + }); + + it.skip('should update a User successfully', async () => { + jest.spyOn(model, 'findOneAndUpdate').mockReturnValueOnce( + createMock>({ + exec: jest.fn().mockResolvedValueOnce({ + wishlist: [], + isAdmin: false, + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }), + }), + ); + const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex'); + const updateUserdto: UpdateUserDTO = { + wishlist: [], + isAdmin: false, + first_name: 'John', + last_name: 'Doe', + email: 'john@example.com', + phone: '9909999099', + photoUrl: 'https://google.com/john', + address: 'Block C Amsterdam', + description: 'Aspiring Software Developer', + score: 0, + coverPhotoUrl: 'https://google.com/john', + }; + const updatedUser = await service.updateUser(id, updateUserdto); + expect(updatedUser).toEqual( + mockUser( + [], + false, + '6079f573062890a5e2cad207', + 'John', + 'Doe', + 'john@example.com', + '9909999099', + 'https://google.com/john', + 'Block C Amsterdam', + 'Aspiring Software Developer', + 0, + 'https://google.com/john', + ), + ); }); }); });