Created
May 11, 2023 16:22
-
-
Save Lori-Becker/48b6968b84ed820f1c8e7e899fbce9fe to your computer and use it in GitHub Desktop.
TS Version of mocking ResizeObserver
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
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