Created
February 7, 2022 15:27
-
-
Save jpkempf/968a140b833520ae7cf3b5d039568314 to your computer and use it in GitHub Desktop.
Custom Hook to mock the PerformanceObserver API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect } from 'react'; | |
const useMockPerformanceObserver = (): void => { | |
useEffect(() => { | |
const OriginalPerformanceObserver = window.PerformanceObserver; | |
class MockPerformanceObserver extends PerformanceObserver { | |
disconnect = () => null; | |
observe = () => null; | |
takeRecords = () => null; | |
unobserve = () => null; | |
} | |
Object.defineProperty(window, 'PerformanceObserver', { | |
writable: true, | |
configurable: true, | |
value: MockPerformanceObserver, | |
}); | |
Object.defineProperty(global, 'PerformanceObserver', { | |
writable: true, | |
configurable: true, | |
value: MockPerformanceObserver, | |
}); | |
return () => { | |
Object.defineProperty(window, 'PerformanceObserver', { | |
writable: true, | |
configurable: true, | |
value: OriginalPerformanceObserver, | |
}); | |
Object.defineProperty(global, 'PerformanceObserver', { | |
writable: true, | |
configurable: true, | |
value: OriginalPerformanceObserver, | |
}); | |
}; | |
}); | |
}; | |
export default useMockPerformanceObserver; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment