Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

3.7 KB
Raw Blame
import { createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { act } from "react";
import { Window } from "happy-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { useSharedClock } from "./shared-clock";

let win: Window;
let root: Root;

function setVisibility(state: "visible" | "hidden") {
  Object.defineProperty(document, "visibilityState", { value: state, configurable: true });
  document.dispatchEvent(new Event("visibilitychange"));
}

beforeEach(() => {
  vi.useFakeTimers();
  vi.setSystemTime(new Date("2026-06-01T12:00:00.000Z"));
  win = new Window();
  vi.stubGlobal("window", win);
  vi.stubGlobal("document", win.document);
  vi.stubGlobal("Event", win.Event);
  vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
  setVisibility("visible");
  const host = win.document.createElement("div");
  win.document.body.appendChild(host);
  root = createRoot(host as unknown as Element);
});

afterEach(() => {
  act(() => root.unmount());
  vi.useRealTimers();
  vi.unstubAllGlobals();
  win.close();
});

function ClockReader({ id, intervalMs, enabled = true }: { id: string; intervalMs: number; enabled?: boolean }) {
  const now = useSharedClock(intervalMs, enabled);
  return createElement("span", { "data-clock": id }, String(now));
}

describe("useSharedClock", () => {
  it("coalesces subscribers at the same interval onto one timer and cleans up when the last unmounts", () => {
    const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
    const clearIntervalSpy = vi.spyOn(globalThis, "clearInterval");

    act(() => {
      root.render(
        createElement("div", null,
          createElement(ClockReader, { id: "a", intervalMs: 15_000 }),
          createElement(ClockReader, { id: "b", intervalMs: 15_000 }),
          createElement(ClockReader, { id: "c", intervalMs: 15_000 }),
        ),
      );
    });

    expect(setIntervalSpy).toHaveBeenCalledTimes(1);
    const initial = Date.now();
    expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(String(initial));

    act(() => {
      vi.advanceTimersByTime(15_000);
    });
    const afterTick = String(initial + 15_000);
    expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(afterTick);
    expect(document.querySelector('[data-clock="b"]')?.textContent).toBe(afterTick);
    expect(document.querySelector('[data-clock="c"]')?.textContent).toBe(afterTick);

    // Unmounting two of three keeps the shared timer alive.
    act(() => {
      root.render(createElement("div", null, createElement(ClockReader, { id: "a", intervalMs: 15_000 })));
    });
    expect(clearIntervalSpy).not.toHaveBeenCalled();

    // Unmounting the last tears down the shared timer.
    act(() => {
      root.render(createElement("div", null));
    });
    expect(clearIntervalSpy).toHaveBeenCalledTimes(1);
  });

  it("pauses updates while hidden and syncs immediately when visible again", () => {
    act(() => {
      root.render(createElement(ClockReader, { id: "a", intervalMs: 30_000 }));
    });
    const initial = Date.now();

    act(() => {
      setVisibility("hidden");
      vi.advanceTimersByTime(90_000);
    });
    expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(String(initial));

    act(() => {
      setVisibility("visible");
    });
    expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(String(initial + 90_000));
  });

  it("does not register a timer when disabled", () => {
    const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
    act(() => {
      root.render(createElement(ClockReader, { id: "a", intervalMs: 15_000, enabled: false }));
    });
    expect(setIntervalSpy).not.toHaveBeenCalled();
  });
});