|
| 1 | +/** |
| 2 | + * Fake-timer proof for `useLocalDayBoundaries`: verifies it schedules exactly |
| 3 | + * one `setTimeout` per local midnight, rebuilding boundaries and rescheduling |
| 4 | + * the next fire each time — never `setInterval` (which would drift across DST). |
| 5 | + * Uses `node:test`'s `mock.timers` to drive the wall clock deterministically. |
| 6 | + */ |
| 7 | + |
| 8 | +import assert from "node:assert/strict"; |
| 9 | +import test from "node:test"; |
| 10 | +import { mock } from "node:test"; |
| 11 | + |
| 12 | +function installDOMShim() { |
| 13 | + class EventTargetShim { |
| 14 | + constructor() { |
| 15 | + this.listeners = new Map(); |
| 16 | + } |
| 17 | + |
| 18 | + addEventListener(type, listener) { |
| 19 | + this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]); |
| 20 | + } |
| 21 | + |
| 22 | + removeEventListener(type, listener) { |
| 23 | + this.listeners.set( |
| 24 | + type, |
| 25 | + (this.listeners.get(type) ?? []).filter((l) => l !== listener), |
| 26 | + ); |
| 27 | + } |
| 28 | + |
| 29 | + dispatchEvent(event) { |
| 30 | + for (const listener of this.listeners.get(event.type) ?? []) |
| 31 | + listener(event); |
| 32 | + return true; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + class NodeShim extends EventTargetShim { |
| 37 | + constructor(tagName) { |
| 38 | + super(); |
| 39 | + this.tagName = tagName; |
| 40 | + this.nodeName = tagName.toUpperCase(); |
| 41 | + this.nodeType = 1; |
| 42 | + this.namespaceURI = "http://www.w3.org/1999/xhtml"; |
| 43 | + this.children = []; |
| 44 | + this.childNodes = []; |
| 45 | + this.style = {}; |
| 46 | + this.parentNode = null; |
| 47 | + } |
| 48 | + |
| 49 | + get ownerDocument() { |
| 50 | + return globalThis.document; |
| 51 | + } |
| 52 | + get firstChild() { |
| 53 | + return this.children[0] ?? null; |
| 54 | + } |
| 55 | + get lastChild() { |
| 56 | + return this.children.at(-1) ?? null; |
| 57 | + } |
| 58 | + get nextSibling() { |
| 59 | + return null; |
| 60 | + } |
| 61 | + get nodeValue() { |
| 62 | + return null; |
| 63 | + } |
| 64 | + |
| 65 | + appendChild(child) { |
| 66 | + this.children.push(child); |
| 67 | + this.childNodes.push(child); |
| 68 | + child.parentNode = this; |
| 69 | + return child; |
| 70 | + } |
| 71 | + |
| 72 | + removeChild(child) { |
| 73 | + this.children = this.children.filter((current) => current !== child); |
| 74 | + this.childNodes = this.childNodes.filter((current) => current !== child); |
| 75 | + child.parentNode = null; |
| 76 | + return child; |
| 77 | + } |
| 78 | + |
| 79 | + insertBefore(child, reference) { |
| 80 | + if (!reference) return this.appendChild(child); |
| 81 | + const index = this.children.indexOf(reference); |
| 82 | + if (index < 0) return this.appendChild(child); |
| 83 | + this.children.splice(index, 0, child); |
| 84 | + this.childNodes.splice(index, 0, child); |
| 85 | + child.parentNode = this; |
| 86 | + return child; |
| 87 | + } |
| 88 | + |
| 89 | + contains(node) { |
| 90 | + return ( |
| 91 | + this === node || this.children.some((child) => child.contains(node)) |
| 92 | + ); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + class DocumentShim extends EventTargetShim { |
| 97 | + constructor() { |
| 98 | + super(); |
| 99 | + this.nodeType = 9; |
| 100 | + this.defaultView = globalThis; |
| 101 | + } |
| 102 | + |
| 103 | + createElement(tagName) { |
| 104 | + return new NodeShim(tagName); |
| 105 | + } |
| 106 | + |
| 107 | + createTextNode(value) { |
| 108 | + const node = new NodeShim("#text"); |
| 109 | + node.nodeType = 3; |
| 110 | + node.nodeValue = value; |
| 111 | + return node; |
| 112 | + } |
| 113 | + |
| 114 | + createComment(value) { |
| 115 | + const node = new NodeShim("#comment"); |
| 116 | + node.nodeType = 8; |
| 117 | + node.nodeValue = value; |
| 118 | + return node; |
| 119 | + } |
| 120 | + |
| 121 | + get activeElement() { |
| 122 | + return null; |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + globalThis.document = new DocumentShim(); |
| 127 | + globalThis.HTMLIFrameElement = NodeShim; |
| 128 | + globalThis.HTMLElement = NodeShim; |
| 129 | + globalThis.IS_REACT_ACT_ENVIRONMENT = true; |
| 130 | + process.env.IS_REACT_ACT_ENVIRONMENT = "true"; |
| 131 | + Object.defineProperty(globalThis, "window", { |
| 132 | + configurable: true, |
| 133 | + value: globalThis, |
| 134 | + }); |
| 135 | + // React's scheduler uses MessageChannel (native in Node) as a fallback, so |
| 136 | + // mocking setTimeout/Date cannot stall commits — rAF just needs to exist. |
| 137 | + globalThis.requestAnimationFrame = (callback) => setTimeout(callback, 0); |
| 138 | + globalThis.cancelAnimationFrame = (id) => clearTimeout(id); |
| 139 | + globalThis.CSS = { escape: (value) => value }; |
| 140 | +} |
| 141 | + |
| 142 | +installDOMShim(); |
| 143 | + |
| 144 | +import React from "react"; |
| 145 | +import { act } from "react"; |
| 146 | +import { createRoot } from "react-dom/client"; |
| 147 | + |
| 148 | +import { useLocalDayBoundaries } from "./hooks.ts"; |
| 149 | + |
| 150 | +function Harness({ onBoundaries, range }) { |
| 151 | + const boundaries = useLocalDayBoundaries(range); |
| 152 | + onBoundaries(boundaries); |
| 153 | + return null; |
| 154 | +} |
| 155 | + |
| 156 | +const SEVEN_DAY_RANGE = { kind: "preset", days: 7 }; |
| 157 | + |
| 158 | +/** Local midnight as unix seconds, the unit the hook emits. */ |
| 159 | +function midnight(year, monthIndex, day) { |
| 160 | + return Math.floor( |
| 161 | + new Date(year, monthIndex, day, 0, 0, 0, 0).getTime() / 1_000, |
| 162 | + ); |
| 163 | +} |
| 164 | + |
| 165 | +/** |
| 166 | + * Mounts the hook with `initialRange` and calls `run` with a live view: |
| 167 | + * `boundaries` = newest emission, `renders` = emission count, |
| 168 | + * `render(range)` re-renders, `tick(ms)` advances the mocked clock. |
| 169 | + */ |
| 170 | +async function withMountedHook(initialRange, run) { |
| 171 | + const emissions = []; |
| 172 | + const root = createRoot(document.createElement("div")); |
| 173 | + const render = async (range) => { |
| 174 | + await act(async () => { |
| 175 | + root.render( |
| 176 | + React.createElement(Harness, { |
| 177 | + onBoundaries: (boundaries) => emissions.push(boundaries), |
| 178 | + range, |
| 179 | + }), |
| 180 | + ); |
| 181 | + }); |
| 182 | + }; |
| 183 | + |
| 184 | + try { |
| 185 | + await render(initialRange); |
| 186 | + await run({ |
| 187 | + emissions, |
| 188 | + get boundaries() { |
| 189 | + return emissions.at(-1); |
| 190 | + }, |
| 191 | + get renders() { |
| 192 | + return emissions.length; |
| 193 | + }, |
| 194 | + render, |
| 195 | + unmount: async () => { |
| 196 | + await act(async () => { |
| 197 | + root.unmount(); |
| 198 | + }); |
| 199 | + }, |
| 200 | + /** Advance the mocked wall clock, flushing any React work it triggers. */ |
| 201 | + tick: async (ms) => { |
| 202 | + await act(async () => { |
| 203 | + mock.timers.tick(ms); |
| 204 | + }); |
| 205 | + }, |
| 206 | + }); |
| 207 | + } finally { |
| 208 | + await act(async () => { |
| 209 | + root.unmount(); |
| 210 | + }); |
| 211 | + } |
| 212 | +} |
| 213 | + |
| 214 | +/** Runs `fn` with the wall clock frozen one minute before a local midnight. */ |
| 215 | +async function atOneMinuteToMidnight(fn) { |
| 216 | + mock.timers.enable({ |
| 217 | + apis: ["setTimeout", "Date"], |
| 218 | + now: new Date(2026, 5, 15, 23, 59, 0).getTime(), |
| 219 | + }); |
| 220 | + try { |
| 221 | + await fn(); |
| 222 | + } finally { |
| 223 | + mock.timers.reset(); |
| 224 | + } |
| 225 | +} |
| 226 | + |
| 227 | +test("useLocalDayBoundaries reschedules across two local-midnight rollovers, rebuilding boundaries each time", async () => { |
| 228 | + await atOneMinuteToMidnight(async () => { |
| 229 | + await withMountedHook(SEVEN_DAY_RANGE, async (hook) => { |
| 230 | + assert.equal( |
| 231 | + hook.boundaries.length, |
| 232 | + 8, |
| 233 | + "7-day window yields 8 boundaries", |
| 234 | + ); |
| 235 | + const initial = hook.boundaries; |
| 236 | + |
| 237 | + // Crosses the Jun 16 local midnight. The single scheduled `setTimeout` |
| 238 | + // must fire, bump `rolloverTick`, and rebuild the boundary set. |
| 239 | + await hook.tick(60_000); |
| 240 | + |
| 241 | + assert.notDeepEqual( |
| 242 | + hook.boundaries, |
| 243 | + initial, |
| 244 | + "boundaries must rebuild after the first midnight rollover fires", |
| 245 | + ); |
| 246 | + assert.equal( |
| 247 | + hook.boundaries.length, |
| 248 | + 8, |
| 249 | + "boundary count is unchanged by a rollover", |
| 250 | + ); |
| 251 | + assert.equal( |
| 252 | + hook.boundaries.at(-1), |
| 253 | + midnight(2026, 5, 17), |
| 254 | + "newest boundary must shift forward to tomorrow of the new window", |
| 255 | + ); |
| 256 | + const afterFirst = hook.boundaries; |
| 257 | + |
| 258 | + // Crossing the Jun 17 local midnight only fires if the first rollover's |
| 259 | + // effect RESCHEDULED a fresh `setTimeout` rather than going silent. |
| 260 | + await hook.tick(24 * 60 * 60 * 1_000); |
| 261 | + |
| 262 | + assert.notDeepEqual( |
| 263 | + hook.boundaries, |
| 264 | + afterFirst, |
| 265 | + "boundaries must rebuild again after the second rollover, proving the timer rescheduled itself", |
| 266 | + ); |
| 267 | + assert.equal( |
| 268 | + hook.boundaries.at(-1), |
| 269 | + midnight(2026, 5, 18), |
| 270 | + "newest boundary must shift forward again after the rescheduled rollover", |
| 271 | + ); |
| 272 | + }); |
| 273 | + }); |
| 274 | +}); |
| 275 | + |
| 276 | +test("useLocalDayBoundaries clears its scheduled timeout on unmount (no post-unmount rollover)", async () => { |
| 277 | + await atOneMinuteToMidnight(async () => { |
| 278 | + await withMountedHook(SEVEN_DAY_RANGE, async (hook) => { |
| 279 | + const rendersAtUnmount = hook.renders; |
| 280 | + await hook.unmount(); |
| 281 | + |
| 282 | + // Crossing the midnight the pending timeout targeted must not throw or |
| 283 | + // invoke a setState-after-unmount path — `clearTimeout` in the effect's |
| 284 | + // cleanup must have already cancelled it. |
| 285 | + await hook.tick(60_000); |
| 286 | + |
| 287 | + assert.equal( |
| 288 | + hook.renders, |
| 289 | + rendersAtUnmount, |
| 290 | + "no render (and no error) after the component unmounted", |
| 291 | + ); |
| 292 | + }); |
| 293 | + }); |
| 294 | +}); |
| 295 | + |
| 296 | +test("useLocalDayBoundaries returns the same boundary array when re-rendered with an equal range literal", async () => { |
| 297 | + await withMountedHook({ kind: "preset", days: 7 }, async (hook) => { |
| 298 | + // A fresh object literal each render — the memo must key on the range's |
| 299 | + // fields, not its identity, or every render would refetch. |
| 300 | + await hook.render({ kind: "preset", days: 7 }); |
| 301 | + |
| 302 | + assert.ok(hook.renders >= 2, "component rendered at least twice"); |
| 303 | + assert.equal( |
| 304 | + hook.boundaries, |
| 305 | + hook.emissions[0], |
| 306 | + "an equal range literal must reuse the memoized boundary array", |
| 307 | + ); |
| 308 | + }); |
| 309 | +}); |
| 310 | + |
| 311 | +test("useLocalDayBoundaries rebuilds when the range changes to a custom range", async () => { |
| 312 | + await withMountedHook(SEVEN_DAY_RANGE, async (hook) => { |
| 313 | + assert.equal(hook.boundaries.length, 8); |
| 314 | + |
| 315 | + await hook.render({ |
| 316 | + kind: "custom", |
| 317 | + startDate: "2026-01-01", |
| 318 | + endDate: "2026-01-03", |
| 319 | + }); |
| 320 | + |
| 321 | + assert.equal( |
| 322 | + hook.boundaries.length, |
| 323 | + 4, |
| 324 | + "a 3-day custom range yields 4 boundaries closing the final day", |
| 325 | + ); |
| 326 | + assert.equal( |
| 327 | + hook.boundaries[0], |
| 328 | + midnight(2026, 0, 1), |
| 329 | + "first boundary opens the requested start date in local time", |
| 330 | + ); |
| 331 | + }); |
| 332 | +}); |
| 333 | + |
| 334 | +test("useLocalDayBoundaries returns no boundaries for an invalid custom range", async () => { |
| 335 | + // Inverted range — `useAgentUsageSeries` gates its query on |
| 336 | + // `boundaries.length >= 2`, so this must issue no request rather than one |
| 337 | + // the backend would reject. |
| 338 | + const invertedRange = { |
| 339 | + kind: "custom", |
| 340 | + startDate: "2026-03-10", |
| 341 | + endDate: "2026-03-01", |
| 342 | + }; |
| 343 | + await withMountedHook(invertedRange, async (hook) => { |
| 344 | + assert.deepEqual(hook.boundaries, []); |
| 345 | + }); |
| 346 | +}); |
0 commit comments