@@ -8,17 +8,20 @@ jest.mock("../../../../services/UserService");
88import { UserService } from "../../../../services/UserService" ;
99
1010// Mock DTOs
11- jest . mock ( "../../../../modules/user/ dto/CreateUserDto" , ( ) => {
11+ jest . mock ( "../../dto/CreateUserDto" , ( ) => {
1212 return {
13- CreateUserDto : function ( ) {
14- return { } ;
13+ CreateUserDto : function ( data : Record < string , unknown > ) {
14+ // Mock validation logic
15+ if ( ! data . email ) throw new Error ( "Email is required" ) ;
16+ return { email : data . email , ...data } ;
1517 } ,
1618 } ;
1719} ) ;
18- jest . mock ( "../../../../modules/user/ dto/UpdateUserDto" , ( ) => {
20+ jest . mock ( "../../dto/UpdateUserDto" , ( ) => {
1921 return {
20- UpdateUserDto : function ( ) {
21- return { } ;
22+ UpdateUserDto : function ( data : Record < string , unknown > ) {
23+ // Mock basic validation similar to CreateUserDto
24+ return { ...data } ;
2225 } ,
2326 } ;
2427} ) ;
@@ -34,6 +37,10 @@ function setupApp(): Express {
3437 return app ;
3538}
3639
40+ const setupMockUserService = ( methods : Partial < Record < string , unknown > > ) => {
41+ ( UserService as jest . Mock ) . mockImplementation ( ( ) => methods ) ;
42+ } ;
43+
3744describe ( "UserController" , ( ) => {
3845 let app : Express ;
3946
@@ -45,9 +52,9 @@ describe("UserController", () => {
4552 describe ( "POST /users" , ( ) => {
4653 it ( "should create a user and return 201" , async ( ) => {
4754 const mockUser = { id :
"1" , email :
"[email protected] " } ; 48- ( UserService as jest . Mock ) . mockImplementation ( ( ) => ( {
55+ setupMockUserService ( {
4956 createUser : jest . fn ( ) . mockResolvedValue ( mockUser ) ,
50- } ) ) ;
57+ } ) ;
5158 const res = await request ( app )
5259 . post ( "/users" )
5360 . send ( { email :
"[email protected] " } ) ; @@ -65,6 +72,19 @@ describe("UserController", () => {
6572 expect ( res . status ) . toBe ( 400 ) ;
6673 expect ( res . body . error ) . toBe ( "fail" ) ;
6774 } ) ;
75+
76+ it ( "should handle validation errors with specific status codes" , async ( ) => {
77+ ( UserService as jest . Mock ) . mockImplementation ( ( ) => ( {
78+ createUser : jest
79+ . fn ( )
80+ . mockRejectedValue ( new Error ( "Invalid email format" ) ) ,
81+ } ) ) ;
82+ const res = await request ( app )
83+ . post ( "/users" )
84+ . send ( { email : "invalid-email" } ) ;
85+ expect ( res . status ) . toBe ( 422 ) ;
86+ expect ( res . body . error ) . toContain ( "Ivalid email format" ) ;
87+ } ) ;
6888 } ) ;
6989
7090 describe ( "GET /users/:id" , ( ) => {
0 commit comments