|
| 1 | +import assert from "node:assert/strict"; |
| 2 | +import { test } from "node:test"; |
| 3 | + |
| 4 | +import { isStale } from "./useDashboardData"; |
| 5 | + |
| 6 | +// Mirrors STALE_THRESHOLD_MS in useDashboardData.ts (5 minutes). Kept as a |
| 7 | +// local constant rather than imported so these tests pin the *contract* |
| 8 | +// (fresh below the threshold, stale above it) without depending on that |
| 9 | +// value being exported. |
| 10 | +const STALE_THRESHOLD_MS = 5 * 60 * 1000; |
| 11 | +const NOW_MS = Date.parse("2026-06-15T12:00:00.000Z"); |
| 12 | + |
| 13 | +test("invalid or missing timestamps are treated as stale", () => { |
| 14 | + assert.equal(isStale("not-a-date", NOW_MS), true, "unparseable string"); |
| 15 | + assert.equal(isStale("", NOW_MS), true, "empty string"); |
| 16 | + assert.equal(isStale("abcdef", NOW_MS), true, "garbage string"); |
| 17 | + assert.equal(isStale("2026-13-45T00:00:00Z", NOW_MS), true, "invalid calendar date"); |
| 18 | + assert.equal(isStale(null, NOW_MS), true, "null"); |
| 19 | + assert.equal(isStale(undefined, NOW_MS), true, "undefined"); |
| 20 | +}); |
| 21 | + |
| 22 | +test("valid fresh timestamps are not stale", () => { |
| 23 | + const fetchedAt = new Date(NOW_MS - 30_000).toISOString(); // 30s ago |
| 24 | + assert.equal(isStale(fetchedAt, NOW_MS), false); |
| 25 | +}); |
| 26 | + |
| 27 | +test("valid old timestamps beyond the threshold are stale", () => { |
| 28 | + const fetchedAt = new Date(NOW_MS - STALE_THRESHOLD_MS - 60_000).toISOString(); // 6 min ago |
| 29 | + assert.equal(isStale(fetchedAt, NOW_MS), true); |
| 30 | +}); |
| 31 | + |
| 32 | +test("a timestamp equal to now is fresh", () => { |
| 33 | + const fetchedAt = new Date(NOW_MS).toISOString(); |
| 34 | + assert.equal(isStale(fetchedAt, NOW_MS), false); |
| 35 | +}); |
| 36 | + |
| 37 | +test("a future timestamp is fresh (unchanged pre-existing behavior)", () => { |
| 38 | + const fetchedAt = new Date(NOW_MS + 60_000).toISOString(); // 1 min in the future |
| 39 | + assert.equal(isStale(fetchedAt, NOW_MS), false); |
| 40 | +}); |
| 41 | + |
| 42 | +test("boundary: exactly at the stale threshold is still fresh (strict greater-than)", () => { |
| 43 | + const fetchedAt = new Date(NOW_MS - STALE_THRESHOLD_MS).toISOString(); |
| 44 | + assert.equal(isStale(fetchedAt, NOW_MS), false); |
| 45 | +}); |
| 46 | + |
| 47 | +test("boundary: one millisecond past the stale threshold is stale", () => { |
| 48 | + const fetchedAt = new Date(NOW_MS - STALE_THRESHOLD_MS - 1).toISOString(); |
| 49 | + assert.equal(isStale(fetchedAt, NOW_MS), true); |
| 50 | +}); |
| 51 | + |
| 52 | +test("boundary: one millisecond inside the stale threshold is fresh", () => { |
| 53 | + const fetchedAt = new Date(NOW_MS - STALE_THRESHOLD_MS + 1).toISOString(); |
| 54 | + assert.equal(isStale(fetchedAt, NOW_MS), false); |
| 55 | +}); |
0 commit comments