import { IRouter , KibanaRequest , RequestHandlerContext , RouteValidatorConfig , } from 'src/core/server' ; import { httpServiceMock , httpServerMock } from 'src/core/server/mocks' ; /**
 * Test helper that mocks Kibana's router and DRYs out various helper (callRoute, schema validation)
 */ type MethodType = 'get' | 'post' | 'put' | 'patch' | 'delete' ; type PayloadType = 'params' | 'query' | 'body' ; interface IMockRouter { method : MethodType ; path : string ; } interface IMockRouterRequest { body ? : object ; query ? : object ; params ? : object ; } type MockRouterRequest = KibanaRequest | IMockRouterRequest ; export class MockRouter { public router ! : jest . Mocked < IRouter > ; public method : MethodType ; public path : string ; public payload ? : PayloadType ; public response = httpServerMock . createResponseFactory ( ) ; constructor ( { method , path } ) { this . createRouter ( ) ; this . method = method ; this . path = path ; } public createRouter = ( ) => { this . router = httpServiceMock . createRouter ( ) ; } ; public callRoute = async ( request ) => { const route = this . findRouteRegistration ( ) ; const [ , handler ] = route ; const context = { } as jest . Mocked < RequestHandlerContext > ; await handler ( context , httpServerMock . createKibanaRequest ( request as any ) , this . response ) ; } ; /**
     * Schema validation helpers
     */ public validateRoute = ( request ) => { const route = this . findRouteRegistration ( ) ; const [ config ] = route ; const validate = config . validate as RouteValidatorConfig < { } , { } , { } > ; const payloads = Object . keys ( request ) as PayloadType [ ] ; payloads . forEach ( ( payload ) => { const payloadValidation = validate [ payload ] as { validate ( request ) : void ; } ; const payloadRequest = request [ payload ] as KibanaRequest ; payloadValidation . validate ( payloadRequest ) ; } ) ; } ; public shouldValidate = ( request ) => { expect ( ( ) => this . validateRoute ( request ) ) . not . toThrow ( ) ; } ; public shouldThrow = ( request ) => { expect ( ( ) => this . validateRoute ( request ) ) . toThrow ( ) ; } ; private findRouteRegistration = ( ) => { const routerCalls = this . router [ this . method ] . mock . calls as any [ ] ; if ( ! routerCalls . length ) throw new Error ( 'No routes registered.' ) ; const route = routerCalls . find ( ( [ router ] ) => router . path === this . path ) ; if ( ! route ) throw new Error ( 'No matching registered routes found - check method/path keys' ) ; return route ; } ; } /**
 * Example usage:
 */