Skip to content

Instantly share code, notes, and snippets.

@Lori-Becker
Created May 11, 2023 16:22
Show Gist options
  • Save Lori-Becker/48b6968b84ed820f1c8e7e899fbce9fe to your computer and use it in GitHub Desktop.
Save Lori-Becker/48b6968b84ed820f1c8e7e899fbce9fe to your computer and use it in GitHub Desktop.
TS Version of mocking ResizeObserver
type ResizeObserverMockCallback = (entries: ResizeObserverEntry[]) => void;
interface IResizeObserverMock {
observe: (target: Element) => void;
disconnect: () => void;
unobserve: (target: Element) => void;
}
function ResizeObserverMock(callback: ResizeObserverMockCallback): IResizeObserverMock {
let timeout: ReturnType<typeof setTimeout>;
return {
observe: (element: Element) => {
timeout = setTimeout(() => {
const entry: ResizeObserverEntry = {
target: element,
contentRect: element.getBoundingClientRect(),
borderBoxSize: [{ inlineSize: element.clientWidth, blockSize: element.clientHeight }],
contentBoxSize: [],
devicePixelContentBoxSize: [],
};
callback([entry]);
});
},
disconnect: () => {
clearTimeout(timeout);
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
unobserve: () => {},
};
}
const originalResizeObserver: typeof window.ResizeObserver = window.ResizeObserver;
beforeEach(() => {
(window as any).ResizeObserver = ResizeObserverMock;
});
afterEach(() => {
window.ResizeObserver = originalResizeObserver;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment