-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcreateAuthClient.test.ts
More file actions
201 lines (171 loc) · 7.47 KB
/
createAuthClient.test.ts
File metadata and controls
201 lines (171 loc) · 7.47 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
/**
* Tests for createAuthClient (backed by official better-auth client)
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { createAuthClient } from '../createAuthClient';
import type { AuthClient } from '../types';
/**
* Helper: creates a mock fetch that routes requests based on URL
* and records every call for inspection.
*/
function createMockFetch(handlers: Record<string, { status?: number; body: unknown }>) {
const calls: Array<{ url: string; method: string; body: string | null }> = [];
const mockFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
let url: string;
if (typeof input === 'string') {
url = input;
} else if (input instanceof URL) {
url = input.toString();
} else {
url = input.url;
}
calls.push({ url, method: init?.method ?? 'GET', body: init?.body as string | null });
for (const [pattern, handler] of Object.entries(handlers)) {
if (url.includes(pattern)) {
return new Response(JSON.stringify(handler.body), {
status: handler.status ?? 200,
headers: { 'Content-Type': 'application/json' },
});
}
}
return new Response(JSON.stringify({ message: 'Not found' }), {
status: 404,
headers: { 'Content-Type': 'application/json' },
});
});
return { mockFn, calls };
}
describe('createAuthClient', () => {
it('creates a client with all expected methods', () => {
const { mockFn } = createMockFetch({});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
expect(client).toHaveProperty('signIn');
expect(client).toHaveProperty('signUp');
expect(client).toHaveProperty('signOut');
expect(client).toHaveProperty('getSession');
expect(client).toHaveProperty('forgotPassword');
expect(client).toHaveProperty('resetPassword');
expect(client).toHaveProperty('updateUser');
});
it('signIn sends POST to /sign-in/email', async () => {
const { mockFn, calls } = createMockFetch({
'/sign-in/email': {
body: {
user: { id: '1', name: 'Test', email: 'test@test.com' },
session: { token: 'tok123', id: 's1', userId: '1', expiresAt: '2025-01-01' },
},
},
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
const result = await client.signIn({ email: 'test@test.com', password: 'pass123' });
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/sign-in/email');
expect(calls[0].method).toBe('POST');
expect(JSON.parse(calls[0].body!)).toMatchObject({ email: 'test@test.com', password: 'pass123' });
expect(result.user.email).toBe('test@test.com');
expect(result.session.token).toBe('tok123');
});
it('signUp sends POST to /sign-up/email', async () => {
const { mockFn, calls } = createMockFetch({
'/sign-up/email': {
body: {
user: { id: '2', name: 'New User', email: 'new@test.com' },
session: { token: 'tok456', id: 's2', userId: '2', expiresAt: '2025-01-01' },
},
},
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
const result = await client.signUp({ name: 'New User', email: 'new@test.com', password: 'pass123' });
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/sign-up/email');
expect(calls[0].method).toBe('POST');
expect(JSON.parse(calls[0].body!)).toMatchObject({ email: 'new@test.com', name: 'New User' });
expect(result.user.name).toBe('New User');
});
it('signOut sends POST to /sign-out', async () => {
const { mockFn, calls } = createMockFetch({
'/sign-out': { body: { success: true } },
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
await client.signOut();
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/sign-out');
expect(calls[0].method).toBe('POST');
});
it('getSession sends GET to /get-session', async () => {
const { mockFn, calls } = createMockFetch({
'/get-session': {
body: {
user: { id: '1', name: 'Test', email: 'test@test.com' },
session: { token: 'tok789', id: 's1', userId: '1', expiresAt: '2025-01-01' },
},
},
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
const result = await client.getSession();
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/get-session');
expect(calls[0].method).toBe('GET');
expect(result?.user.id).toBe('1');
});
it('getSession returns null on failure', async () => {
const { mockFn } = createMockFetch({
'/get-session': { status: 401, body: { message: 'Unauthorized' } },
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
const result = await client.getSession();
expect(result).toBeNull();
});
it('forgotPassword sends POST to /forget-password', async () => {
const { mockFn, calls } = createMockFetch({
'/forget-password': { body: { status: true } },
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
await client.forgotPassword('test@test.com');
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/forget-password');
expect(calls[0].method).toBe('POST');
expect(JSON.parse(calls[0].body!)).toMatchObject({ email: 'test@test.com' });
});
it('resetPassword sends POST to /reset-password', async () => {
const { mockFn, calls } = createMockFetch({
'/reset-password': { body: { status: true } },
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
await client.resetPassword('token123', 'newpass');
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/reset-password');
expect(calls[0].method).toBe('POST');
expect(JSON.parse(calls[0].body!)).toMatchObject({ token: 'token123', newPassword: 'newpass' });
});
it('throws error with server message on non-OK response', async () => {
const { mockFn } = createMockFetch({
'/sign-in/email': {
status: 401,
body: { message: 'Invalid credentials', code: 'INVALID_CREDENTIALS' },
},
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
await expect(client.signIn({ email: 'x', password: 'y' })).rejects.toThrow('Invalid credentials');
});
it('throws error on non-OK response without message', async () => {
const { mockFn } = createMockFetch({
'/sign-in/email': { status: 500, body: {} },
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
await expect(client.signIn({ email: 'x', password: 'y' })).rejects.toThrow();
});
it('updateUser sends POST to /update-user and returns user', async () => {
const { mockFn, calls } = createMockFetch({
'/update-user': {
body: { user: { id: '1', name: 'Updated', email: 'test@test.com' } },
},
});
const client = createAuthClient({ baseURL: 'http://localhost/api/auth', fetchFn: mockFn });
const result = await client.updateUser({ name: 'Updated' });
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('/api/auth/update-user');
expect(calls[0].method).toBe('POST');
expect(result.name).toBe('Updated');
});
});