-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthProvider.test.tsx
More file actions
317 lines (277 loc) · 8.68 KB
/
AuthProvider.test.tsx
File metadata and controls
317 lines (277 loc) · 8.68 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// AuthProvider.test.tsx
import React, { useContext, act } from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, waitFor, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import AuthProvider from '../../context/AuthProvider';
import AuthContext, { AuthContextData } from '../../context/AuthContext';
import api from '../../api-service/api';
import { API_TOKEN, USER_DATA } from '../../app-constants/app-constants';
import ApiConfig from '../../api-service/apiConfig';
// Mock the API service methods.
vi.mock('../../api-service/api');
// Create a helper component to consume AuthContext for testing.
const ConsumerComponent: React.FC = () => {
const {
signed,
loading,
user,
signIn,
register,
signOut,
updateUser,
checkCurrentAuthUser
} = useContext<AuthContextData>(AuthContext);
return (
<div>
<div data-testid="signed">{signed ? 'true' : 'false'}</div>
<div data-testid="loading">{loading ? 'true' : 'false'}</div>
<div data-testid="user">{user ? user.name : 'none'}</div>
<button
data-testid="signIn"
onClick={async() => {
await signIn('test@example.com', 'password123');
}}
>
Sign In
</button>
<button
data-testid="register"
onClick={() => {
register('new@example.com', 'password123', 'password123');
}}
>
Register
</button>
<button
data-testid="sign-out-btn"
onClick={() => {
signOut();
}}
>
Sign Out
</button>
<button
data-testid="updateUser"
onClick={() => {
updateUser({
userId: 1,
name: 'Updated User',
email: 'updated@example.com',
admin: false,
createdAt: new Date(),
gravatarImageUrl: 'http://dummyimage.com'
});
}}
>
Update User
</button>
<button
data-testid="checkCurrentAuthUser"
onClick={() => {
checkCurrentAuthUser('/some-path');
}}
>
Check Current Auth User
</button>
</div>
);
};
describe('AuthProvider', () => {
// Reset DOM and mocks for each test.
beforeEach(() => {
localStorage.clear();
vi.clearAllMocks();
});
afterEach(() => {
cleanup();
});
it('should render the default context values', async () => {
const { getByTestId } = render(
<AuthProvider>
<ConsumerComponent />
</AuthProvider>
);
await waitFor(() => {
expect(getByTestId('signed').textContent).toBe('false');
expect(getByTestId('user').textContent).toBe('none');
});
});
it('should set loading to false after initial auth check with no token', async () => {
// No token in localStorage, so fetchCurrentSession returns immediately.
const { getByTestId } = render(
<AuthProvider>
<ConsumerComponent />
</AuthProvider>
);
await waitFor(() =>
expect(getByTestId('loading').textContent).toBe('false')
);
expect(getByTestId('signed').textContent).toBe('false');
});
it('should set loading to false and signed to true after successful initial auth check', async () => {
const fakeTokenResponse = {
token: 'refresh-token',
};
const fakeCurrentUser = {
userId: '789',
name: 'Refreshed User',
email: 'refreshed@example.com',
admin: false,
createdAt: new Date().toISOString(),
gravatarImageUrl: 'http://dummyimage.com',
lang: 'en',
lastLogin: new Date().toISOString()
};
vi.spyOn(api, 'getJSON').mockImplementation(async(url: string) => {
if (url === ApiConfig.refreshTokenUrl) {
return fakeTokenResponse;
}
if (url === ApiConfig.currentUserUrl) {
return fakeCurrentUser;
}
return undefined;
});
localStorage.setItem(API_TOKEN, 'dummy');
const { getByTestId } = render(
<AuthProvider>
<ConsumerComponent />
</AuthProvider>
);
await waitFor(() =>
expect(getByTestId('loading').textContent).toBe('false')
);
expect(getByTestId('signed').textContent).toBe('true');
expect(getByTestId('user').textContent).toBe('Refreshed User');
});
it('should sign in a user successfully', async () => {
// Create a fake sign-in response.
const fakeResponse = {
userId: '123',
name: 'Test User',
email: 'test@example.com',
admin: false,
createdAt: new Date(),
token: 'dummy-token',
gravatarImageUrl: 'http://dummyimage.com'
};
vi.spyOn(api, 'postJSON').mockResolvedValue(fakeResponse);
const { getByTestId } = render(
<AuthProvider>
<ConsumerComponent />
</AuthProvider>
);
await userEvent.click(getByTestId('signIn'));
await waitFor(() =>
expect(getByTestId('signed').textContent).toBe('true')
);
expect(getByTestId('user').textContent).toBe('Test User');
// LocalStorage should have API_TOKEN and USER_DATA set.
expect(localStorage.getItem(API_TOKEN)).toBe('dummy-token');
expect(localStorage.getItem(USER_DATA)).not.toBeNull();
});
it('should sign out a user', async () => {
// Pre-populate localStorage to simulate a signed-in state.
localStorage.setItem(API_TOKEN, 'dummy-token');
localStorage.setItem(
USER_DATA,
JSON.stringify({
userId: '123',
name: 'Test User',
email: 'test@example.com',
admin: false,
createdAt: new Date(),
gravatarImageUrl: 'http://dummyimage.com'
})
);
const fakeResponse = {
userId: '123',
name: 'Test User',
email: 'test@example.com',
admin: false,
createdAt: new Date(),
token: 'dummy-token',
gravatarImageUrl: 'http://dummyimage.com'
};
vi.spyOn(api, 'postJSON').mockResolvedValue(fakeResponse);
const { getByTestId } = render(
<AuthProvider>
<ConsumerComponent />
</AuthProvider>
);
// Make sure that the context initially renders with the signed user by triggering a signIn.
await userEvent.click(getByTestId('signIn'));
await waitFor(() =>
expect(getByTestId('signed').textContent).toBe('true')
);
// Now sign out
await userEvent.click(getByTestId('sign-out-btn'));
await waitFor(() =>
expect(getByTestId('signed').textContent).toBe('false')
);
expect(getByTestId('user').textContent).toBe('none');
// LocalStorage items should be removed.
expect(localStorage.getItem(API_TOKEN)).toBeNull();
expect(localStorage.getItem(USER_DATA)).toBeNull();
});
it('should update user in context and localStorage', async () => {
const { getByTestId } = render(
<AuthProvider>
<ConsumerComponent />
</AuthProvider>
);
await userEvent.click(getByTestId('updateUser'));
await waitFor(() => {
expect(getByTestId('user').textContent).toBe('Updated User')
const savedUser = localStorage.getItem(USER_DATA);
expect(savedUser).not.toBeNull();
if (savedUser) {
const parsedUser = JSON.parse(savedUser);
expect(parsedUser.name).toBe('Updated User');
}
});
});
it('should call fetchCurrentSession when checking current auth user', async () => {
const fakeTokenResponse = {
token: 'refresh-token',
};
const fakeCurrentUser = {
userId: '789',
name: 'Refreshed User',
email: 'refreshed@example.com',
admin: false,
createdAt: new Date().toISOString(),
gravatarImageUrl: 'http://dummyimage.com',
lang: 'en',
lastLogin: new Date().toISOString()
};
vi.spyOn(api, 'getJSON').mockImplementation(async(url: string) => {
if (url === ApiConfig.refreshTokenUrl) {
return fakeTokenResponse;
}
if (url === ApiConfig.currentUserUrl) {
return fakeCurrentUser;
}
return undefined;
});
// Store API_TOKEN so that fetchCurrentSession runs the refresh logic.
localStorage.setItem(API_TOKEN, 'dummy');
const user = userEvent.setup();
let getByTestIdFunction;
await act(async () => {
const { getByTestId } = render(
<AuthProvider>
<ConsumerComponent />
</AuthProvider>
);
getByTestIdFunction = getByTestId;
});
// Wait for any initial renders to complete
await waitFor(() => expect(getByTestIdFunction('checkCurrentAuthUser')).toBeDefined());
await user.click(getByTestIdFunction('checkCurrentAuthUser'));
await waitFor(() => {
expect(localStorage.getItem(API_TOKEN)).toBe('refresh-token');
expect(localStorage.getItem(USER_DATA)).toContain('Refreshed User');
});
});
});