({
height,
width
}: {
height: number;
width: number;
})
| 55 | |
| 56 | // Simulates scrolling the window (jsdom doesn't implement window.scrollTo) |
| 57 | export function mockWindowScroll({ |
| 58 | height, |
| 59 | width |
| 60 | }: { |
| 61 | height: number; |
| 62 | width: number; |
| 63 | }) { |
| 64 | const position = { x: 0, y: 0 }; |
| 65 | |
| 66 | // Restore jsdom's own definitions (rather than replacing them) after the test |
| 67 | const originalDescriptors = { |
| 68 | scrollX: Object.getOwnPropertyDescriptor(window, "scrollX"), |
| 69 | scrollY: Object.getOwnPropertyDescriptor(window, "scrollY") |
| 70 | }; |
| 71 | |
| 72 | Object.defineProperty(window, "scrollX", { |
| 73 | configurable: true, |
| 74 | get: () => position.x |
| 75 | }); |
| 76 | Object.defineProperty(window, "scrollY", { |
| 77 | configurable: true, |
| 78 | get: () => position.y |
| 79 | }); |
| 80 | |
| 81 | const scrollTo = vi |
| 82 | .spyOn(window, "scrollTo") |
| 83 | .mockImplementation((options?: ScrollToOptions | number) => { |
| 84 | if (typeof options === "object") { |
| 85 | if (options.left !== undefined) { |
| 86 | position.x = options.left; |
| 87 | } |
| 88 | if (options.top !== undefined) { |
| 89 | position.y = options.top; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | window.dispatchEvent(new Event("scroll")); |
| 94 | }); |
| 95 | |
| 96 | onTestFinished(() => { |
| 97 | for (const [name, descriptor] of Object.entries(originalDescriptors)) { |
| 98 | if (descriptor) { |
| 99 | Object.defineProperty(window, name, descriptor); |
| 100 | } else { |
| 101 | // @ts-expect-error Remove the override (jsdom defines the property on a prototype) |
| 102 | delete window[name]; |
| 103 | } |
| 104 | } |
| 105 | }); |
| 106 | |
| 107 | return { |
| 108 | position, |
| 109 | scrollTo, |
| 110 | viewport: { height, width } |
| 111 | }; |
| 112 | } |
no outgoing calls