Commit c5510a27 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add a real test suite and CI/CD for the webapp

Nothing existed before this - first tests for the project. Vitest +
React Testing Library (jsdom environment), all explicit imports (no
reliance on injected globals, even though globals: true is set).

Coverage, prioritized by actual risk rather than 100%-for-its-own-sake:
- client.ts (highest value): auth header injection, json/form body
  serialization, error parsing, and - the trickiest logic in the app -
  the 401-refresh-and-retry flow, including that concurrent 401s share a
  single in-flight refresh instead of each firing their own, and that a
  failed refresh doesn't loop.
- jwt.ts: real base64url decode (not a simplified stand-in), including
  the -/_ substitution path standard base64 doesn't need.
- AuthContext: the dev auto-login bypass specifically - doesn't
  auto-authenticate without configured tokens, does with them, doesn't
  clobber an already-real session, and logout actually clears state.
  Uses vi.resetModules() + dynamic import per test since DEV_ACCESS_TOKEN
  is captured as a module-level const at import time, so env stubs set
  after the module already loaded would silently do nothing.
- UI primitives (Button/ProgressBar/EmptyState): rendering + interaction.
- Library page: empty state, list rendering, error display, and the
  play/pause flow including that pausing doesn't re-fetch the stream.

jsdom needed two stubs in test/setup.ts: HTMLMediaElement.play/pause
(Library calls these for real) and URL.createObjectURL/revokeObjectURL
(jsdom has no real object URL storage) - both throw "Not implemented"
without them.

