@@ -672,10 +672,10 @@ class ModuleMockerClass {
672672 if ( typeof original !== 'function' ) {
673673 throw new Error (
674674 'Cannot spy the ' +
675- methodName +
676- ' property because it is not a function; ' +
677- this . _typeOf ( original ) +
678- ' given instead' ,
675+ methodName +
676+ ' property because it is not a function; ' +
677+ this . _typeOf ( original ) +
678+ ' given instead' ,
679679 ) ;
680680 }
681681
@@ -691,6 +691,65 @@ class ModuleMockerClass {
691691 return object [ methodName ] ;
692692 }
693693
694+ spyOnProperty ( object : any , propertyName : any , accessType = 'get' ) : any {
695+ if ( typeof object !== 'object' && typeof object !== 'function' ) {
696+ throw new Error (
697+ 'Cannot spyOn on a primitive value; ' + this . _typeOf ( object ) + ' given' ,
698+ ) ;
699+ }
700+
701+ if ( ! obj ) {
702+ throw new Error ( 'spyOn could not find an object to spy upon for ' + propertyName + '' ) ;
703+ }
704+
705+ if ( ! propertyName ) {
706+ throw new Error ( 'No property name supplied' ) ;
707+ }
708+
709+ let descriptor ;
710+ try {
711+ descriptor = Object . getOwnPropertyDescriptor ( obj , propertyName ) ;
712+ } catch ( e ) {
713+ // IE 8 doesn't support `definePropery` on non-DOM nodes
714+ }
715+
716+ if ( ! descriptor ) {
717+ throw new Error ( propertyName + ' property does not exist' ) ;
718+ }
719+
720+ if ( ! descriptor . configurable ) {
721+ throw new Error ( propertyName + ' is not declared configurable' ) ;
722+ }
723+
724+ if ( ! descriptor [ accessType ] ) {
725+ throw new Error ( 'Property ' + propertyName + ' does not have access type ' + accessType ) ;
726+ }
727+
728+ const original = descriptor [ accessType ]
729+
730+ if ( ! this . isMockFunction ( original ) ) {
731+ if ( typeof original !== 'function' ) {
732+ throw new Error (
733+ 'Cannot spy the ' +
734+ methodName +
735+ ' property because it is not a function; ' +
736+ this . _typeOf ( original ) +
737+ ' given instead' ,
738+ ) ;
739+ }
740+
741+ descriptor [ accessType ] = this . _makeComponent ( { type : 'function' } , ( ) => {
742+ descriptor [ accessType ] = original ;
743+ } ) ;
744+
745+ descriptor [ accessType ] . mockImplementation ( function ( ) {
746+ return original . apply ( this , arguments ) ;
747+ } ) ;
748+ }
749+
750+ return descriptor [ accessType ] ;
751+ }
752+
694753 clearAllMocks ( ) {
695754 this . _mockState = new WeakMap ( ) ;
696755 }
0 commit comments