Skip to content

Commit 48da281

Browse files
Copilothotlong
andcommitted
refactor: address code review - add resetAuthState, toSafeUser helper, improve test isolation
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
1 parent ecdb58d commit 48da281

File tree

2 files changed

+46
-16
lines changed

2 files changed

+46
-16
lines changed

apps/console/src/__tests__/authHandlers.test.ts

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,15 @@
1010

1111
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
1212
import { setupServer } from 'msw/node';
13-
import { createAuthHandlers } from '../mocks/authHandlers';
13+
import { createAuthHandlers, resetAuthState } from '../mocks/authHandlers';
1414

1515
const BASE_URL = 'http://localhost/api/v1/auth';
1616
const handlers = createAuthHandlers('/api/v1/auth');
1717
const server = setupServer(...handlers);
1818

1919
beforeAll(() => server.listen({ onUnhandledRequest: 'bypass' }));
2020
afterAll(() => server.close());
21-
22-
/**
23-
* Reset the in-memory user store between tests by importing a
24-
* fresh set of handlers. Because the module-level Maps/state
25-
* persist across tests within the same module, we accept that
26-
* state accumulates during a single describe block and structure
27-
* tests as a sequential flow: sign-up → sign-in → session → sign-out.
28-
*/
21+
beforeEach(() => resetAuthState());
2922

3023
describe('Mock Auth Handlers', () => {
3124
it('should register a new user via sign-up', async () => {
@@ -51,6 +44,13 @@ describe('Mock Auth Handlers', () => {
5144
});
5245

5346
it('should reject duplicate sign-up', async () => {
47+
// Register a user first
48+
await fetch(`${BASE_URL}/sign-up/email`, {
49+
method: 'POST',
50+
headers: { 'Content-Type': 'application/json' },
51+
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com', password: 'secret123' }),
52+
});
53+
5454
const res = await fetch(`${BASE_URL}/sign-up/email`, {
5555
method: 'POST',
5656
headers: { 'Content-Type': 'application/json' },
@@ -77,6 +77,13 @@ describe('Mock Auth Handlers', () => {
7777
});
7878

7979
it('should sign in with correct credentials', async () => {
80+
// Register user first
81+
await fetch(`${BASE_URL}/sign-up/email`, {
82+
method: 'POST',
83+
headers: { 'Content-Type': 'application/json' },
84+
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com', password: 'secret123' }),
85+
});
86+
8087
const res = await fetch(`${BASE_URL}/sign-in/email`, {
8188
method: 'POST',
8289
headers: { 'Content-Type': 'application/json' },
@@ -106,7 +113,12 @@ describe('Mock Auth Handlers', () => {
106113
});
107114

108115
it('should return current session after sign-in', async () => {
109-
// First sign in to establish a session
116+
// Register and sign in
117+
await fetch(`${BASE_URL}/sign-up/email`, {
118+
method: 'POST',
119+
headers: { 'Content-Type': 'application/json' },
120+
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com', password: 'secret123' }),
121+
});
110122
await fetch(`${BASE_URL}/sign-in/email`, {
111123
method: 'POST',
112124
headers: { 'Content-Type': 'application/json' },
@@ -150,7 +162,12 @@ describe('Mock Auth Handlers', () => {
150162
});
151163

152164
it('should update user when authenticated', async () => {
153-
// Sign in first
165+
// Register and sign in first
166+
await fetch(`${BASE_URL}/sign-up/email`, {
167+
method: 'POST',
168+
headers: { 'Content-Type': 'application/json' },
169+
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com', password: 'secret123' }),
170+
});
154171
await fetch(`${BASE_URL}/sign-in/email`, {
155172
method: 'POST',
156173
headers: { 'Content-Type': 'application/json' },
@@ -171,9 +188,6 @@ describe('Mock Auth Handlers', () => {
171188
});
172189

173190
it('should reject update-user when not authenticated', async () => {
174-
// Sign out first
175-
await fetch(`${BASE_URL}/sign-out`, { method: 'POST' });
176-
177191
const res = await fetch(`${BASE_URL}/update-user`, {
178192
method: 'POST',
179193
headers: { 'Content-Type': 'application/json' },

apps/console/src/mocks/authHandlers.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
* enable sign-up, sign-in, session, and sign-out flows in the MSW
77
* (browser / test) environment where no real AuthPlugin is available.
88
*
9+
* NOTE: This is a mock/testing module only. Passwords are stored in
10+
* plain text — never use this pattern in production code.
11+
*
912
* Endpoints:
1013
* POST /sign-up/email — register a new user
1114
* POST /sign-in/email — authenticate with email + password
@@ -38,6 +41,13 @@ const users = new Map<string, MockUser & { password: string }>();
3841
let currentSession: { user: MockUser; session: MockSession } | null = null;
3942
let nextId = 1;
4043

44+
/** Reset all in-memory auth state. Call in test `beforeEach` for isolation. */
45+
export function resetAuthState(): void {
46+
users.clear();
47+
currentSession = null;
48+
nextId = 1;
49+
}
50+
4151
function generateToken(): string {
4252
return `mock-token-${Date.now()}-${Math.random().toString(36).slice(2)}`;
4353
}
@@ -46,6 +56,12 @@ function generateExpiry(): string {
4656
return new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
4757
}
4858

59+
/** Return a user object without the password field. */
60+
function toSafeUser(user: MockUser & { password: string }): MockUser {
61+
const { password: _, ...safe } = user;
62+
return safe;
63+
}
64+
4965
/**
5066
* Create MSW request handlers that mock the better-auth REST endpoints.
5167
*
@@ -94,7 +110,7 @@ export function createAuthHandlers(baseUrl: string): HttpHandler[] {
94110
token: generateToken(),
95111
expiresAt: generateExpiry(),
96112
};
97-
const { password: _, ...safeUser } = user;
113+
const safeUser = toSafeUser(user);
98114
currentSession = { user: safeUser, session };
99115

100116
return HttpResponse.json({ user: safeUser, session });
@@ -126,7 +142,7 @@ export function createAuthHandlers(baseUrl: string): HttpHandler[] {
126142
token: generateToken(),
127143
expiresAt: generateExpiry(),
128144
};
129-
const { password: _, ...safeUser } = stored;
145+
const safeUser = toSafeUser(stored);
130146
currentSession = { user: safeUser, session };
131147

132148
return HttpResponse.json({ user: safeUser, session });

0 commit comments

Comments
 (0)