-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathsetup.test.ts
More file actions
221 lines (170 loc) · 7.91 KB
/
setup.test.ts
File metadata and controls
221 lines (170 loc) · 7.91 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
212
213
214
215
216
217
218
219
220
221
import { ClerkAPIResponseError } from '@clerk/shared/error';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// Re-export internals for testing by importing the module and testing through fetchEnvVars
// Since fetchWithRetry and isNetworkError are not exported, we test them indirectly through fetchEnvVars
// and also directly by extracting them via a test-specific import approach.
// We need to mock the dependencies before importing the module under test
vi.mock('@clerk/backend', () => ({
createClerkClient: vi.fn(),
}));
vi.mock('dotenv', () => ({
default: { config: vi.fn() },
}));
vi.mock('@clerk/shared/keys', () => ({
parsePublishableKey: vi.fn(() => ({ frontendApi: 'clerk.test.lcl.dev' })),
}));
import { createClerkClient } from '@clerk/backend';
import { fetchEnvVars } from '../setup';
function createClerkAPIError(status: number, retryAfter?: number) {
return new ClerkAPIResponseError('API error', {
data: [],
status,
retryAfter,
});
}
function createNetworkError(code: string) {
const err = new Error(`connect ${code}`);
(err as NodeJS.ErrnoException).code = code;
return err;
}
describe('fetchWithRetry (via fetchEnvVars)', () => {
const mockCreateTestingToken = vi.fn();
beforeEach(() => {
mockCreateTestingToken.mockReset();
vi.useFakeTimers();
vi.stubEnv('CLERK_PUBLISHABLE_KEY', 'pk_test_abc');
vi.stubEnv('CLERK_SECRET_KEY', 'sk_test_abc');
delete process.env.CLERK_TESTING_TOKEN;
vi.mocked(createClerkClient).mockReturnValue({
testingTokens: { createTestingToken: mockCreateTestingToken },
} as any);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
it('returns on first success without retrying', async () => {
mockCreateTestingToken.mockResolvedValueOnce({ token: 'test-token' });
const result = await fetchEnvVars({ dotenv: false });
expect(result.CLERK_TESTING_TOKEN).toBe('test-token');
expect(mockCreateTestingToken).toHaveBeenCalledTimes(1);
});
it('retries on 429 and succeeds', async () => {
mockCreateTestingToken
.mockRejectedValueOnce(createClerkAPIError(429))
.mockResolvedValueOnce({ token: 'test-token' });
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const promise = fetchEnvVars({ dotenv: false });
await vi.advanceTimersByTimeAsync(30_000);
const result = await promise;
expect(result.CLERK_TESTING_TOKEN).toBe('test-token');
expect(mockCreateTestingToken).toHaveBeenCalledTimes(2);
expect(warnSpy).toHaveBeenCalledTimes(1);
expect(warnSpy.mock.calls[0][0]).toContain('[Retry] 429');
expect(warnSpy.mock.calls[0][0]).toContain('attempt 1/5');
});
it.each([408, 500, 502, 503, 504])('retries on %i status code', async status => {
mockCreateTestingToken
.mockRejectedValueOnce(createClerkAPIError(status))
.mockResolvedValueOnce({ token: 'test-token' });
vi.spyOn(console, 'warn').mockImplementation(() => {});
const promise = fetchEnvVars({ dotenv: false });
await vi.advanceTimersByTimeAsync(30_000);
const result = await promise;
expect(result.CLERK_TESTING_TOKEN).toBe('test-token');
expect(mockCreateTestingToken).toHaveBeenCalledTimes(2);
});
it('does not retry on non-retryable status codes', async () => {
mockCreateTestingToken.mockRejectedValueOnce(createClerkAPIError(401));
vi.spyOn(console, 'error').mockImplementation(() => {});
await expect(fetchEnvVars({ dotenv: false })).rejects.toThrow('API error');
expect(mockCreateTestingToken).toHaveBeenCalledTimes(1);
});
it('throws after max retries exhausted', async () => {
mockCreateTestingToken.mockImplementation(() => Promise.reject(createClerkAPIError(429)));
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'error').mockImplementation(() => {});
const promise = fetchEnvVars({ dotenv: false }).catch(e => e);
await vi.runAllTimersAsync();
const error = await promise;
expect(error).toBeInstanceOf(ClerkAPIResponseError);
expect(error.status).toBe(429);
// 1 initial + 5 retries = 6 total calls
expect(mockCreateTestingToken).toHaveBeenCalledTimes(6);
});
it('uses retryAfter from error when available', async () => {
mockCreateTestingToken
.mockRejectedValueOnce(createClerkAPIError(429, 2))
.mockResolvedValueOnce({ token: 'test-token' });
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const promise = fetchEnvVars({ dotenv: false });
// retryAfter is 2 seconds = 2000ms
await vi.advanceTimersByTimeAsync(2000);
const result = await promise;
expect(result.CLERK_TESTING_TOKEN).toBe('test-token');
expect(warnSpy.mock.calls[0][0]).toContain('waiting 2000ms');
});
it('uses exponential backoff as floor when retryAfter is 0', async () => {
vi.spyOn(Math, 'random').mockReturnValue(0);
mockCreateTestingToken
.mockRejectedValueOnce(createClerkAPIError(429, 0))
.mockResolvedValueOnce({ token: 'test-token' });
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const promise = fetchEnvVars({ dotenv: false });
// retryAfter=0 should NOT cause a 0ms delay; exponential backoff (1000ms for attempt 0) is used as floor
await vi.advanceTimersByTimeAsync(999);
expect(mockCreateTestingToken).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
const result = await promise;
expect(result.CLERK_TESTING_TOKEN).toBe('test-token');
expect(warnSpy.mock.calls[0][0]).toContain('waiting 1000ms');
});
it('caps retryAfter delay at MAX_RETRY_DELAY_MS', async () => {
mockCreateTestingToken
.mockRejectedValueOnce(createClerkAPIError(429, 60))
.mockResolvedValueOnce({ token: 'test-token' });
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const promise = fetchEnvVars({ dotenv: false });
await vi.advanceTimersByTimeAsync(30_000);
const result = await promise;
expect(result.CLERK_TESTING_TOKEN).toBe('test-token');
// 60s * 1000 = 60000ms, capped to 30000ms
expect(warnSpy.mock.calls[0][0]).toContain('waiting 30000ms');
});
it.each(['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'ETIMEDOUT', 'EAI_AGAIN'])(
'retries on network error %s',
async code => {
mockCreateTestingToken
.mockRejectedValueOnce(createNetworkError(code))
.mockResolvedValueOnce({ token: 'test-token' });
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const promise = fetchEnvVars({ dotenv: false });
await vi.advanceTimersByTimeAsync(30_000);
const result = await promise;
expect(result.CLERK_TESTING_TOKEN).toBe('test-token');
expect(mockCreateTestingToken).toHaveBeenCalledTimes(2);
expect(warnSpy.mock.calls[0][0]).toContain(`[Retry] ${code}`);
},
);
it('does not retry on non-network errors', async () => {
mockCreateTestingToken.mockRejectedValueOnce(new TypeError('unexpected'));
vi.spyOn(console, 'error').mockImplementation(() => {});
await expect(fetchEnvVars({ dotenv: false })).rejects.toThrow('unexpected');
expect(mockCreateTestingToken).toHaveBeenCalledTimes(1);
});
it('does not retry when non-retryable error code is present', async () => {
const err = new Error('unknown');
(err as NodeJS.ErrnoException).code = 'EPERM';
vi.spyOn(console, 'error').mockImplementation(() => {});
mockCreateTestingToken.mockRejectedValueOnce(err);
await expect(fetchEnvVars({ dotenv: false })).rejects.toThrow('unknown');
expect(mockCreateTestingToken).toHaveBeenCalledTimes(1);
});
it('skips retry when CLERK_TESTING_TOKEN is already set', async () => {
vi.stubEnv('CLERK_TESTING_TOKEN', 'existing-token');
const result = await fetchEnvVars({ dotenv: false });
expect(result.CLERK_TESTING_TOKEN).toBe('existing-token');
expect(mockCreateTestingToken).not.toHaveBeenCalled();
});
});