Health.test.tsx

9.4 KB · raw

1// @vitest-environment jsdom23import { afterEach, describe, expect, it, vi } from "vitest";45import { flushView, renderView } from "./view-test-utils";6import type { AdvancedHealthReport, VaultEntry } from "../../shared/types";78const sendMessageMock = vi.fn<(msg: unknown) => Promise<unknown>>();910vi.mock("../App", () => ({11  sendMessage: (msg: unknown) => sendMessageMock(msg),12}));1314function entry(overrides: Partial<VaultEntry> = {}): VaultEntry {15  return {16    id: "entry-1",17    type: "login",18    title: "Example",19    username: "[email protected]",20    password: "correct-horse-battery-staple",21    url: "https://example.com/login",22    createdAt: Date.now() - 10_000,23    modifiedAt: Date.now() - 10_000,24    ...overrides,25  };26}2728describe("HealthView", () => {29  let dispose: (() => void) | undefined;3031  afterEach(() => {32    dispose?.();33    dispose = undefined;34    sendMessageMock.mockReset();35    document.body.innerHTML = "";36    vi.useRealTimers();37  });3839  it("opens the local entry editor from the Pro remediation queue", async () => {40    const report: AdvancedHealthReport = {41      vaultScore: 65,42      generatedAt: Date.now(),43      entryCount: 1,44      reusedGroups: 0,45      agedCount: 1,46      remediation: [47        {48          id: "entry-1",49          title: "Example",50          domain: "example.com",51          url: "https://example.com/login",52          score: 65,53          ageDays: 200,54          reasons: ["200 days old"],55          factors: {56            breached: false,57            breachCount: 0,58            reused: false,59            aged: true,60            weak: false,61            missingTotpOnSensitive: false,62          },63        },64      ],65    };66    sendMessageMock.mockResolvedValue({ ok: true, data: report });67    const onFixEntry = vi.fn();6869    const { HealthView } = await import("./Health");70    const mounted = renderView(71      <HealthView72        entries={[entry()]}73        isPro={true}74        onFixEntry={onFixEntry}75        onBack={vi.fn()}76        onRefresh={vi.fn()}77      />,78    );79    dispose = mounted.dispose;8081    await flushView();82    await flushView();8384    expect(mounted.container.textContent).toContain("Remediation queue");85    expect(mounted.container.textContent).toContain("Example");86    expect(mounted.container.textContent).not.toContain("Change password");8788    const button = mounted.container.querySelector<HTMLButtonElement>(".peach-health-pro-row button");89    expect(button?.textContent).toContain("Update");90    button?.click();91    expect(onFixEntry).toHaveBeenCalledWith(expect.objectContaining({ id: "entry-1" }));92  });93  it("reconnects to a running scan and reports partial results without claiming clean", async () => {94    vi.useFakeTimers();95    const running = { id: "scan", state: "running", total: 3, scanned: 1, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 };96    sendMessageMock.mockResolvedValueOnce({ ok: true, data: running }).mockResolvedValue({ ok: true, data: { ...running, state: "complete", unknown: 1, unapplied: 1 } });97    const refresh = vi.fn();98    const { HealthView } = await import("./Health");99    const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={refresh} />);100    dispose = mounted.dispose;101    await vi.advanceTimersByTimeAsync(0);102    expect(mounted.container.textContent).toContain("1 of 3 checked");103    expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(true);104    await vi.advanceTimersByTimeAsync(1000);105    expect(mounted.container.textContent).toContain("1 unavailable");106    expect(mounted.container.textContent).toContain("1 changed or superseded");107    expect(mounted.container.textContent).not.toContain("All passwords clean");108    expect(refresh).toHaveBeenCalled();109    const calls = sendMessageMock.mock.calls.length;110    mounted.dispose(); dispose = undefined;111    await vi.advanceTimersByTimeAsync(5000);112    expect(sendMessageMock.mock.calls.length).toBe(calls);113  });114115  it.each(["empty", "unknown", "cancelled", "error"])("does not claim clean for %s scans", async (kind) => {116    const status = { id: "scan", state: kind === "cancelled" ? "cancelled" : "complete", total: kind === "empty" ? 0 : 1, scanned: 0, breached: 0, unknown: kind === "unknown" ? 1 : 0, unapplied: 0, cancelled: kind === "cancelled" ? 1 : 0 };117    sendMessageMock.mockResolvedValue(kind === "error" ? { ok: false, error: "offline" } : { ok: true, data: status });118    const { HealthView } = await import("./Health");119    const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);120    dispose = mounted.dispose;121    await flushView();122    expect(mounted.container.textContent).toContain(kind === "empty" ? "No passwords to check" : kind === "unknown" ? "1 unavailable" : kind === "cancelled" ? "Scan cancelled" : "Could not read breach scan status");123    expect(mounted.container.textContent).not.toContain("All passwords clean");124  });125126  it.each(["failure", "idle"])("ends polling truthfully after worker %s", async (kind) => {127    vi.useFakeTimers();128    const running = { id: "scan", state: "running", total: 1, scanned: 0, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 };129    sendMessageMock.mockResolvedValueOnce({ ok: true, data: running }).mockResolvedValue(kind === "failure" ? { ok: false } : { ok: true, data: { ...running, id: null, state: "idle", total: 0 } });130    const { HealthView } = await import("./Health");131    const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);132    dispose = mounted.dispose;133    await vi.advanceTimersByTimeAsync(1000);134    expect(mounted.container.textContent).toContain(kind === "failure" ? "Could not read breach scan status" : "Breach scan interrupted");135    expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(false);136    const calls = sendMessageMock.mock.calls.length;137    await vi.advanceTimersByTimeAsync(5000);138    expect(sendMessageMock.mock.calls.length).toBe(calls);139  });140141  it.each([0, 2])("reports a fully checked scan with %s breached passwords", async (breached) => {142    sendMessageMock.mockResolvedValue({ ok: true, data: { id: "scan", state: "complete", total: 2, scanned: 2, breached, unknown: 0, unapplied: 0, cancelled: 0 } });143    const { HealthView } = await import("./Health");144    const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);145    dispose = mounted.dispose;146    await flushView();147    expect(mounted.container.textContent).toContain(breached ? "2 found in breaches" : "No breaches found in 2 checked passwords");148  });149150  it.each([151    { scanned: 2, total: 1 }, { breached: 1, scanned: 0 }, { unknown: -1 }, { unknown: 0.5 }, { unapplied: 2 },152  ])("rejects inconsistent scan counters %j", async (override) => {153    sendMessageMock.mockResolvedValue({ ok: true, data: { id: "scan", state: "complete", total: 1, scanned: 0, breached: 0, unknown: 1, unapplied: 0, cancelled: 0, ...override } });154    const { HealthView } = await import("./Health");155    const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);156    dispose = mounted.dispose;157    await flushView();158    expect(mounted.container.textContent).toContain("Could not read breach scan status");159    expect(mounted.container.textContent).not.toContain("No breaches found");160  });161162  it("ignores a stale mount response after a scan start and responses after disposal", async () => {163    let mountResolve!: (value: unknown) => void;164    let startResolve!: (value: unknown) => void;165    sendMessageMock.mockReturnValueOnce(new Promise((resolve) => { mountResolve = resolve; }))166      .mockReturnValueOnce(new Promise((resolve) => { startResolve = resolve; }));167    const refresh = vi.fn();168    const { HealthView } = await import("./Health");169    const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={refresh} />);170    dispose = mounted.dispose;171    await flushView();172    mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")!.click();173    await flushView();174    const complete = { id: "old", state: "complete", total: 1, scanned: 1, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 };175    mountResolve({ ok: true, data: complete });176    await flushView();177    expect(mounted.container.textContent).not.toContain("No breaches found");178    expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(true);179    mounted.dispose(); dispose = undefined;180    startResolve({ ok: true, data: complete });181    await flushView();182    expect(refresh).not.toHaveBeenCalled();183  });184185  it("allows retry after a failed scan start", async () => {186    sendMessageMock.mockResolvedValueOnce({ ok: true, data: { id: null, state: "idle", total: 0, scanned: 0, breached: 0, unknown: 0, unapplied: 0, cancelled: 0 } }).mockResolvedValue({ ok: false });187    const { HealthView } = await import("./Health");188    const mounted = renderView(<HealthView entries={[]} onFixEntry={vi.fn()} onBack={vi.fn()} onRefresh={vi.fn()} />);189    dispose = mounted.dispose;190    await flushView();191    mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")!.click();192    await flushView();193    expect(mounted.container.textContent).toContain("Could not start breach scan");194    expect(mounted.container.querySelector<HTMLButtonElement>(".peach-health-check-btn")?.disabled).toBe(false);195  });196197});