PairDevice.test.tsx

6.4 KB · raw

1// @vitest-environment jsdom2//3// PairDeviceView is relay-only: the extension always DISPLAYS an invitation for4// another device to scan. LAN pairing codes went with LAN sync5// (docs/sync-lan-retirement.md), so there is no code-entry mode to test.6//7// chrome messaging is mocked the way the popup uses it:8//   - shared/bridge `sendMessage` is mocked (popup → bg)9//   - chrome.runtime.onMessage.{add,remove}Listener is faked so the test can10//     fire ADOPTION_SOURCE_* pushes (bg → popup)1112import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";1314// --- mock the background bridge (popup → bg) -------------------------------15const { mockSendMessage } = vi.hoisted(() => ({ mockSendMessage: vi.fn() }));16vi.mock("../../shared/bridge", () => ({ sendMessage: mockSendMessage }));1718const SOURCE_INVITATION =19  "peach-pair-v1:eyJyZWxheSI6IndzczovL3JlbGF5LnBlYWNocGFzc3dvcmRzLmNvbSIsInRva2VuIjoiQUFFQ0F3UUZCZ2NJQ1FvTERBME9EdyJ9";2021import { PairDeviceView } from "./PairDevice";22import { renderView, inputText } from "./view-test-utils";2324// --- fake chrome.runtime push channel (bg → popup) ------------------------25type RuntimeListener = (msg: { type?: string; payload?: unknown }) => void;26let listeners: RuntimeListener[] = [];2728function pushFromBackground(type: string, payload: unknown): void {29  for (const l of [...listeners]) l({ type, payload });30}3132beforeEach(() => {33  listeners = [];34  mockSendMessage.mockReset();35  mockSendMessage.mockImplementation((msg: { type?: string }) => {36    if (msg?.type === "START_ADOPTION_SOURCE") {37      return Promise.resolve({38        ok: true,39        data: { invitation: SOURCE_INVITATION },40      });41    }42    if (msg?.type === "ADOPTION_SOURCE_CONFIRM") {43      return Promise.resolve({ ok: true, data: { valid: true } });44    }45    if (msg?.type === "GET_SYNC_SETTINGS" || msg?.type === "SET_SYNC_SETTINGS") {46      return Promise.resolve({47        ok: true,48        data: { mode: "public", relayUrl: "wss://relay.peachpasswords.com" },49      });50    }51    return Promise.resolve({ ok: true });52  });53  (globalThis as unknown as { chrome: unknown }).chrome = {54    runtime: {55      onMessage: {56        addListener: (fn: RuntimeListener) => { listeners.push(fn); },57        removeListener: (fn: RuntimeListener) => { listeners = listeners.filter((l) => l !== fn); },58      },59    },60  };61});6263describe("PairDevice — relay adoption source", () => {64  const cleanups: Array<() => void> = [];65  afterEach(() => {66    while (cleanups.length) cleanups.pop()!();67  });6869  function mount() {70    const rendered = renderView(71      <PairDeviceView72        isPro={true}73        onBack={() => {}}74        onLearnPro={() => {}}75      />,76    );77    cleanups.push(rendered.dispose);78    return rendered;79  }8081  it("opens the relay room before rendering its QR, and offers no manual copy", async () => {82    const { container } = mount();83    await vi.waitFor(() => {84      expect(container.textContent).toContain("Scan this in Peach");85    });8687    expect(mockSendMessage).toHaveBeenCalledWith({88      type: "START_ADOPTION_SOURCE",89    });90    expect(container.querySelector("svg.peach-pair-qr")).toBeTruthy();91    // The invitation is carried by the QR alone — the manual textarea and its92    // Copy button duplicated the pairing-code path and were removed.93    expect(container.querySelector("#pairing-invitation-manual")).toBeNull();94    expect(container.textContent).not.toContain("or copy the invitation");95    expect(container.textContent).toContain("single-use token");96  });9798  // Moment 1 (docs/sync-relay-surfacing.md): present, but never a step.99  it("names the relay in force without making it a decision", async () => {100    const { container } = mount();101    await vi.waitFor(() => {102      expect(container.textContent).toContain("Scan this in Peach");103    });104105    const summary = container.querySelector(".peach-sync-mode-summary");106    expect(summary?.textContent).toContain("Using Public relay");107    // Quiet means quiet: no selector on screen until asked for.108    expect(container.querySelector(".peach-sync-mode")).toBeNull();109110    container.querySelector<HTMLButtonElement>(".peach-sync-mode-change")!.click();111    await vi.waitFor(() => {112      expect(container.querySelectorAll(".peach-sync-mode")).toHaveLength(3);113    });114    // The expanded selector is taller than the popup, so the QR folds away.115    expect(container.querySelector("svg.peach-pair-qr")).toBeNull();116  });117118  it("rebuilds the invitation when the relay changes, since the code carries it", async () => {119    const { container } = mount();120    await vi.waitFor(() => {121      expect(container.textContent).toContain("Scan this in Peach");122    });123    const opened = () =>124      mockSendMessage.mock.calls.filter(125        ([m]) => (m as { type?: string })?.type === "START_ADOPTION_SOURCE",126      ).length;127    expect(opened()).toBe(1);128129    container.querySelector<HTMLButtonElement>(".peach-sync-mode-change")!.click();130    await vi.waitFor(() => {131      expect(container.querySelectorAll(".peach-sync-mode")).toHaveLength(3);132    });133    const noSync = [...container.querySelectorAll<HTMLButtonElement>("button.peach-sync-mode")].find(134      (b) => b.textContent?.includes("No sync"),135    )!;136    noSync.click();137138    await vi.waitFor(() => {139      expect(mockSendMessage).toHaveBeenCalledWith({ type: "CANCEL_ADOPTION_SOURCE" });140      expect(opened()).toBe(2);141    });142  });143144  it("requires the matching SAS and master password before sharing", async () => {145    const { container } = mount();146    await vi.waitFor(() => {147      expect(container.textContent).toContain("Scan this in Peach");148    });149150    pushFromBackground("ADOPTION_SOURCE_SAS", {151      sas: "48219371",152      receiverDeviceName: "June's phone",153    });154    expect(container.textContent).toContain("June's phone");155    expect(container.textContent).toContain("48219371");156157    inputText(158      container.querySelector("#adoption-consent-password") as HTMLInputElement,159      "correct horse battery staple",160    );161    const approve = Array.from(container.querySelectorAll("button")).find(162      (button) => button.textContent?.includes("Share vault"),163    ) as HTMLButtonElement;164    approve.click();165    await vi.waitFor(() => {166      expect(mockSendMessage).toHaveBeenCalledWith({167        type: "ADOPTION_SOURCE_CONFIRM",168        payload: { password: "correct horse battery staple" },169      });170    });171    await vi.waitFor(() => {172      expect(container.textContent).toContain("Waiting for the new device");173    });174  });175});