diff --git a/packages/tracer/src/Tracer.ts b/packages/tracer/src/Tracer.ts index a5c7aa1aaa..663b98afc7 100644 --- a/packages/tracer/src/Tracer.ts +++ b/packages/tracer/src/Tracer.ts @@ -424,7 +424,7 @@ class Tracer extends Utility implements TracerInterface { return this.provider.captureAsyncFunc(`### ${originalMethod.name}`, async subsegment => { let result; try { - result = await originalMethod.apply(this, [...args]); + result = await originalMethod.apply(target, [...args]); this.addResponseAsMetadata(result, originalMethod.name); } catch (error) { this.addErrorAsMetadata(error as Error); diff --git a/packages/tracer/tests/unit/Tracer.test.ts b/packages/tracer/tests/unit/Tracer.test.ts index 6644e25a46..0c6e086508 100644 --- a/packages/tracer/tests/unit/Tracer.test.ts +++ b/packages/tracer/tests/unit/Tracer.test.ts @@ -973,6 +973,42 @@ describe('Class: Tracer', () => { }); + test('when used as decorator and when calling other methods/props in the class they are called in the orginal scope', async () => { + + // Prepare + const tracer: Tracer = new Tracer(); + const newSubsegment: Segment | Subsegment | undefined = new Subsegment('### dummyMethod'); + jest.spyOn(tracer.provider, 'getSegment') + .mockImplementation(() => newSubsegment); + setContextMissingStrategy(() => null); + + class Lambda implements LambdaInterface { + + @tracer.captureMethod() + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + public async dummyMethod(): Promise { + return `otherMethod:${this.otherMethod()}`; + } + + @tracer.captureLambdaHandler() + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + public async handler(_event: TEvent, _context: Context, _callback: Callback): void | Promise { + return (await this.dummyMethod() as unknown); + } + + public otherMethod(): string { + return 'otherMethod'; + } + + } + + // Act / Assess + expect(await (new Lambda()).handler({}, context, () => console.log('Lambda invoked!'))).toEqual('otherMethod:otherMethod'); + + }); + }); describe('Method: captureAWS', () => {