import { setTimeout as setTimeoutPromise } from 'timers/promises' ; import { contextServiceMock , executionContextServiceMock , } from '../../../../../../../../src/core/server/mocks' ; import { createHttpServer } from 'src/core/server/test_utils' ; import supertest from 'supertest' ; import { APMEventClient } from '.' ; describe ( 'APMEventClient' , ( ) => { let server ; beforeEach ( ( ) => { server = createHttpServer ( ) ; } ) ; afterEach ( async ( ) => { await server . stop ( ) ; } ) ; it ( 'cancels a search when a request is aborted' , async ( ) => { await server . preboot ( { context : contextServiceMock . createPrebootContract ( ) , } ) ; const { server : innerServer , createRouter } = await server . setup ( { context : contextServiceMock . createSetupContract ( ) , executionContext : executionContextServiceMock . createInternalSetupContract ( ) , } ) ; const router = createRouter ( '/' ) ; let abortSignal ; router . get ( { path : '/' , validate : false } , async ( context , request , res ) => { const eventClient = new APMEventClient ( { esClient : { search : async ( params , { signal } ) => { abortSignal = signal ; await setTimeoutPromise ( 3000 ) ; return { } ; } , } as any , debug : false , request , indices : { } as any , options : { includeFrozen : false , } , } ) ; await eventClient . search ( 'foo' , { apm : { events : [ ] , } , } ) ; return res . ok ( { body : 'ok' } ) ; } ) ; await server . start ( ) ; expect ( abortSignal ?. aborted ) . toBeFalsy ( ) ; const incomingRequest = supertest ( innerServer . listener ) . get ( '/' ) . end ( ) ; await new Promise ( ( resolve ) => { setTimeout ( ( ) => { incomingRequest . on ( 'abort' , ( ) => { setTimeout ( ( ) => { resolve ( undefined ) ; } , 100 ) ; } ) ; incomingRequest . abort ( ) ; } , 100 ) ; } ) ; expect ( abortSignal ?. aborted ) . toBe ( true ) ; } ) ; } ) ;