import tachijs , { ConfigSetter , controller , httpGet } from '../../index' ; import request from 'supertest' ; import { ErrorRequestHandler , RequestHandler } from 'express' ; import { reqParams } from '../../decorators' ; describe ( 'controller' , ( ) => { it ( 'sets path to router' , async ( ) => { @ controller ( '/test' ) class HomeController { @ httpGet ( '/' ) index ( ) { return 'Hello' ; } } const app = tachijs ( { controllers : [ HomeController ] } ) ; const response = await request ( app ) . get ( '/test' ) ; expect ( response ) . toMatchObject ( { status : 200 , text : 'Hello' } ) ; } ) ; it ( 'handles thrown errors' , async ( ) => { const errorHandler = ( error , req , res , next ) => res . status ( 500 ) . send ( error . message ) ; const after = expressApp => { expressApp . use ( errorHandler ) ; } ; @ controller ( '/' ) class HomeController { @ httpGet ( '/' ) index ( ) { throw new Error ( 'Error!' ) ; } } const app = tachijs ( { controllers : [ HomeController ] , after } ) ; const response = await request ( app ) . get ( '/' ) ; expect ( response ) . toMatchObject ( { status : 500 , text : 'Error!' } ) ; } ) ; it ( 'sets middlewares' , async ( ) => { const spy = jest . fn ( ) ; const middleware = ( req , res , next ) => { spy ( ) ; next ( ) ; } ; @ controller ( '/test' , [ middleware ] ) class HomeController { @ httpGet ( '/' ) index ( ) { return 'Hello' ; } } const app = tachijs ( { controllers : [ HomeController ] } ) ; const response = await request ( app ) . get ( '/test' ) ; expect ( response ) . toMatchObject ( { status : 200 , text : 'Hello' } ) ; expect ( spy ) . toBeCalled ( ) ; } ) ; it ( 'sets middlewares individually' , async ( ) => { const spy = jest . fn ( ) ; const middleware = ( req , res , next ) => { spy ( ) ; next ( ) ; } ; @ controller ( '/' , [ middleware ] ) class PreemptiveController { @ httpGet ( '/' ) index ( ) { return 'Hello' ; } } @ controller ( '/' ) class TestController { @ httpGet ( '/test' ) index ( ) { return 'User' ; } } const app = tachijs ( { controllers : [ PreemptiveController , TestController ] } ) ; await request ( app ) . get ( '/test' ) ; expect ( spy ) . not . toBeCalled ( ) ; } ) ; it ( 'sets router options' , async ( ) => { @ controller ( '/:name' , [ ] , { mergeParams : true } ) class HomeController { @ httpGet ( '/hello' ) index ( @ reqParams ( 'name' ) name ) { return `Hello, ${ name }` ; } } const app = tachijs ( { controllers : [ HomeController ] } ) ; const response = await request ( app ) . get ( '/test/hello' ) ; expect ( response ) . toMatchObject ( { status : 200 , text : 'Hello, test' } ) ; } ) ; } ) ;