Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

client.test.ts

115 lines2.7 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { createGeminiClient } from '../src/utils/client'
3​
4const mocks = vi.hoisted(() => {
5 return {
6 constructorSpy: vi.fn<(options: Record<string, unknown>) => void>(),
7 }
8})
9​
10vi.mock('@google/genai', () => {
11 class MockGoogleGenAI {
12 constructor(options: Record<string, unknown>) {
13 mocks.constructorSpy(options)
14 }
15 }
16​
17 return {
18 GoogleGenAI: MockGoogleGenAI,
19 }
20})
21​
22describe('createGeminiClient', () => {
23 beforeEach(() => {
24 vi.clearAllMocks()
25 })
26​
27 afterEach(() => {
28 vi.unstubAllEnvs()
29 })
30​
31 it('passes an API key through in AI Studio mode', () => {
32 createGeminiClient({ apiKey: 'studio-key' })
33​
34 expect(mocks.constructorSpy).toHaveBeenCalledExactlyOnceWith({
35 apiKey: 'studio-key',
36 })
37 })
38​
39 it('throws in AI Studio mode when apiKey is missing', () => {
40 expect(() => createGeminiClient({})).toThrow(/A Gemini API key is required/)
41 expect(mocks.constructorSpy).not.toHaveBeenCalled()
42 })
43​
44 it('does not force apiKey in Vertex mode', () => {
45 createGeminiClient({
46 vertexai: true,
47 project: 'my-project',
48 location: 'europe-west1',
49 })
50​
51 expect(mocks.constructorSpy).toHaveBeenCalledExactlyOnceWith({
52 vertexai: true,
53 project: 'my-project',
54 location: 'europe-west1',
55 })
56 })
57​
58 it('does not force apiKey in enterprise mode', () => {
59 createGeminiClient({
60 enterprise: true,
61 project: 'my-project',
62 location: 'europe-west1',
63 })
64​
65 expect(mocks.constructorSpy).toHaveBeenCalledExactlyOnceWith({
66 enterprise: true,
67 project: 'my-project',
68 location: 'europe-west1',
69 })
70 })
71})
72​
73describe('createGeminiClient proxy options', () => {
74 beforeEach(() => {
75 vi.clearAllMocks()
76 })
77​
78 it('maps baseURL and defaultHeaders onto httpOptions', () => {
79 createGeminiClient({
80 apiKey: 'k',
81 baseURL: 'https://gw.example/gemini',
82 defaultHeaders: { 'cf-aig-authorization': 'Bearer t' },
83 })
84​
85 expect(mocks.constructorSpy).toHaveBeenCalledExactlyOnceWith({
86 apiKey: 'k',
87 httpOptions: {
88 baseUrl: 'https://gw.example/gemini',
89 headers: { 'cf-aig-authorization': 'Bearer t' },
90 },
91 })
92 })
93​
94 it('keeps other httpOptions, normalized names win', () => {
95 createGeminiClient({
96 apiKey: 'k',
97 httpOptions: {
98 baseUrl: 'https://old.example',
99 headers: { a: '1', b: 'old' },
100 timeout: 5,
101 },
102 baseURL: 'https://new.example',
103 defaultHeaders: { b: 'new' },
104 })
105​
106 expect(mocks.constructorSpy).toHaveBeenCalledExactlyOnceWith({
107 apiKey: 'k',
108 httpOptions: {
109 baseUrl: 'https://new.example',
110 headers: { b: 'new' },
111 timeout: 5,
112 },
113 })
114 })
115})