-
Notifications
You must be signed in to change notification settings - Fork 518
Expand file tree
/
Copy pathuse-usage-query.test.ts
More file actions
211 lines (174 loc) · 5.63 KB
/
use-usage-query.test.ts
File metadata and controls
211 lines (174 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { wrapMockAsFetch, type FetchCallFn } from '@codebuff/common/testing/fixtures'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderHook, waitFor } from '@testing-library/react'
import {
describe,
test,
expect,
beforeEach,
afterEach,
mock,
spyOn,
} from 'bun:test'
import React from 'react'
import type { Logger } from '@codebuff/common/types/contracts/logger'
import { useChatStore } from '../../state/chat-store'
import * as authModule from '../../utils/auth'
import {
fetchUsageData,
useUsageQuery,
useRefreshUsage,
} from '../use-usage-query'
describe('fetchUsageData', () => {
const originalFetch = globalThis.fetch
const originalEnv = process.env.NEXT_PUBLIC_CODEBUFF_APP_URL
beforeEach(() => {
process.env.NEXT_PUBLIC_CODEBUFF_APP_URL = 'https://test.codebuff.local'
})
afterEach(() => {
globalThis.fetch = originalFetch
process.env.NEXT_PUBLIC_CODEBUFF_APP_URL = originalEnv
mock.restore()
})
test('should fetch usage data successfully', async () => {
const mockResponse = {
type: 'usage-response' as const,
usage: 100,
remainingBalance: 500,
balanceBreakdown: { free: 300, paid: 200 },
next_quota_reset: '2024-02-01T00:00:00.000Z',
}
globalThis.fetch = wrapMockAsFetch(
mock<FetchCallFn>(
async () =>
new Response(JSON.stringify(mockResponse), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
),
)
const result = await fetchUsageData({ authToken: 'test-token' })
expect(result).toEqual(mockResponse)
})
test('should throw error on failed request', async () => {
globalThis.fetch = wrapMockAsFetch(
mock<FetchCallFn>(async () => new Response('Error', { status: 500 })),
)
const mockLogger: Logger = {
error: mock<Logger['error']>(() => {}),
warn: mock<Logger['warn']>(() => {}),
info: mock<Logger['info']>(() => {}),
debug: mock<Logger['debug']>(() => {}),
}
await expect(
fetchUsageData({ authToken: 'test-token', logger: mockLogger }),
).rejects.toThrow('Failed to fetch usage: 500')
})
test('should throw error when app URL is not set', async () => {
await expect(
fetchUsageData({
authToken: 'test-token',
clientEnv: { NEXT_PUBLIC_CODEBUFF_APP_URL: undefined },
}),
).rejects.toThrow('NEXT_PUBLIC_CODEBUFF_APP_URL is not set')
})
})
describe('useUsageQuery', () => {
let queryClient: QueryClient
let getAuthTokenSpy: ReturnType<typeof spyOn>
const originalEnv = process.env.NEXT_PUBLIC_CODEBUFF_APP_URL
function createWrapper() {
return ({ children }: { children: React.ReactNode }) =>
React.createElement(
QueryClientProvider,
{ client: queryClient },
children,
)
}
beforeEach(() => {
queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
process.env.NEXT_PUBLIC_CODEBUFF_APP_URL = 'https://test.codebuff.local'
useChatStore.getState().reset()
})
afterEach(() => {
getAuthTokenSpy?.mockRestore()
process.env.NEXT_PUBLIC_CODEBUFF_APP_URL = originalEnv
mock.restore()
})
test.skip('should fetch data when enabled', async () => {
getAuthTokenSpy = spyOn(authModule, 'getAuthToken').mockReturnValue(
'test-token',
)
const mockResponse = {
type: 'usage-response' as const,
usage: 100,
remainingBalance: 500,
next_quota_reset: '2024-02-01T00:00:00.000Z',
}
globalThis.fetch = wrapMockAsFetch(
mock<FetchCallFn>(
async () =>
new Response(JSON.stringify(mockResponse), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
),
)
const { result } = renderHook(() => useUsageQuery(), {
wrapper: createWrapper(),
})
await waitFor(() => expect(result.current.isSuccess).toBe(true))
expect(result.current.data).toEqual(mockResponse)
})
test.skip('should not fetch when disabled', async () => {
getAuthTokenSpy = spyOn(authModule, 'getAuthToken').mockReturnValue(
'test-token',
)
const fetchMock = mock<FetchCallFn>(async () => new Response('{}'))
globalThis.fetch = wrapMockAsFetch(fetchMock)
const { result } = renderHook(() => useUsageQuery({ enabled: false }), {
wrapper: createWrapper(),
})
await new Promise((resolve) => setTimeout(resolve, 100))
expect(fetchMock).not.toHaveBeenCalled()
expect(result.current.data).toBeUndefined()
})
test.skip('should not fetch when no auth token', async () => {
getAuthTokenSpy = spyOn(authModule, 'getAuthToken').mockReturnValue(
undefined,
)
const fetchMock = mock<FetchCallFn>(async () => new Response('{}'))
globalThis.fetch = wrapMockAsFetch(fetchMock)
renderHook(() => useUsageQuery(), {
wrapper: createWrapper(),
})
await new Promise((resolve) => setTimeout(resolve, 100))
expect(fetchMock).not.toHaveBeenCalled()
})
})
describe('useRefreshUsage', () => {
let queryClient: QueryClient
function createWrapper() {
return ({ children }: { children: React.ReactNode }) =>
React.createElement(
QueryClientProvider,
{ client: queryClient },
children,
)
}
beforeEach(() => {
queryClient = new QueryClient()
})
test.skip('should invalidate usage queries', async () => {
const invalidateSpy = spyOn(queryClient, 'invalidateQueries')
const { result } = renderHook(() => useRefreshUsage(), {
wrapper: createWrapper(),
})
result.current()
expect(invalidateSpy).toHaveBeenCalled()
})
})