File size: 13,339 Bytes
766d85d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
318
319
320
321
322
323
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../tests/helpers/msw/server'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
import { resetAllStores } from '../tests/helpers/store'
import { buildUser, buildSettings } from '../tests/helpers/factories'
import App from './App'

// ── Mock page components ───────────────────────────────────────────────────────
vi.mock('./pages/LoginPage', () => ({ default: () => <div>Login</div> }))
vi.mock('./pages/DashboardPage', () => ({ default: () => <div>Dashboard</div> }))
vi.mock('./pages/TripPlannerPage', () => ({ default: () => <div>TripPlanner</div> }))
vi.mock('./pages/FilesPage', () => ({ default: () => <div>Files</div> }))
vi.mock('./pages/AdminPage', () => ({ default: () => <div>Admin</div> }))
vi.mock('./pages/SettingsPage', () => ({ default: () => <div>Settings</div> }))
vi.mock('./pages/VacayPage', () => ({ default: () => <div>Vacay</div> }))
vi.mock('./pages/AtlasPage', () => ({ default: () => <div>Atlas</div> }))
vi.mock('./pages/SharedTripPage', () => ({ default: () => <div>SharedTrip</div> }))
vi.mock('./pages/InAppNotificationsPage.tsx', () => ({ default: () => <div>Notifications</div> }))

// Prevent WebSocket side effects from the notification listener
vi.mock('./hooks/useInAppNotificationListener.ts', () => ({
  useInAppNotificationListener: vi.fn(),
}))

// ── Helpers ────────────────────────────────────────────────────────────────────

function renderApp(initialPath = '/') {
  return render(
    <MemoryRouter initialEntries={[initialPath]}>
      <App />
    </MemoryRouter>
  )
}

/**
 * Seeds authStore with sensible defaults for a test, replacing loadUser with a
 * no-op spy so the MSW /api/auth/me response does not overwrite the seeded state.
 */
function seedAuth(overrides: Record<string, unknown> = {}) {
  useAuthStore.setState({
    isLoading: false,
    isAuthenticated: false,
    user: null,
    appRequireMfa: false,
    loadUser: vi.fn().mockResolvedValue(undefined),
    ...overrides,
  })
}

beforeEach(() => {
  resetAllStores()
  vi.clearAllMocks()
  document.documentElement.classList.remove('dark')
})

// ── RootRedirect ───────────────────────────────────────────────────────────────

describe('RootRedirect', () => {
  it('FE-COMP-APP-001: / redirects to /login when not authenticated', async () => {
    seedAuth({ isAuthenticated: false })
    renderApp('/')
    await waitFor(() => expect(screen.getByText('Login')).toBeInTheDocument())
  })

  it('FE-COMP-APP-002: / redirects to /dashboard when authenticated', async () => {
    seedAuth({ isAuthenticated: true, user: buildUser() })
    renderApp('/')
    await waitFor(() => expect(screen.getByText('Dashboard')).toBeInTheDocument())
  })

  it('FE-COMP-APP-003: / shows loading spinner while auth is loading', () => {
    seedAuth({ isLoading: true, isAuthenticated: false })
    renderApp('/')
    expect(document.querySelector('.animate-spin')).toBeInTheDocument()
    expect(screen.queryByText('Login')).not.toBeInTheDocument()
  })
})

// ── ProtectedRoute β€” unauthenticated ──────────────────────────────────────────

describe('ProtectedRoute β€” unauthenticated', () => {
  it('FE-COMP-APP-004: /dashboard redirects to /login with redirect param when not authenticated', async () => {
    seedAuth({ isAuthenticated: false })
    renderApp('/dashboard')
    await waitFor(() => expect(screen.getByText('Login')).toBeInTheDocument())
  })

  it('FE-COMP-APP-005: /trips/42 redirects to /login when not authenticated', async () => {
    seedAuth({ isAuthenticated: false })
    renderApp('/trips/42')
    await waitFor(() => expect(screen.getByText('Login')).toBeInTheDocument())
  })
})

// ── ProtectedRoute β€” loading ───────────────────────────────────────────────────

