@@ -11,6 +11,7 @@ import {
1111 fill ,
1212 markFunctionWrapped ,
1313 objectify ,
14+ wrapMethod ,
1415} from '../../../src/utils/object' ;
1516import { testOnlyIfNodeVersionAtLeast } from '../../testutils' ;
1617
@@ -455,3 +456,47 @@ describe('markFunctionWrapped', () => {
455456 expect ( originalFunc ) . not . toHaveBeenCalled ( ) ;
456457 } ) ;
457458} ) ;
459+
460+ describe ( 'wrapMethod' , ( ) => {
461+ it ( 'can wrap a method on an object' , ( ) => {
462+ const wrappedEnumerable = ( ) => { } ;
463+ const originalEnumerable = ( ) => { } ;
464+ const wrappedNotEnumerable = ( ) => { } ;
465+ const originalNotEnumerable = ( ) => { } ;
466+ const obj : Record < string , unknown > = {
467+ enumerable : originalEnumerable ,
468+ } ;
469+ Object . defineProperty ( obj , 'notEnumerable' , {
470+ writable : true ,
471+ configurable : true ,
472+ enumerable : false ,
473+ value : originalNotEnumerable ,
474+ } ) ;
475+ wrapMethod ( obj , 'notEnumerable' , wrappedNotEnumerable , false ) ;
476+ wrapMethod ( obj , 'enumerable' , wrappedEnumerable ) ;
477+ // does not change enumerability
478+ expect ( Object . keys ( obj ) ) . toStrictEqual ( [ 'enumerable' ] ) ;
479+ expect ( obj . notEnumerable ) . toBe ( wrappedNotEnumerable ) ;
480+ expect ( ( obj . notEnumerable as WrappedFunction ) . __sentry_original__ ) . toBe ( originalNotEnumerable ) ;
481+ expect ( obj . enumerable ) . toBe ( wrappedEnumerable ) ;
482+ expect ( ( obj . enumerable as WrappedFunction ) . __sentry_original__ ) . toBe ( originalEnumerable ) ;
483+ } ) ;
484+
485+ it ( 'throws if misused' , ( ) => {
486+ const wrapped = ( ) => { } ;
487+ const original = ( ) => { } ;
488+ const obj = {
489+ get m ( ) {
490+ return original ;
491+ } ,
492+ } ;
493+ wrapMethod ( obj , 'm' , wrapped ) ;
494+ expect ( ( ) => {
495+ //@ts -expect-error verify type checking prevents this mistake
496+ wrapMethod ( obj , 'foo' , wrapped ) ;
497+ } ) . toThrowError ( 'Cannot wrap method: foo is not a function' ) ;
498+ expect ( ( ) => {
499+ wrapMethod ( obj , 'm' , wrapped ) ;
500+ } ) . toThrowError ( 'Attempting to wrap method m multiple times' ) ;
501+ } ) ;
502+ } ) ;
0 commit comments