@@ -2,49 +2,51 @@ import errorHandler from '../../../apps/backend/middleware/errorHandler';
22import WxycError from '../../../apps/backend/utils/error' ;
33import { Request , Response , NextFunction } from 'express' ;
44
5- function mockResponse ( ) : Response {
5+ function mockResponse ( ) {
6+ const statusMock = jest . fn ( ) . mockReturnThis ( ) ;
7+ const jsonMock = jest . fn ( ) . mockReturnThis ( ) ;
68 const res = {
7- status : jest . fn ( ) . mockReturnThis ( ) ,
8- json : jest . fn ( ) . mockReturnThis ( ) ,
9- } ;
10- return res as unknown as Response ;
9+ status : statusMock ,
10+ json : jsonMock ,
11+ } as unknown as Response ;
12+ return { res, statusMock , jsonMock } ;
1113}
1214
1315const mockReq = { } as Request ;
1416const mockNext = jest . fn ( ) as NextFunction ;
1517
1618describe ( 'errorHandler middleware' , ( ) => {
1719 it ( 'returns { message } with correct status for WxycError' , ( ) => {
18- const res = mockResponse ( ) ;
20+ const { res, statusMock , jsonMock } = mockResponse ( ) ;
1921 const error = new WxycError ( 'Album not found' , 404 ) ;
2022
2123 errorHandler ( error , mockReq , res , mockNext ) ;
2224
23- expect ( res . status ) . toHaveBeenCalledWith ( 404 ) ;
24- expect ( res . json ) . toHaveBeenCalledWith ( { message : 'Album not found' } ) ;
25+ expect ( statusMock ) . toHaveBeenCalledWith ( 404 ) ;
26+ expect ( jsonMock ) . toHaveBeenCalledWith ( { message : 'Album not found' } ) ;
2527 } ) ;
2628
2729 it ( 'returns generic message for non-WxycError (does not leak internals)' , ( ) => {
28- const res = mockResponse ( ) ;
30+ const { res, statusMock , jsonMock } = mockResponse ( ) ;
2931 const error = new Error ( 'SELECT * FROM users failed: connection refused' ) ;
3032
3133 errorHandler ( error , mockReq , res , mockNext ) ;
3234
33- expect ( res . status ) . toHaveBeenCalledWith ( 500 ) ;
34- expect ( res . json ) . toHaveBeenCalledWith ( { message : 'Internal server error' } ) ;
35+ expect ( statusMock ) . toHaveBeenCalledWith ( 500 ) ;
36+ expect ( jsonMock ) . toHaveBeenCalledWith ( { message : 'Internal server error' } ) ;
3537 } ) ;
3638
3739 it ( 'handles non-Error values thrown' , ( ) => {
38- const res = mockResponse ( ) ;
40+ const { res, statusMock , jsonMock } = mockResponse ( ) ;
3941
4042 errorHandler ( 'something broke' , mockReq , res , mockNext ) ;
4143
42- expect ( res . status ) . toHaveBeenCalledWith ( 500 ) ;
43- expect ( res . json ) . toHaveBeenCalledWith ( { message : 'Internal server error' } ) ;
44+ expect ( statusMock ) . toHaveBeenCalledWith ( 500 ) ;
45+ expect ( jsonMock ) . toHaveBeenCalledWith ( { message : 'Internal server error' } ) ;
4446 } ) ;
4547
4648 it ( 'logs non-WxycError errors to console' , ( ) => {
47- const res = mockResponse ( ) ;
49+ const { res } = mockResponse ( ) ;
4850 const error = new Error ( 'db connection lost' ) ;
4951 const consoleSpy = jest . spyOn ( console , 'error' ) . mockImplementation ( ) ;
5052
0 commit comments