describe('ProtectedRoute β€” loading state', () => {
  it('FE-COMP-APP-006: protected route shows loading spinner while isLoading is true', () => {
    seedAuth({ isLoading: true, isAuthenticated: false })
    renderApp('/dashboard')
    expect(document.querySelector('.animate-spin')).toBeInTheDocument()
    expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
  })
})

// ── ProtectedRoute β€” MFA enforcement ──────────────────────────────────────────

describe('ProtectedRoute β€” MFA enforcement', () => {
  it('FE-COMP-APP-007: redirects to /settings?mfa=required when appRequireMfa is true and MFA is disabled', async () => {
    seedAuth({
      isAuthenticated: true,
      appRequireMfa: true,
      user: buildUser({ mfa_enabled: false }),
    })
    renderApp('/dashboard')
    await waitFor(() => expect(screen.getByText('Settings')).toBeInTheDocument())
  })

  it('FE-COMP-APP-008: does NOT redirect when already on /settings even with MFA required', async () => {
    seedAuth({
      isAuthenticated: true,
      appRequireMfa: true,
      user: buildUser({ mfa_enabled: false }),
    })
    renderApp('/settings')
    await waitFor(() => expect(screen.getByText('Settings')).toBeInTheDocument())
    expect(screen.queryByText('Login')).not.toBeInTheDocument()
  })

  it('FE-COMP-APP-009: does NOT redirect when user has MFA enabled', async () => {
    seedAuth({
      isAuthenticated: true,
      appRequireMfa: true,
      user: buildUser({ mfa_enabled: true }),
    })
    renderApp('/dashboard')
    await waitFor(() => expect(screen.getByText('Dashboard')).toBeInTheDocument())
  })
})

// ── ProtectedRoute β€” admin role ────────────────────────────────────────────────

describe('ProtectedRoute β€” admin role check', () => {
  it('FE-COMP-APP-010: /admin redirects to /dashboard for non-admin user', async () => {
    seedAuth({
      isAuthenticated: true,
      user: buildUser({ role: 'user' }),
    })
    renderApp('/admin')
    await waitFor(() => expect(screen.getByText('Dashboard')).toBeInTheDocument())
    expect(screen.queryByText('Admin')).not.toBeInTheDocument()
  })

  it('FE-COMP-APP-011: /admin is accessible for admin user', async () => {
    seedAuth({
      isAuthenticated: true,
      user: buildUser({ role: 'admin' }),
    })
    renderApp('/admin')
    await waitFor(() => expect(screen.getByText('Admin')).toBeInTheDocument())
  })
})

// ── Public routes ──────────────────────────────────────────────────────────────

describe('Public routes', () => {
  it('FE-COMP-APP-012: /login is accessible without authentication', async () => {
    seedAuth({ isAuthenticated: false })
    renderApp('/login')
    expect(screen.getByText('Login')).toBeInTheDocument()
  })

  it('FE-COMP-APP-013: /shared/:token is accessible without authentication', async () => {
    seedAuth({ isAuthenticated: false })
    renderApp('/shared/sometoken')
    expect(screen.getByText('SharedTrip')).toBeInTheDocument()
  })

  it('FE-COMP-APP-014: unknown routes redirect to / which then redirects to /login', async () => {
    seedAuth({ isAuthenticated: false })
    renderApp('/does-not-exist')
    await waitFor(() => expect(screen.getByText('Login')).toBeInTheDocument())
  })
})

// ── App β€” on-mount effects ─────────────────────────────────────────────────────

