Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

Add unit tests for openrouter

Khuram Niaz15311802921b
diff --git a/__tests__/openrouter-models-route.spec.ts b/__tests__/openrouter-models-route.spec.ts
new file mode 100644
index 0000000..2c8aec1
--- /dev/null
+++ b/__tests__/openrouter-models-route.spec.ts
@@ -0,0 +1,120 @@
+jest.mock("@/auth", () => ({
+ auth: jest.fn(),
+}));
+
+jest.mock("@/lib/api-key-resolver", () => ({
+ resolveApiKey: jest.fn(),
+}));
+
+// NextResponse.json uses Response.json() internally; provide a working implementation
+jest.mock("next/server", () => ({
+ NextResponse: {
+ json: (data: unknown, init?: { status?: number }) => ({
+ status: init?.status ?? 200,
+ json: async () => data,
+ }),
+ },
+}));
+
+import { GET } from "@/app/api/ai/openrouter/models/route";
+import { auth } from "@/auth";
+import { resolveApiKey } from "@/lib/api-key-resolver";
+
+describe("GET /api/ai/openrouter/models", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it("returns 401 when no API key is configured", async () => {
+ (auth as jest.Mock).mockResolvedValue({ user: { id: "user-1" } });
+ (resolveApiKey as jest.Mock).mockResolvedValue(null);
+
+ const response = await GET();
+ const data = await response.json();
+
+ expect(response.status).toBe(401);
+ expect(data.error).toContain("OpenRouter API key not configured");
+ });
+
+ it("returns model data on successful fetch", async () => {
+ (auth as jest.Mock).mockResolvedValue({ user: { id: "user-1" } });
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-valid");
+
+ const mockModels = {
+ data: [{ id: "openai/gpt-4o" }, { id: "google/gemini-flash" }],
+ };
+ global.fetch = jest.fn().mockResolvedValue({
+ ok: true,
+ json: async () => mockModels,
+ });
+
+ const response = await GET();
+ const data = await response.json();
+
+ expect(response.status).toBe(200);
+ expect(data).toEqual(mockModels);
+ expect(global.fetch).toHaveBeenCalledWith(
+ "https://openrouter.ai/api/v1/models",
+ { headers: { Authorization: "Bearer sk-or-valid" } },
+ );
+ });
+
+ it("passes the resolved API key as a Bearer token", async () => {
+ (auth as jest.Mock).mockResolvedValue({ user: { id: "user-1" } });
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-my-key");
+ global.fetch = jest.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ data: [] }),
+ });
+
+ await GET();
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: { Authorization: "Bearer sk-or-my-key" },
+ }),
+ );
+ });
+
+ it("returns the upstream status code when OpenRouter fetch fails", async () => {
+ (auth as jest.Mock).mockResolvedValue({ user: { id: "user-1" } });
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-valid");
+ global.fetch = jest.fn().mockResolvedValue({ ok: false, status: 503 });
+
+ const response = await GET();
+ const data = await response.json();
+
+ expect(response.status).toBe(503);
+ expect(data.error).toBe("Failed to fetch OpenRouter models");
+ });
+
+ it("returns 500 on unexpected fetch error", async () => {
+ (auth as jest.Mock).mockResolvedValue({ user: { id: "user-1" } });
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-valid");
+ global.fetch = jest.fn().mockRejectedValue(new Error("Network failure"));
+
+ const response = await GET();
+
+ expect(response.status).toBe(500);
+ });
+
+ it("handles missing session by passing undefined userId to resolveApiKey", async () => {
+ (auth as jest.Mock).mockResolvedValue(null);
+ (resolveApiKey as jest.Mock).mockResolvedValue(undefined);
+
+ const response = await GET();
+
+ expect(response.status).toBe(401);
+ expect(resolveApiKey).toHaveBeenCalledWith(undefined, "openrouter");
+ });
+
+ it("resolves the API key using the authenticated user's id", async () => {
+ (auth as jest.Mock).mockResolvedValue({ user: { id: "user-42" } });
+ (resolveApiKey as jest.Mock).mockResolvedValue(null);
+
+ await GET();
+
+ expect(resolveApiKey).toHaveBeenCalledWith("user-42", "openrouter");
+ });
+});
diff --git a/__tests__/provider-registry-server.spec.ts b/__tests__/provider-registry-server.spec.ts
new file mode 100644
index 0000000..0453205
--- /dev/null
+++ b/__tests__/provider-registry-server.spec.ts
@@ -0,0 +1,111 @@
+// Mock server-only so the module can be imported in the jest (jsdom) environment
+jest.mock("server-only", () => ({}));
+
+// Mock AI SDK packages to avoid loading provider implementations in tests
+jest.mock("@ai-sdk/openai", () => ({ createOpenAI: jest.fn() }));
+jest.mock("@ai-sdk/deepseek", () => ({ createDeepSeek: jest.fn() }));
+jest.mock("@ai-sdk/google", () => ({ createGoogleGenerativeAI: jest.fn() }));
+jest.mock("ollama-ai-provider-v2", () => ({ createOllama: jest.fn() }));
+
+import { createOpenAI } from "@ai-sdk/openai";
+import {
+ PROVIDER_FACTORIES,
+ PROVIDER_VERIFIERS,
+} from "@/lib/ai/provider-registry.server";
+
+describe("PROVIDER_VERIFIERS – openrouter", () => {
+ it("returns { success: true } on a 200 OK response", async () => {
+ global.fetch = jest.fn().mockResolvedValue({ ok: true, status: 200 });
+
+ const result = await PROVIDER_VERIFIERS.openrouter("sk-or-valid");
+
+ expect(result).toEqual({ success: true });
+ expect(global.fetch).toHaveBeenCalledWith(
+ "https://openrouter.ai/api/v1/models",
+ { headers: { Authorization: "Bearer sk-or-valid" } },
+ );
+ });
+
+ it("returns 'Invalid API key' error on 401", async () => {
+ global.fetch = jest.fn().mockResolvedValue({ ok: false, status: 401 });
+
+ const result = await PROVIDER_VERIFIERS.openrouter("sk-or-bad-key");
+
+ expect(result).toEqual({ success: false, error: "Invalid API key" });
+ });
+
+ it("returns status-based error message on 500", async () => {
+ global.fetch = jest.fn().mockResolvedValue({ ok: false, status: 500 });
+
+ const result = await PROVIDER_VERIFIERS.openrouter("sk-or-key");
+
+ expect(result).toEqual({
+ success: false,
+ error: "OpenRouter returned 500",
+ });
+ });
+
+ it("returns status-based error message on 503", async () => {
+ global.fetch = jest.fn().mockResolvedValue({ ok: false, status: 503 });
+
+ const result = await PROVIDER_VERIFIERS.openrouter("sk-or-key");
+
+ expect(result).toEqual({
+ success: false,
+ error: "OpenRouter returned 503",
+ });
+ });
+
+ it("includes the API key in the Authorization header", async () => {
+ global.fetch = jest.fn().mockResolvedValue({ ok: true, status: 200 });
+
+ await PROVIDER_VERIFIERS.openrouter("sk-or-my-secret-key");
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ headers: { Authorization: "Bearer sk-or-my-secret-key" },
+ }),
+ );
+ });
+});
+
+describe("PROVIDER_FACTORIES – openrouter", () => {
+ it("uses createOpenAI with the openrouter baseURL", () => {
+ const mockModelInstance = { modelId: "openai/gpt-4o" };
+ const mockChainFn = jest.fn().mockReturnValue(mockModelInstance);
+ (createOpenAI as jest.Mock).mockReturnValue(mockChainFn);
+
+ const result = PROVIDER_FACTORIES.openrouter(
+ "sk-or-apikey",
+ "openai/gpt-4o",
+ );
+
+ expect(createOpenAI).toHaveBeenCalledWith({
+ apiKey: "sk-or-apikey",
+ baseURL: "https://openrouter.ai/api/v1",
+ });
+ expect(mockChainFn).toHaveBeenCalledWith("openai/gpt-4o");
+ expect(result).toBe(mockModelInstance);
+ });
+
+ it("passes the model name through to the factory chain", () => {
+ const mockChainFn = jest.fn().mockReturnValue({});
+ (createOpenAI as jest.Mock).mockReturnValue(mockChainFn);
+
+ PROVIDER_FACTORIES.openrouter("sk-or-key", "google/gemini-flash");
+
+ expect(mockChainFn).toHaveBeenCalledWith("google/gemini-flash");
+ });
+
+ it("passes the API key through to createOpenAI", () => {
+ const mockChainFn = jest.fn().mockReturnValue({});
+ (createOpenAI as jest.Mock).mockReturnValue(mockChainFn);
+
+ PROVIDER_FACTORIES.openrouter("sk-or-specific-key", "any-model");
+
+ expect(createOpenAI).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: "sk-or-specific-key" }),
+ );
+ });
+});
diff --git a/__tests__/provider-registry.spec.ts b/__tests__/provider-registry.spec.ts
new file mode 100644
index 0000000..8915e92
--- /dev/null
+++ b/__tests__/provider-registry.spec.ts
@@ -0,0 +1,136 @@
+import { PROVIDER_REGISTRY, AI_PROVIDERS } from "@/lib/ai/provider-registry";
+
+describe("AI_PROVIDERS", () => {
+ it("includes openrouter", () => {
+ expect(AI_PROVIDERS).toContain("openrouter");
+ });
+
+ it("contains exactly 5 providers", () => {
+ expect(AI_PROVIDERS).toHaveLength(5);
+ });
+
+ it("contains ollama, openai, deepseek, openrouter, gemini", () => {
+ expect(AI_PROVIDERS).toEqual(
+ expect.arrayContaining([
+ "ollama",
+ "openai",
+ "deepseek",
+ "openrouter",
+ "gemini",
+ ]),
+ );
+ });
+});
+
+describe("PROVIDER_REGISTRY – openrouter entry", () => {
+ const entry = PROVIDER_REGISTRY.openrouter;
+
+ it("exists in the registry", () => {
+ expect(entry).toBeDefined();
+ });
+
+ it("has id 'openrouter'", () => {
+ expect(entry.id).toBe("openrouter");
+ });
+
+ it("has displayName 'OpenRouter'", () => {
+ expect(entry.displayName).toBe("OpenRouter");
+ });
+
+ it("uses api-key credential type", () => {
+ expect(entry.credentialType).toBe("api-key");
+ });
+
+ it("is categorized as cloud", () => {
+ expect(entry.category).toBe("cloud");
+ });
+
+ it("uses OPENROUTER_API_KEY env var", () => {
+ expect(entry.envVar).toBe("OPENROUTER_API_KEY");
+ });
+
+ it("has correct modelsEndpoint", () => {
+ expect(entry.modelsEndpoint).toBe("openrouter/models");
+ });
+
+ it("does not require a running check", () => {
+ expect(entry.requiresRunningCheck).toBe(false);
+ });
+
+ it("does not support keepAlive", () => {
+ expect(entry.supportsKeepAlive).toBe(false);
+ });
+
+ it("has password input type", () => {
+ expect(entry.keyConfig.inputType).toBe("password");
+ });
+
+ it("marks key as sensitive", () => {
+ expect(entry.keyConfig.sensitive).toBe(true);
+ });
+
+ it("placeholder starts with sk-or-", () => {
+ expect(entry.keyConfig.placeholder).toMatch(/^sk-or-/);
+ });
+
+ it("has no defaultCredential", () => {
+ expect(entry.defaultCredential).toBeUndefined();
+ });
+
+ describe("parseModelsResponse", () => {
+ it("maps model ids and sorts alphabetically", () => {
+ const data = {
+ data: [
+ { id: "mistral/mistral-7b" },
+ { id: "anthropic/claude-2" },
+ { id: "openai/gpt-4" },
+ ],
+ };
+ expect(entry.parseModelsResponse!(data)).toEqual([
+ "anthropic/claude-2",
+ "mistral/mistral-7b",
+ "openai/gpt-4",
+ ]);
+ });
+
+ it("returns empty array when data property is missing", () => {
+ expect(entry.parseModelsResponse!({})).toEqual([]);
+ });
+
+ it("returns empty array when data.data is empty", () => {
+ expect(entry.parseModelsResponse!({ data: [] })).toEqual([]);
+ });
+
+ it("returns a single model correctly", () => {
+ const data = { data: [{ id: "openai/gpt-4o" }] };
+ expect(entry.parseModelsResponse!(data)).toEqual(["openai/gpt-4o"]);
+ });
+
+ it("sorts multiple models alphabetically", () => {
+ const data = {
+ data: [{ id: "z-model" }, { id: "a-model" }, { id: "m-model" }],
+ };
+ expect(entry.parseModelsResponse!(data)).toEqual([
+ "a-model",
+ "m-model",
+ "z-model",
+ ]);
+ });
+
+ it("handles models with slash-separated provider/name format", () => {
+ const data = {
+ data: [
+ { id: "google/gemini-pro" },
+ { id: "anthropic/claude-3-opus" },
+ { id: "meta-llama/llama-3-8b" },
+ ],
+ };
+ const result = entry.parseModelsResponse!(data);
+ expect(result).toEqual([
+ "anthropic/claude-3-opus",
+ "google/gemini-pro",
+ "meta-llama/llama-3-8b",
+ ]);
+ });
+ });
+});
diff --git a/__tests__/providers.spec.ts b/__tests__/providers.spec.ts
new file mode 100644
index 0000000..0871622
--- /dev/null
+++ b/__tests__/providers.spec.ts
@@ -0,0 +1,89 @@
+// Mock server-only dependencies to allow importing getModel in the jsdom environment
+jest.mock("@/lib/api-key-resolver", () => ({
+ resolveApiKey: jest.fn(),
+}));
+
+jest.mock("@/lib/ai/provider-registry.server", () => ({
+ PROVIDER_FACTORIES: {
+ openrouter: jest.fn(),
+ openai: jest.fn(),
+ deepseek: jest.fn(),
+ ollama: jest.fn(),
+ gemini: jest.fn(),
+ },
+}));
+
+import { getModel } from "@/lib/ai/providers";
+import { resolveApiKey } from "@/lib/api-key-resolver";
+import { PROVIDER_FACTORIES } from "@/lib/ai/provider-registry.server";
+
+describe("getModel – openrouter", () => {
+ const mockModelInstance = { modelId: "openai/gpt-4o" };
+
+ beforeEach(() => {
+ (PROVIDER_FACTORIES.openrouter as jest.Mock).mockReturnValue(
+ mockModelInstance,
+ );
+ });
+
+ it("resolves credentials and returns a model instance", async () => {
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-test-key");
+
+ const result = await getModel("openrouter", "openai/gpt-4o", "user-1");
+
+ expect(resolveApiKey).toHaveBeenCalledWith("user-1", "openrouter");
+ expect(PROVIDER_FACTORIES.openrouter).toHaveBeenCalledWith(
+ "sk-or-test-key",
+ "openai/gpt-4o",
+ );
+ expect(result).toBe(mockModelInstance);
+ });
+
+ it("works without a userId (falls back to env var resolution)", async () => {
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-from-env");
+
+ const result = await getModel("openrouter", "openai/gpt-4o");
+
+ expect(resolveApiKey).toHaveBeenCalledWith(undefined, "openrouter");
+ expect(result).toBe(mockModelInstance);
+ });
+
+ it("throws when OpenRouter credential is not configured", async () => {
+ (resolveApiKey as jest.Mock).mockResolvedValue(undefined);
+
+ await expect(
+ getModel("openrouter", "openai/gpt-4o", "user-1"),
+ ).rejects.toThrow("OpenRouter credential not configured");
+ });
+
+ it("passes the model name to the factory", async () => {
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-key");
+
+ await getModel("openrouter", "anthropic/claude-3-opus", "user-1");
+
+ expect(PROVIDER_FACTORIES.openrouter).toHaveBeenCalledWith(
+ "sk-or-key",
+ "anthropic/claude-3-opus",
+ );
+ });
+});
+
+describe("getModel – provider validation", () => {
+ it("throws for unknown provider", async () => {
+ (resolveApiKey as jest.Mock).mockResolvedValue("some-key");
+
+ await expect(
+ getModel("unknown-provider" as any, "some-model"),
+ ).rejects.toThrow("Unknown AI provider");
+ });
+
+ it("recognizes openrouter as a valid ProviderType", async () => {
+ (resolveApiKey as jest.Mock).mockResolvedValue("sk-or-key");
+ (PROVIDER_FACTORIES.openrouter as jest.Mock).mockReturnValue({});
+
+ // Should resolve without throwing
+ await expect(
+ getModel("openrouter", "openai/gpt-4o"),
+ ).resolves.toBeDefined();
+ });
+});