|
| 1 | +import { describe, it, expect, vi, afterEach } from "vitest"; |
| 2 | +import { readFileSync } from "fs"; |
| 3 | +import { join } from "path"; |
| 4 | +import { formatRelativeDate } from "./relative-time"; |
| 5 | + |
| 6 | +describe("formatRelativeDate", () => { |
| 7 | + afterEach(() => { |
| 8 | + vi.useRealTimers(); |
| 9 | + }); |
| 10 | + |
| 11 | + it('returns "just now" for dates less than 1 minute ago', () => { |
| 12 | + vi.useFakeTimers(); |
| 13 | + vi.setSystemTime(new Date("2024-06-15T12:00:30Z")); |
| 14 | + expect(formatRelativeDate("2024-06-15T12:00:00Z")).toBe("just now"); |
| 15 | + }); |
| 16 | + |
| 17 | + it("returns minutes ago for dates less than 1 hour ago", () => { |
| 18 | + vi.useFakeTimers(); |
| 19 | + vi.setSystemTime(new Date("2024-06-15T12:47:00Z")); |
| 20 | + expect(formatRelativeDate("2024-06-15T12:00:00Z")).toBe("47m ago"); |
| 21 | + }); |
| 22 | + |
| 23 | + it("returns hours ago for dates less than 24 hours ago", () => { |
| 24 | + vi.useFakeTimers(); |
| 25 | + vi.setSystemTime(new Date("2024-06-15T15:00:00Z")); |
| 26 | + expect(formatRelativeDate("2024-06-15T12:00:00Z")).toBe("3h ago"); |
| 27 | + }); |
| 28 | + |
| 29 | + it("returns days ago for dates less than 7 days ago", () => { |
| 30 | + vi.useFakeTimers(); |
| 31 | + vi.setSystemTime(new Date("2024-06-18T12:00:00Z")); |
| 32 | + expect(formatRelativeDate("2024-06-15T12:00:00Z")).toBe("3d ago"); |
| 33 | + }); |
| 34 | + |
| 35 | + it("returns formatted date for dates 7+ days ago", () => { |
| 36 | + vi.useFakeTimers(); |
| 37 | + vi.setSystemTime(new Date("2024-06-25T12:00:00Z")); |
| 38 | + expect(formatRelativeDate("2024-06-15T12:00:00Z")).toBe("Jun 15"); |
| 39 | + }); |
| 40 | +}); |
| 41 | + |
| 42 | +describe("RelativeTime hydration safety", () => { |
| 43 | + it("uses suppressHydrationWarning to prevent hydration mismatch errors", () => { |
| 44 | + const source = readFileSync( |
| 45 | + join(__dirname, "relative-time.tsx"), |
| 46 | + "utf-8", |
| 47 | + ); |
| 48 | + |
| 49 | + // The component must use suppressHydrationWarning on the span element |
| 50 | + // so React ignores the text content difference between SSR and client. |
| 51 | + expect(source).toContain("suppressHydrationWarning"); |
| 52 | + }); |
| 53 | + |
| 54 | + it("uses useEffect with setInterval to keep the display current", () => { |
| 55 | + const source = readFileSync( |
| 56 | + join(__dirname, "relative-time.tsx"), |
| 57 | + "utf-8", |
| 58 | + ); |
| 59 | + |
| 60 | + expect(source).toMatch(/useEffect\(/); |
| 61 | + expect(source).toMatch(/setInterval\(/); |
| 62 | + }); |
| 63 | +}); |
0 commit comments