import { describe, it, expect, afterAll, beforeEach, vi, beforeAll } from "vitest"; import { createRoot, flush } from "solid-js"; import { createDateNow } from "../src/index.js"; beforeAll(() => { vi.useFakeTimers(); }); beforeEach(() => { vi.clearAllTimers(); }); afterAll(() => { vi.useRealTimers(); }); describe("createDateNow", () => { it("returns a signal and update function", () => { const test_now = Date.now(); const { dispose, now } = createRoot(dispose => { const [now] = createDateNow(100); return { dispose, now }; }); const time = now().getTime(); expect(time > test_now - 100 && time < test_now + 100, "the date should be 'now'").toBeTruthy(); dispose(); }); it("autoupdates", () => { const { now, dispose } = createRoot(dispose => { const [now] = createDateNow(100); return { now, dispose }; }); flush(); // run initial effect and set up interval const initial = now().getTime(); vi.advanceTimersByTime(150); flush(); // commit signal write from interval callback expect(now().getTime() > initial, "the newer timestamp should have bigger value").toBeTruthy(); dispose(); }); it("manual updating", () => { const { now, update, dispose } = createRoot(dispose => { const [now, update] = createDateNow(() => false); return { now, update, dispose }; }); flush(); const time = now().getTime(); vi.advanceTimersByTime(150); expect(time, "the time shouldn't update without calling update()").toBe(now().getTime()); update(); flush(); expect( now().getTime(), "the timestamp after update() should have bigger value", ).toBeGreaterThan(time); dispose(); }); it("stop autoupdating onCleanup", () => { const { now, dispose } = createRoot(dispose => { const [now] = createDateNow(100); return { now, dispose }; }); flush(); // set up interval const time = now().getTime(); dispose(); // cleanup clears the interval vi.advanceTimersByTime(150); expect(time, "the time shouldn't update after dispose").toBe(now().getTime()); }); });