import { trace } from '@opentelemetry/api' ; import { hrTimeToMilliseconds , hrTimeToNanoseconds } from '@opentelemetry/core' ; import { registerInstrumentations } from '@opentelemetry/instrumentation' ; import * as tracing from '@opentelemetry/sdk-trace-base' ; import { ReadableSpan } from '@opentelemetry/sdk-trace-base' ; import { WebTracerProvider } from '@opentelemetry/sdk-trace-web' ; import * as assert from 'assert' ; import * as sinon from 'sinon' ; import { LongTaskInstrumentation } from '../src' ; import { DummySpanExporter } from './util' ; const LONGTASK_DURATION = 50 * 1.1 ; function generateLongTask ( ) { const startingTimestamp = performance . now ( ) ; while ( performance . now ( ) - startingTimestamp < LONGTASK_DURATION ) { } } describe ( 'LongTaskInstrumentation' , ( ) => { let longTaskInstrumentation ; let sandbox ; let webTracerProvider ; let dummySpanExporter ; let exportSpy ; let deregister ; beforeEach ( ( ) => { sandbox = sinon . createSandbox ( ) ; webTracerProvider = new WebTracerProvider ( ) ; dummySpanExporter = new DummySpanExporter ( ) ; exportSpy = sandbox . stub ( dummySpanExporter , 'export' ) ; webTracerProvider . addSpanProcessor ( new tracing . SimpleSpanProcessor ( dummySpanExporter ) ) ; webTracerProvider . register ( ) ; longTaskInstrumentation = new LongTaskInstrumentation ( { enabled : false , } ) ; deregister = registerInstrumentations ( { instrumentations : [ longTaskInstrumentation ] , } ) ; } ) ; afterEach ( ( ) => { deregister ( ) ; sandbox . restore ( ) ; exportSpy . restore ( ) ; trace . disable ( ) ; } ) ; it ( 'should report long taking tasks' , async ( ) => { let taskStart ; await new Promise < void > ( resolve => { exportSpy . callsFake ( ( ) => { if ( ! taskStart ) { return ; } resolve ( ) ; } ) ; setTimeout ( ( ) => { exportSpy . resetHistory ( ) ; taskStart = performance . timeOrigin + performance . now ( ) ; generateLongTask ( ) ; } , 1 ) ; } ) ; assert . strictEqual ( exportSpy . args . length , 1 , 'should export once' ) ; assert . strictEqual ( exportSpy . args [ 0 ] [ 0 ] . length , 1 , 'should export one span' ) ; const span = exportSpy . args [ 0 ] [ 0 ] [ 0 ] ; assert . ok ( hrTimeToMilliseconds ( span . startTime ) <= Math . ceil ( taskStart ! ) , 'span start should be when task started' ) ; assert . ok ( hrTimeToNanoseconds ( span . duration ) > LONGTASK_DURATION , "span duration should be longtask's" ) ; } ) ; } ) ;