.gitlab-ci.yml: deliberately minimal after everything the backend's
pipeline taught this session - no Docker, no apt-get, just
npm ci -> tsc -> vitest -> vite build on node:20-slim. Verified locally:
npm ci works cleanly against the lockfile (real risk after many
incremental npm installs), and the exact CI command sequence passes
end to end.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 92661638
Pipeline #1042 failed with stage
......@@ -12,6 +12,7 @@ dist
dist-ssr
*.local
.env
.cache
# Editor directories and files
.vscode/*
......
stages:
- test
variables:
npm_config_cache: "$CI_PROJECT_DIR/.cache/npm"
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- .cache/npm/
# Runs on every push. Typechecks, runs the Vitest suite, and confirms the production build
# actually succeeds - all three catch different classes of bugs (tsc catches type errors
# vitest doesn't run into if a test happens not to exercise a given path; vite build catches
# real bundling/import issues tsc alone won't, e.g. a bad asset path or circular import).
test:
stage: test
image: node:20-slim
script:
- npm ci
- npx tsc -b --noEmit
- npm test
- npm run build
only:
- main
This diff is collapsed.
......@@ -7,7 +7,9 @@
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"lucide-react": "^1.31.0",
......@@ -17,13 +19,18 @@
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.3",
"@types/node": "^24.13.3",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.4",
"jsdom": "^29.1.1",
"oxlint": "^1.75.0",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.2.0"
"vite": "^8.2.0",
"vitest": "^4.1.10"
}
}
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { apiFetch, ApiError, clearTokens, getAccessToken, setTokens } from './client'
function jsonResponse(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
describe('apiFetch', () => {
beforeEach(() => {
clearTokens()
vi.stubGlobal('fetch', vi.fn())
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('sends the Authorization header when an access token is set', async () => {
setTokens('access-123', 'refresh-456')
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(200, { ok: true }))
await apiFetch('/library')
const [, options] = vi.mocked(fetch).mock.calls[0]
const headers = options?.headers as Headers
expect(headers.get('Authorization')).toBe('Bearer access-123')
})
it('omits the Authorization header when auth: false', async () => {
setTokens('access-123', 'refresh-456')
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(200, { ok: true }))
await apiFetch('/auth/request_code', { auth: false })
const [, options] = vi.mocked(fetch).mock.calls[0]
const headers = options?.headers as Headers
expect(headers.get('Authorization')).toBeNull()
})
it('serializes a json body with the right content-type', async () => {
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(200, {}))
await apiFetch('/social/posts', { method: 'POST', json: { song_id: 1 } })
const [, options] = vi.mocked(fetch).mock.calls[0]
const headers = options?.headers as Headers
expect(headers.get('Content-Type')).toBe('application/json')
expect(options?.body).toBe(JSON.stringify({ song_id: 1 }))
})
it('serializes a form body as URL-encoded, matching FastAPI Form(...) endpoints', async () => {
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(200, {}))
await apiFetch('/discovery/1/swipe', { method: 'POST', form: { liked: true } })
const [, options] = vi.mocked(fetch).mock.calls[0]
expect(options?.body).toBeInstanceOf(URLSearchParams)
expect((options?.body as URLSearchParams).get('liked')).toBe('true')
})
it('returns parsed JSON on success', async () => {
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(200, { library: [1, 2, 3] }))
const result = await apiFetch<{ library: number[] }>('/library')
expect(result.library).toEqual([1, 2, 3])
})
it('returns undefined for a 204 response without trying to parse a body', async () => {
vi.mocked(fetch).mockResolvedValueOnce(new Response(null, { status: 204 }))
const result = await apiFetch('/some/endpoint')
expect(result).toBeUndefined()
})
it('throws ApiError using the response detail message on failure', async () => {
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(404, { detail: 'Song not found' }))
await expect(apiFetch('/library/stream/999')).rejects.toMatchObject({
status: 404,
message: 'Song not found',
})
})
it('falls back to a generic message when the error body is not JSON', async () => {
vi.mocked(fetch).mockResolvedValueOnce(new Response('not json', { status: 500 }))
await expect(apiFetch('/library')).rejects.toMatchObject({
status: 500,
message: 'Request failed with status 500',
})
})
it('is an instance of ApiError specifically, not a plain Error', async () => {
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(400, { detail: 'bad request' }))
try {
await apiFetch('/library')
expect.unreachable('apiFetch should have thrown')
} catch (err) {
expect(err).toBeInstanceOf(ApiError)
}
})
it('on a 401, refreshes the token once and retries the original request', async () => {
setTokens('expired-access', 'valid-refresh')
vi.mocked(fetch)
.mockResolvedValueOnce(jsonResponse(401, { detail: 'Token expired' })) // original request
.mockResolvedValueOnce(jsonResponse(200, { access_token: 'new-access', refresh_token: 'new-refresh' })) // /auth/refresh
.mockResolvedValueOnce(jsonResponse(200, { library: [] })) // retried request
const result = await apiFetch<{ library: unknown[] }>('/library')
expect(result).toEqual({ library: [] })
expect(fetch).toHaveBeenCalledTimes(3)
expect(getAccessToken()).toBe('new-access')
// the retried call must use the freshly refreshed token, not the expired one
const [, retryOptions] = vi.mocked(fetch).mock.calls[2]
const retryHeaders = retryOptions?.headers as Headers
expect(retryHeaders.get('Authorization')).toBe('Bearer new-access')
})
it('on a 401 with no refresh token available, fails without calling /auth/refresh', async () => {
setTokens('expired-access', '')
clearTokens() // no tokens at all - the common real case (never logged in / already logged out)
vi.mocked(fetch).mockResolvedValueOnce(jsonResponse(401, { detail: 'Not authenticated' }))
await expect(apiFetch('/library')).rejects.toMatchObject({ status: 401 })
expect(fetch).toHaveBeenCalledTimes(1)
})
it('on a 401 where the refresh itself also fails, surfaces the original 401 without looping', async () => {
setTokens('expired-access', 'also-invalid-refresh')
vi.mocked(fetch)
.mockResolvedValueOnce(jsonResponse(401, { detail: 'Token expired' })) // original request
.mockResolvedValueOnce(jsonResponse(401, { detail: 'Refresh token invalid or revoked' })) // /auth/refresh fails too
await expect(apiFetch('/library')).rejects.toMatchObject({ status: 401 })
expect(fetch).toHaveBeenCalledTimes(2) // original + refresh attempt, no infinite retry loop
})
it('shares a single in-flight refresh across concurrent 401s instead of refreshing once per call', async () => {
setTokens('expired-access', 'valid-refresh')
vi.mocked(fetch)
.mockResolvedValueOnce(jsonResponse(401, { detail: 'expired' })) // call A original
.mockResolvedValueOnce(jsonResponse(401, { detail: 'expired' })) // call B original
.mockResolvedValueOnce(jsonResponse(200, { access_token: 'new-access', refresh_token: 'new-refresh' })) // one shared refresh
.mockResolvedValueOnce(jsonResponse(200, { a: true })) // call A retry
.mockResolvedValueOnce(jsonResponse(200, { b: true })) // call B retry
const [a, b] = await Promise.all([apiFetch('/a'), apiFetch('/b')])
expect(a).toEqual({ a: true })
expect(b).toEqual({ b: true })
expect(fetch).toHaveBeenCalledTimes(5) // not 6 - the refresh call itself was shared
})
})
import { describe, expect, it, beforeEach } from 'vitest'
import { getCurrentUserId } from './jwt'
import { clearTokens, setTokens } from './client'
/** Builds a real base64url-encoded JWT shape (unsigned - getCurrentUserId never verifies,
* that's the server's job) so the test exercises the actual base64url decode path
* (- and _ substitution) rather than a simplified stand-in. */
function fakeJwt(payload: object): string {
const base64url = (obj: object) =>
btoa(JSON.stringify(obj)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
return `${base64url({ alg: 'HS256', typ: 'JWT' })}.${base64url(payload)}.fake-signature`
}
describe('getCurrentUserId', () => {
beforeEach(() => clearTokens())
it('returns null when there is no access token', () => {
expect(getCurrentUserId()).toBeNull()
})
it('extracts the numeric sub claim from a real access token', () => {
setTokens(fakeJwt({ sub: '42', type: 'access' }), 'refresh-token-unused-here')
expect(getCurrentUserId()).toBe(42)
})
it('returns null for a malformed token instead of throwing', () => {
setTokens('not-a-real-jwt', 'refresh-token-unused-here')
expect(getCurrentUserId()).toBeNull()
})
it('handles base64url characters (-/_) that differ from standard base64', () => {
// A large enough sub value that JSON-stringifying the payload is likely to produce
// base64 output containing + or / in standard encoding - forcing the -/_ substitution
// path in getCurrentUserId to actually matter, not just the common case.
setTokens(fakeJwt({ sub: '999999999', type: 'access', extra: 'padding-to-shift-alignment' }), 'r')
expect(getCurrentUserId()).toBe(999999999)
})
})
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it, vi } from 'vitest'
import { Button } from './Button'
describe('Button', () => {
it('renders its children and responds to clicks', async () => {
const onClick = vi.fn()
render(<Button onClick={onClick}>Create Remix</Button>)
await userEvent.click(screen.getByRole('button', { name: 'Create Remix' }))
expect(onClick).toHaveBeenCalledTimes(1)
})
it('does not fire onClick when disabled', async () => {
const onClick = vi.fn()
render(
<Button onClick={onClick} disabled>
Upload
</Button>,
)
await userEvent.click(screen.getByRole('button', { name: 'Upload' }))
expect(onClick).not.toHaveBeenCalled()
expect(screen.getByRole('button')).toBeDisabled()
})
it('applies variant-specific styling', () => {
render(<Button variant="secondary">Log out</Button>)
expect(screen.getByRole('button')).toHaveClass('bg-neutral-800')
})
it('forwards a ref to the underlying <button> element', () => {
let ref: HTMLButtonElement | null = null
render(
<Button
ref={(el) => {
ref = el
}}
>
Send
</Button>,
)
expect(ref).toBeInstanceOf(HTMLButtonElement)
})
it('passes through arbitrary props like type and aria-label', () => {
render(<Button type="submit" aria-label="Send message" />)
const button = screen.getByRole('button', { name: 'Send message' })
expect(button).toHaveAttribute('type', 'submit')
})
})
import { render, screen } from '@testing-library/react'
import { Music2 } from 'lucide-react'
import { describe, expect, it } from 'vitest'
import { EmptyState } from './EmptyState'
describe('EmptyState', () => {
it('renders the given icon and message', () => {
const { container } = render(
<EmptyState icon={Music2} message="No songs yet - tag something from Telegram to see it here." />,
)
expect(
screen.getByText('No songs yet - tag something from Telegram to see it here.'),
).toBeInTheDocument()
expect(container.querySelector('svg')).toBeInTheDocument()
})
})
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { ProgressBar } from './ProgressBar'
describe('ProgressBar', () => {
it('renders a determinate bar with the correct width and percentage text', () => {
const { container } = render(<ProgressBar percent={42} label="Uploading" />)
expect(screen.getByText('Uploading')).toBeInTheDocument()
expect(screen.getByText('42%')).toBeInTheDocument()
const fill = container.querySelector('[style*="width"]')
expect(fill).toHaveStyle({ width: '42%' })
})
it('renders an indeterminate bar (no percentage text) when percent is null', () => {
render(<ProgressBar percent={null} label="Identifying & tagging…" />)
expect(screen.getByText('Identifying & tagging…')).toBeInTheDocument()
expect(screen.queryByText('%', { exact: false })).not.toBeInTheDocument()
})
})
import { render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client'
// DEV_ACCESS_TOKEN/DEV_REFRESH_TOKEN are captured as module-level constants from
// import.meta.env at import time (see AuthContext.tsx), so changing env after the module is
// already loaded has no effect - vi.resetModules() + a fresh dynamic import per test is what
// actually lets each test control which env values that module sees.
//
// import.meta.env.DEV itself isn't stubbed here: Vitest's default mode ('test' != 'production')
// already makes it true, matching real `npm run dev`. A production build is a genuinely
// different Vite mode, not something a runtime env stub can simulate - that boundary is
// trusted to Vite's own define-time dead-code elimination rather than unit-tested directly.
async function loadFreshAuthContext() {
vi.resetModules()
return import('./AuthContext')
}
function Probe({ useAuth }: { useAuth: typeof import('./AuthContext').useAuth }) {
const { isAuthenticated } = useAuth()
return <span data-testid="auth-state">{isAuthenticated ? 'authenticated' : 'not-authenticated'}</span>
}
describe('AuthProvider dev auto-login', () => {
beforeEach(() => {
clearTokens()
})
afterEach(() => {
vi.unstubAllEnvs()
clearTokens()
})
it('does not auto-authenticate when no dev tokens are configured', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
const { AuthProvider, useAuth } = await loadFreshAuthContext()
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
expect(screen.getByTestId('auth-state')).toHaveTextContent('not-authenticated')
expect(getAccessToken()).toBeNull()
})
it('auto-authenticates using the configured dev tokens', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
const { AuthProvider, useAuth } = await loadFreshAuthContext()
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
await waitFor(() => {
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
})
expect(getAccessToken()).toBe('dev-access-token')
expect(getRefreshToken()).toBe('dev-refresh-token')
})
it('does not overwrite an already-present access token (e.g. from a real login)', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
setTokens('already-logged-in-token', 'already-logged-in-refresh')
const { AuthProvider, useAuth } = await loadFreshAuthContext()
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
expect(getAccessToken()).toBe('already-logged-in-token')
})
})
describe('logout', () => {
afterEach(() => {
vi.unstubAllEnvs()
clearTokens()
vi.restoreAllMocks()
})
it('clears tokens and flips isAuthenticated to false', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens('some-access-token', 'some-refresh-token')
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('{}', { status: 200 })))
const { AuthProvider, useAuth } = await loadFreshAuthContext()
function LogoutProbe() {
const { isAuthenticated, logout } = useAuth()
return (
<div>
<span data-testid="auth-state">{isAuthenticated ? 'authenticated' : 'not-authenticated'}</span>
<button onClick={() => logout()}>Log out</button>
</div>
)
}
render(
<AuthProvider>
<LogoutProbe />
</AuthProvider>,
)
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
screen.getByText('Log out').click()
await waitFor(() => {
expect(screen.getByTestId('auth-state')).toHaveTextContent('not-authenticated')
})
expect(getAccessToken()).toBeNull()
vi.unstubAllGlobals()
})
})
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Library } from './Library'
import { AuthProvider } from '../context/AuthContext'
import { ApiError } from '../api/client'
import * as libraryApi from '../api/library'
import * as streamApi from '../api/stream'
const SONG = {
id: 1,
user_id: 1,
title: 'Invisible',
artist: 'Duran Duran',
album: 'Astronaut',
genre: 'Pop',
coverart: null,
lyrics: null,
file_path: '/x.mp3',
added_at: '2026-01-01T00:00:00Z',
}
function renderLibrary() {
return render(
<MemoryRouter>
<AuthProvider>
<Library />
</AuthProvider>
</MemoryRouter>,
)
}
describe('Library', () => {
beforeEach(() => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('shows the empty state when the library has no songs', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [] })
renderLibrary()
expect(await screen.findByText(/No songs yet/)).toBeInTheDocument()
})
it('renders each song once loaded', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
renderLibrary()
expect(await screen.findByText('Invisible')).toBeInTheDocument()
expect(screen.getByText('Duran Duran · Astronaut')).toBeInTheDocument()
})
it('shows a load error using the ApiError message', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockRejectedValue(new ApiError(500, 'Server exploded', null))
renderLibrary()
expect(await screen.findByText('Server exploded')).toBeInTheDocument()
})
it('fetches a stream URL and plays the song when Play is clicked', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary()
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await waitFor(() => {
expect(fetchStreamUrl).toHaveBeenCalledWith(1)
})
expect(await screen.findByRole('button', { name: 'Pause' })).toBeInTheDocument()
})
it('pauses without re-fetching the stream when clicked again while playing', async () => {
vi.spyOn(libraryApi, 'getLibrary').mockResolvedValue({ status: 'success', library: [SONG] })
const fetchStreamUrl = vi.spyOn(streamApi, 'fetchStreamUrl').mockResolvedValue('blob:fake-url')
renderLibrary()
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: 'Play' }))
await screen.findByRole('button', { name: 'Pause' })
await userEvent.click(screen.getByRole('button', { name: 'Pause' }))
expect(await screen.findByRole('button', { name: 'Play' })).toBeInTheDocument()
expect(fetchStreamUrl).toHaveBeenCalledTimes(1) // not called again on pause
})
})
import '@testing-library/jest-dom/vitest'
import { vi } from 'vitest'
// jsdom doesn't implement real media playback and throws "Not implemented" for these -
// Library's play/pause calls the real HTMLMediaElement APIs, so tests need a harmless stub.
window.HTMLMediaElement.prototype.play = vi.fn().mockResolvedValue(undefined)
window.HTMLMediaElement.prototype.pause = vi.fn()
// jsdom has no real object URL storage - fine for tests, we just need these to not throw.
window.URL.createObjectURL = vi.fn(() => 'blob:mock-url')
window.URL.revokeObjectURL = vi.fn()
/// <reference types="vitest/config" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
......@@ -9,4 +10,10 @@ export default defineConfig({
host: true,
port: 5173,
},
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts',
css: true,
},
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment