| 1 | import { expect, jest } from "@jest/globals"; |
| 2 | import { ILLM } from "../../index.js"; |
| 3 | |
| 4 | export interface LlmTestCase { |
| 5 | llm: ILLM; |
| 6 | methodToTest: keyof ILLM; |
| 7 | params: any[]; |
| 8 | expectedRequest: { |
| 9 | url: string; |
| 10 | method: string; |
| 11 | headers?: Record<string, string>; |
| 12 | body?: Record<string, any>; |
| 13 | }; |
| 14 | mockResponse?: any; |
| 15 | mockStream?: string[]; // array of string chunks for SSE |
| 16 | } |
| 17 | |
| 18 | export async function runLlmTest(testCase: LlmTestCase) { |
| 19 | const { |
| 20 | llm, |
| 21 | methodToTest, |
| 22 | params, |
| 23 | expectedRequest, |
| 24 | mockResponse, |
| 25 | mockStream, |
| 26 | } = testCase; |
| 27 | |
| 28 | const mockFetch = jest.fn<any>(); |
| 29 | |
| 30 | if (mockStream) { |
| 31 | const encoder = new TextEncoder(); |
| 32 | let streamIndex = 0; |
| 33 | mockFetch.mockResolvedValue( |
| 34 | new Response( |
| 35 | new ReadableStream({ |
| 36 | start(controller) { |
| 37 | mockStream.forEach((chunk) => { |
| 38 | controller.enqueue(new TextEncoder().encode(chunk)); |
| 39 | }); |
| 40 | controller.close(); |
| 41 | }, |
| 42 | }), |
| 43 | { |
| 44 | headers: { |
| 45 | "Content-Type": "text/event-stream", |
| 46 | }, |
| 47 | }, |
| 48 | ), |
| 49 | ); |
| 50 | } else { |
| 51 | mockFetch.mockResolvedValue( |
| 52 | new Response(JSON.stringify(mockResponse), { |
| 53 | headers: { |
| 54 | "Content-Type": "application/json", |
| 55 | }, |
| 56 | }), |
| 57 | ); |
| 58 | } |
| 59 | |
| 60 | // @ts-ignore |
| 61 | llm.fetch = mockFetch; |
| 62 | |
| 63 | // @ts-ignore |
| 64 | if (typeof llm[methodToTest] !== "function") { |
| 65 | throw new Error( |
| 66 | `Method ${String(methodToTest)} does not exist on the LLM instance.`, |
| 67 | ); |
| 68 | } |
| 69 | |
| 70 | // @ts-ignore |
| 71 | const result = await llm[methodToTest](...params); |
| 72 | |
| 73 | if (mockStream) { |
| 74 | // Consume the stream to ensure it's processed correctly |
| 75 | for await (const _ of result) { |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | expect(mockFetch).toHaveBeenCalledTimes(1); |
| 80 | const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit]; |
| 81 | |
| 82 | expect(url.toString()).toBe(expectedRequest.url); |
| 83 | expect(options.method).toBe(expectedRequest.method); |
| 84 | |
| 85 | if (expectedRequest.headers) { |
| 86 | expect(options.headers).toEqual(expectedRequest.headers); |
| 87 | } |
| 88 | |
| 89 | if (expectedRequest.body) { |
| 90 | const actualBody = JSON.parse(options.body as string); |
| 91 | expect(actualBody).toEqual(expectedRequest.body); |
| 92 | } |
| 93 | } |