Skip to content

Instantly share code, notes, and snippets.

@jpkempf
Created February 7, 2022 15:27
Show Gist options
  • Save jpkempf/968a140b833520ae7cf3b5d039568314 to your computer and use it in GitHub Desktop.
Save jpkempf/968a140b833520ae7cf3b5d039568314 to your computer and use it in GitHub Desktop.
Custom Hook to mock the PerformanceObserver API
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