describe('App β€” on-mount effects', () => {
  it('FE-COMP-APP-015: loadUser is called on mount for non-shared paths', async () => {
    const loadUser = vi.fn().mockResolvedValue(undefined)
    useAuthStore.setState({ isLoading: false, isAuthenticated: false, loadUser })
    renderApp('/dashboard')
    expect(loadUser).toHaveBeenCalled()
  })

  it('FE-COMP-APP-016: loadUser is NOT called on /shared/ paths', async () => {
    const loadUser = vi.fn().mockResolvedValue(undefined)
    useAuthStore.setState({ isLoading: false, isAuthenticated: false, loadUser })
    renderApp('/shared/token123')
    expect(loadUser).not.toHaveBeenCalled()
  })

  it('FE-COMP-APP-017: GET /api/auth/app-config is called on mount', async () => {
    let configCalled = false
    server.use(
      http.get('/api/auth/app-config', () => {
        configCalled = true
        return HttpResponse.json({})
      })
    )
    seedAuth()
    renderApp('/')
    await waitFor(() => expect(configCalled).toBe(true))
  })

  it('FE-COMP-APP-018: setDemoMode(true) is called when config returns demo_mode: true', async () => {
    server.use(
      http.get('/api/auth/app-config', () => HttpResponse.json({ demo_mode: true }))
    )
    const setDemoMode = vi.fn()
    useAuthStore.setState({
      isLoading: false,
      isAuthenticated: false,
      loadUser: vi.fn().mockResolvedValue(undefined),
      setDemoMode,
    })
    renderApp('/')
    await waitFor(() => expect(setDemoMode).toHaveBeenCalledWith(true))
  })

  it('FE-COMP-APP-019: loadSettings is called once the user is authenticated', async () => {
    const loadSettings = vi.fn().mockResolvedValue(undefined)
    seedAuth({ isAuthenticated: true, user: buildUser() })
    useSettingsStore.setState({ loadSettings })
    renderApp('/dashboard')
    await waitFor(() => expect(loadSettings).toHaveBeenCalled())
  })
})

// ── Dark mode effects ──────────────────────────────────────────────────────────

describe('Dark mode effects', () => {
  it('FE-COMP-APP-020: adds dark class to documentElement when dark_mode is true', async () => {
    seedAuth({ isAuthenticated: true, user: buildUser() })
    useSettingsStore.setState({ settings: buildSettings({ dark_mode: true }) })
    renderApp('/dashboard')
    await waitFor(() =>
      expect(document.documentElement.classList.contains('dark')).toBe(true)
    )
  })

  it('FE-COMP-APP-021: removes dark class when dark_mode is false', async () => {
    document.documentElement.classList.add('dark')
    seedAuth({ isAuthenticated: true, user: buildUser() })
    useSettingsStore.setState({ settings: buildSettings({ dark_mode: false }) })
    renderApp('/dashboard')
    await waitFor(() =>
      expect(document.documentElement.classList.contains('dark')).toBe(false)
    )
  })

  it('FE-COMP-APP-022: forces light mode on /shared/ path even when dark_mode is true', async () => {
    document.documentElement.classList.add('dark')
    useSettingsStore.setState({ settings: buildSettings({ dark_mode: true }) })
    seedAuth({ isAuthenticated: false, loadUser: vi.fn().mockResolvedValue(undefined) })
    renderApp('/shared/tok')
    await waitFor(() =>
      expect(document.documentElement.classList.contains('dark')).toBe(false)
    )
  })

  it('FE-COMP-APP-023: auto mode applies dark based on matchMedia result', async () => {
    // matchMedia stub returns matches: false by default (from setup.ts)
    seedAuth({ isAuthenticated: true, user: buildUser() })
    useSettingsStore.setState({ settings: buildSettings({ dark_mode: 'auto' as any }) })
    renderApp('/dashboard')
    // With matches: false, dark should NOT be added
    await waitFor(() =>
      expect(document.documentElement.classList.contains('dark')).toBe(false)
    )
  })
})

// ── Version cache-busting ──────────────────────────────────────────────────────

describe('Version cache-busting', () => {
  it('FE-COMP-APP-024: stores version in localStorage when config returns a version', async () => {
    server.use(
      http.get('/api/auth/app-config', () =>
        HttpResponse.json({ version: '2.9.10' })
      )
    )
    seedAuth()
    renderApp('/')
    await waitFor(() =>
      expect(localStorage.getItem('trek_app_version')).toBe('2.9.10')
    )
  })

  it('FE-COMP-APP-025: calls window.location.reload() when version changes', async () => {
    localStorage.setItem('trek_app_version', '2.9.9')
    const reload = vi.fn()
    Object.defineProperty(window, 'location', {
      writable: true,
      value: { ...window.location, reload },
    })

    server.use(
      http.get('/api/auth/app-config', () =>
        HttpResponse.json({ version: '2.9.10' })
      )
    )
    seedAuth()
    renderApp('/')
    await waitFor(() => expect(reload).toHaveBeenCalled())
  })
})