Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

5.9 KB
Raw Blame
// @vitest-environment jsdom
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";

// next-intl: return the key so we can assert on stable strings.
vi.mock("next-intl", () => ({
  useTranslations: () => (key: string) => key,
}));

const { default: AddApiKeyModal } =
  await import("../../../src/app/(dashboard)/dashboard/providers/[id]/components/modals/AddApiKeyModal");

const FREE_TOGGLE = 'button[role="switch"][aria-label="importFreeModelsOnlyLabel"]';

const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];

function render(props: Record<string, unknown>) {
  const el = document.createElement("div");
  document.body.appendChild(el);
  const root = createRoot(el);
  act(() => {
    root.render(
      <AddApiKeyModal
        isOpen
        onSave={async () => undefined}
        onClose={() => {}}
        {...(props as any)}
      />
    );
  });
  containers.push({ root, el });
  return el;
}

function setInputValue(input: HTMLInputElement, value: string) {
  const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!;
  act(() => {
    setter.call(input, value);
    input.dispatchEvent(new Event("input", { bubbles: true }));
  });
}

async function waitFor(fn: () => boolean, timeoutMs = 2000) {
  const start = Date.now();
  while (!fn()) {
    if (Date.now() - start > timeoutMs) throw new Error("waitFor timed out");
    await new Promise((r) => setTimeout(r, 20));
  }
}

beforeEach(() => {
  vi.clearAllMocks();
  vi.stubGlobal(
    "fetch",
    vi.fn(() =>
      Promise.resolve({ ok: true, json: () => Promise.resolve({ valid: true }) } as Response)
    )
  );
});

afterEach(() => {
  for (const { root, el } of containers.splice(0)) {
    act(() => root.unmount());
    el.remove();
  }
  vi.unstubAllGlobals();
});

describe("AddApiKeyModal — import only free models", () => {
  it("shows the free-only toggle for a provider that has free models", () => {
    const el = render({ provider: "openrouter", providerName: "OpenRouter" });
    expect(el.querySelector(FREE_TOGGLE)).toBeTruthy();
  });

  it("hides the free-only toggle for a provider without free models", () => {
    const el = render({ provider: "anthropic", providerName: "Anthropic" });
    expect(el.querySelector(FREE_TOGGLE)).toBeNull();
  });

  it("includes importFreeModelsOnly in the saved payload when toggled on", async () => {
    const onSave = vi.fn().mockResolvedValue(undefined);
    const el = render({ provider: "openrouter", providerName: "OpenRouter", onSave });

    const nameInput = el.querySelector<HTMLInputElement>('input[placeholder="productionKey"]')!;
    const apiKeyInput = el.querySelector<HTMLInputElement>('input[type="password"]')!;
    setInputValue(nameInput, "My OpenRouter");
    setInputValue(apiKeyInput, "sk-or-test-key");

    const toggle = el.querySelector<HTMLButtonElement>(FREE_TOGGLE)!;
    act(() => {
      toggle.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    const saveBtn = Array.from(el.querySelectorAll("button")).find(
      (b) => b.textContent?.trim() === "save"
    )!;
    act(() => {
      saveBtn.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    await waitFor(() => onSave.mock.calls.length > 0);
    const payload = onSave.mock.calls[0][0];
    expect(payload.providerSpecificData?.importFreeModelsOnly).toBe(true);
  });
});

describe("AddApiKeyModal — quota scraping fields", () => {
  it("renders only the API key for OpenCode Go and saves no scraping credentials", async () => {
    const onSave = vi.fn().mockResolvedValue(undefined);
    const el = render({ provider: "opencode-go", providerName: "OpenCode Go", onSave });

    expect(el.querySelector('input[name="opencodeGoWorkspaceId"]')).toBeNull();
    expect(el.querySelector('input[name="opencodeGoAuthCookie"]')).toBeNull();
    expect(el.querySelectorAll('input[type="password"]')).toHaveLength(1);

    const nameInput = el.querySelector<HTMLInputElement>('input[placeholder="productionKey"]')!;
    const apiKeyInput = el.querySelector<HTMLInputElement>('input[type="password"]')!;
    setInputValue(nameInput, "OpenCode Go");
    setInputValue(apiKeyInput, "sk-opencode-go-test");

    const saveBtn = Array.from(el.querySelectorAll("button")).find(
      (b) => b.textContent?.trim() === "save"
    )!;
    act(() => {
      saveBtn.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    await waitFor(() => onSave.mock.calls.length > 0);
    const payload = onSave.mock.calls[0][0];
    expect(payload.apiKey).toBe("sk-opencode-go-test");
    expect(payload.providerSpecificData ?? {}).not.toHaveProperty("opencodeGoWorkspaceId");
    expect(payload.providerSpecificData ?? {}).not.toHaveProperty("opencodeGoAuthCookie");
  });

  it("saves Ollama Cloud usage cookie in providerSpecificData", async () => {
    const onSave = vi.fn().mockResolvedValue(undefined);
    const el = render({ provider: "ollama-cloud", providerName: "Ollama Cloud", onSave });

    const nameInput = el.querySelector<HTMLInputElement>('input[placeholder="productionKey"]')!;
    const apiKeyInput = el.querySelector<HTMLInputElement>('input[type="password"]')!;
    const cookieInput = el.querySelector<HTMLInputElement>('input[name="ollamaCloudUsageCookie"]')!;
    setInputValue(nameInput, "Ollama Cloud");
    setInputValue(apiKeyInput, "ollama-key");
    setInputValue(cookieInput, "__Secure-session=ollama-cookie");

    const saveBtn = Array.from(el.querySelectorAll("button")).find(
      (b) => b.textContent?.trim() === "save"
    )!;
    act(() => {
      saveBtn.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    });

    await waitFor(() => onSave.mock.calls.length > 0);
    const payload = onSave.mock.calls[0][0];
    expect(payload.providerSpecificData?.ollamaCloudUsageCookie).toBe(
      "__Secure-session=ollama-cookie"
    );
  });
});