Skip to content

Context7 Platform -- Up-to-date docs for AI agents

1.9 KB
Raw Blame
import { describe, test, expect } from "vitest";
import { SearchLibraryCommand } from "./index";
import { Context7Error } from "@error";
import { requesterWith } from "@utils/test-utils";

const apiResult = {
  results: [
    {
      id: "/facebook/react",
      title: "React",
      description: "A UI library",
      totalSnippets: 42,
      trustScore: 10,
      benchmarkScore: 95,
      versions: ["v19"],
    },
  ],
};

describe("SearchLibraryCommand", () => {
  test("maps an API response to libraries", async () => {
    const command = new SearchLibraryCommand("I need to build a UI", "react");

    await expect(command.exec(requesterWith(apiResult))).resolves.toEqual([
      {
        id: "/facebook/react",
        name: "React",
        description: "A UI library",
        totalSnippets: 42,
        trustScore: 10,
        benchmarkScore: 95,
        versions: ["v19"],
      },
    ]);
  });

  test("formats a text response locally", async () => {
    const command = new SearchLibraryCommand("I need to build a UI", "react", {
      type: "txt",
    });

    const result = await command.exec(requesterWith(apiResult));

    expect(result).toContain("Context7-compatible library ID: /facebook/react");
    expect(result).toContain("Trust Score: High");
  });

  test("throws a Context7 error when the response has no result", async () => {
    const command = new SearchLibraryCommand("I need to build a UI", "react");

    const error = await command.exec(requesterWith(undefined)).catch((e) => e);

    expect(error).toBeInstanceOf(Context7Error);
    expect(error).toMatchObject({
      message: "Request did not return a result",
      code: "invalid_response",
    });
  });

  test("rejects missing inputs without making a request", () => {
    expect(() => new SearchLibraryCommand("", "react")).toThrow(Context7Error);
    expect(() => new SearchLibraryCommand("query", "")).toThrow(Context7Error);
  });
});