diff --git a/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts b/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts index 171527418b..da499ec1a9 100644 --- a/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts +++ b/plugins/web/opentelemetry-instrumentation-user-interaction/src/instrumentation.ts @@ -267,7 +267,7 @@ export class UserInteractionInstrumentation extends InstrumentationBase useCapture: any ) { const once = useCapture && useCapture.once; - const patchedListener = (...args: any[]) => { + const patchedListener = function (this: HTMLElement, ...args: any[]) { let parentSpan: api.Span | undefined; const event: Event | undefined = args[0]; const target = event?.target; @@ -285,14 +285,14 @@ export class UserInteractionInstrumentation extends InstrumentationBase return api.context.with( api.trace.setSpan(api.context.active(), span), () => { - const result = plugin._invokeListener(listener, target, args); + const result = plugin._invokeListener(listener, this, args); // no zone so end span immediately span.end(); return result; } ); } else { - return plugin._invokeListener(listener, target, args); + return plugin._invokeListener(listener, this, args); } }; if (plugin.addPatchedListener(this, type, listener, patchedListener)) { diff --git a/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.nozone.test.ts b/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.nozone.test.ts index 7bdae3e4fc..08447543be 100644 --- a/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.nozone.test.ts +++ b/plugins/web/opentelemetry-instrumentation-user-interaction/test/userInteraction.nozone.test.ts @@ -486,7 +486,11 @@ describe('UserInteractionInstrumentation', () => { btn2.setAttribute('id', 'btn2'); root.appendChild(btn2); - root.addEventListener('click', event => { + const listenerThis: EventTarget[] = []; + root.addEventListener('click', function (event) { + // Assert here with failure would also affect other tests due to setTimeout bellow + listenerThis.push(this); + switch (event.target) { case btn1: getData(FILE_URL, () => { @@ -506,6 +510,17 @@ describe('UserInteractionInstrumentation', () => { sandbox.clock.tick(1000); originalSetTimeout(() => { + assert.strictEqual( + listenerThis[0], + root, + 'this inside event listener matches listened target (0)' + ); + assert.strictEqual( + listenerThis[1], + root, + 'this inside event listener matches listened target (1)' + ); + assert.equal(exportSpy.args.length, 4, 'should export 4 spans'); const span1: tracing.ReadableSpan = exportSpy.args[0][0][0];