mirror of
https://github.com/kilyabin/psysonic.git
synced 2026-07-22 14:35:41 +00:00
test(frontend): vitest framework bootstrap + hot-path coverage gate (#536)
* test(frontend): vitest framework bootstrap + hot-path file coverage gate
Adds the harness for component, hook and store tests on top of the existing
util tests in src/utils/. Mirrors the backend rust-tests rollout: jsdom env,
v8 coverage, soft hot-path file gate, dedicated CI workflow.
What's in:
- vitest.config.ts: jsdom environment, v8 coverage, alias @ -> src
- src/test/setup.ts: jest-dom, @testing-library cleanup, vi.mock for
@tauri-apps/api/{core,event} + plugin-shell, Map-backed Storage polyfill
for Node 25 + jsdom 26 (both ship a broken native localStorage)
- src/test/mocks/tauri.ts: programmable onInvoke() / emitTauriEvent() helpers,
auto-reset between tests
- src/test/helpers/factories.ts: makeTrack / makeTracks
- src/test/helpers/renderWithProviders.tsx: render() wrapped with
MemoryRouter + I18nextProvider
- src/test/README.md: conventions doc (where tests go, how to mock Tauri,
what to never mock)
Sample tests showing the patterns:
- src/components/CoverLightbox.test.tsx: component, queries by role
- src/store/previewStore.test.ts: store characterization, event handlers
+ stopPreview (startPreview deferred until the cross-store provider
strategy is decided)
CI:
- .github/workflows/frontend-tests.yml: jobs for vitest, tsc, coverage +
hot-path gate. coverage job carries continue-on-error: true (soft).
- .github/frontend-hot-path-files.txt: initial list (3 utils at >=70%).
playerStore + the unfinished half of previewStore are deferred until
Phase 1 coverage work lands.
- scripts/check-frontend-hot-path-coverage.sh: mirror of the rust gate.
npm scripts:
- test: one-shot run (unchanged)
- test⌚ vitest in watch mode
- test:coverage: v8 coverage + html / lcov / json-summary reports
57 / 57 tests pass; tsc --noEmit clean.
* chore(nix): sync npmDepsHash with package-lock.json
---------
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
parent
1cc43dc669
commit
02d533e949
@@ -0,0 +1,125 @@
|
||||
# Frontend test framework
|
||||
|
||||
Vitest + jsdom + @testing-library/react. Existing util tests in
|
||||
`src/utils/*.test.ts` keep working; this folder adds the harness for store,
|
||||
hook, component and (eventually) integration tests.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/test/
|
||||
setup.ts # global setup: jest-dom, @testing-library cleanup,
|
||||
# vi.mock for @tauri-apps/api/*
|
||||
mocks/
|
||||
tauri.ts # programmable invoke() + listen() helpers
|
||||
helpers/
|
||||
factories.ts # makeTrack / makeTracks fixtures
|
||||
renderWithProviders.tsx # render() wrapped with MemoryRouter + i18n
|
||||
CLAUDE.md # this file
|
||||
```
|
||||
|
||||
## Running tests
|
||||
|
||||
```bash
|
||||
npm test # one-shot run
|
||||
npm run test:watch # watch mode
|
||||
npm run test:coverage # with v8 coverage → ./coverage/
|
||||
```
|
||||
|
||||
## Where tests go
|
||||
|
||||
- **Co-located with the unit under test**: `Foo.tsx` → `Foo.test.tsx`,
|
||||
`barStore.ts` → `barStore.test.ts`. Mirrors the existing util test layout
|
||||
and avoids a parallel directory tree.
|
||||
- Vitest picks them up via `include: src/**/*.test.{ts,tsx}` in
|
||||
`vitest.config.ts`.
|
||||
|
||||
## Mocking Tauri
|
||||
|
||||
`@tauri-apps/api/core` and `@tauri-apps/api/event` are mocked globally in
|
||||
`setup.ts`. To configure per-test behaviour, import the helpers in
|
||||
`mocks/tauri.ts`:
|
||||
|
||||
```ts
|
||||
import { onInvoke, emitTauriEvent, invokeMock } from '@/test/mocks/tauri';
|
||||
|
||||
beforeEach(() => {
|
||||
onInvoke('audio_play', () => undefined);
|
||||
});
|
||||
|
||||
it('responds to engine events', () => {
|
||||
emitTauriEvent('audio:progress', { id: 't1', currentTime: 42 });
|
||||
expect(invokeMock).toHaveBeenCalledWith('audio_play', { id: 't1' });
|
||||
});
|
||||
```
|
||||
|
||||
Unhandled `invoke()` calls throw a descriptive error — tests are honest about
|
||||
which commands they exercise. Handlers are auto-cleared between tests.
|
||||
|
||||
## Mocking HTTP
|
||||
|
||||
For Subsonic / Navidrome / Last.fm calls, prefer **module-level mocks** for
|
||||
unit tests:
|
||||
|
||||
```ts
|
||||
vi.mock('@/api/subsonic', () => ({
|
||||
getAlbum: vi.fn(async () => ({ id: 'a1', tracks: [] })),
|
||||
buildStreamUrl: (id: string) => `https://mock/stream/${id}`,
|
||||
}));
|
||||
```
|
||||
|
||||
For broader integration tests that touch many endpoints we can introduce
|
||||
**MSW** later. The framework is intentionally MSW-free right now to keep
|
||||
the dep surface small until we need it.
|
||||
|
||||
## Patterns
|
||||
|
||||
### Pure utilities
|
||||
|
||||
Direct import + assert (see `src/utils/dynamicColors.test.ts`). No setup
|
||||
needed beyond `import { describe, it, expect } from 'vitest'`.
|
||||
|
||||
### Zustand stores
|
||||
|
||||
- Import the hook, drive it via `useFooStore.getState()`.
|
||||
- Reset state in a `beforeEach` — Zustand stores are module-level singletons
|
||||
and leak across tests otherwise.
|
||||
- Stub Tauri side effects via `onInvoke()`.
|
||||
- Use `emitTauriEvent()` to drive event-driven state transitions.
|
||||
|
||||
See `src/store/previewStore.test.ts` for the reference pattern.
|
||||
|
||||
### Components
|
||||
|
||||
- `renderWithProviders(<MyComponent />)` from `helpers/renderWithProviders`.
|
||||
- Query by role / label / text first; fall back to `data-testid` only when
|
||||
the DOM provides no semantic anchor.
|
||||
- Use `userEvent` (not `fireEvent`) for click / type / keyboard, with the
|
||||
exception of `keydown` on `window` for global shortcut paths.
|
||||
|
||||
See `src/components/CoverLightbox.test.tsx`.
|
||||
|
||||
### Hooks
|
||||
|
||||
Wrap in `renderHook()` from `@testing-library/react`. Provide custom
|
||||
wrappers when the hook reads from a provider.
|
||||
|
||||
## What to NOT mock
|
||||
|
||||
- **Real Zustand stores.** The whole point of characterization tests is to
|
||||
exercise the actual state graph. Mock only at the system boundary
|
||||
(Tauri / network / browser APIs).
|
||||
- **The router.** `MemoryRouter` via `renderWithProviders` is fine — don't
|
||||
stub `useNavigate` etc. unless a test specifically inspects navigation.
|
||||
- **react-i18next.** `I18nextProvider` with the real `i18n.ts` instance is
|
||||
cheap and avoids tests that lie about labels.
|
||||
|
||||
## Coverage gates
|
||||
|
||||
- `vitest run --coverage` writes `coverage/coverage-summary.json` which the
|
||||
hot-path gate consumes.
|
||||
- `.github/frontend-hot-path-files.txt` lists the files held to ≥70% line
|
||||
coverage by `scripts/check-frontend-hot-path-coverage.sh`.
|
||||
- CI runs both. The gate is currently soft (`continue-on-error: true`) —
|
||||
flip to a hard PR-blocker once a few PRs run cleanly. Mirrors the backend
|
||||
rust-tests rollout.
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Test fixture factories.
|
||||
*
|
||||
* Build minimal but valid domain objects with sensible defaults; override only
|
||||
* the fields the test cares about. Keeps tests focused on behaviour rather
|
||||
* than on assembling boilerplate.
|
||||
*/
|
||||
import type { Track } from '@/store/playerStore';
|
||||
|
||||
let trackCounter = 0;
|
||||
|
||||
export function makeTrack(overrides: Partial<Track> = {}): Track {
|
||||
trackCounter += 1;
|
||||
const id = overrides.id ?? `track-${trackCounter}`;
|
||||
return {
|
||||
id,
|
||||
title: `Track ${trackCounter}`,
|
||||
artist: 'Test Artist',
|
||||
album: 'Test Album',
|
||||
albumId: `album-${trackCounter}`,
|
||||
duration: 180,
|
||||
coverArt: id,
|
||||
...overrides,
|
||||
} as Track;
|
||||
}
|
||||
|
||||
export function makeTracks(n: number, overridesFn?: (i: number) => Partial<Track>): Track[] {
|
||||
return Array.from({ length: n }, (_, i) => makeTrack(overridesFn?.(i) ?? {}));
|
||||
}
|
||||
|
||||
export function resetFactoryCounters(): void {
|
||||
trackCounter = 0;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Wraps `render()` from @testing-library/react with the providers most
|
||||
* Psysonic components need: a router (for hooks like useNavigate / useParams)
|
||||
* and i18n (for components that call `useTranslation`).
|
||||
*
|
||||
* Tests that don't need a specific route can call `renderWithProviders(<X />)`.
|
||||
* Tests that need a specific URL pass `{ route: '/album/42' }`.
|
||||
*/
|
||||
import type { ReactElement, ReactNode } from 'react';
|
||||
import { render, type RenderOptions, type RenderResult } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import i18n from '@/i18n';
|
||||
|
||||
interface WrapperOptions {
|
||||
route?: string;
|
||||
}
|
||||
|
||||
function makeWrapper({ route = '/' }: WrapperOptions) {
|
||||
return function Wrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>
|
||||
</I18nextProvider>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export function renderWithProviders(
|
||||
ui: ReactElement,
|
||||
options: WrapperOptions & Omit<RenderOptions, 'wrapper'> = {},
|
||||
): RenderResult {
|
||||
const { route, ...rest } = options;
|
||||
return render(ui, { wrapper: makeWrapper({ route }), ...rest });
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Tauri test harness — programmable `invoke()` + `listen()` mocks.
|
||||
*
|
||||
* Usage in a test:
|
||||
*
|
||||
* import { onInvoke, emitTauriEvent } from '@/test/mocks/tauri';
|
||||
*
|
||||
* beforeEach(() => {
|
||||
* onInvoke('audio_play', () => undefined);
|
||||
* onInvoke('audio_get_state', () => ({ playing: true }));
|
||||
* });
|
||||
*
|
||||
* it('emits progress', () => {
|
||||
* emitTauriEvent('audio:progress', { id: 't1', currentTime: 42 });
|
||||
* });
|
||||
*
|
||||
* Handlers are auto-cleared between tests (`beforeEach` hook below).
|
||||
* Unhandled invokes throw — keeps tests honest about which commands they touch.
|
||||
*/
|
||||
import { beforeEach, vi } from 'vitest';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
|
||||
export type InvokeHandler = (args: unknown) => unknown | Promise<unknown>;
|
||||
export type EventCallback = (payload: unknown) => void;
|
||||
|
||||
const invokeHandlers = new Map<string, InvokeHandler>();
|
||||
const eventListeners = new Map<string, EventCallback[]>();
|
||||
|
||||
// Tauri's typed signatures are strict (InvokeArgs / Event<T>). Tests don't
|
||||
// need that level of precision — cast the mocks to `any` so the helpers
|
||||
// accept simple `{ payload }` envelopes and plain object args.
|
||||
const invokeMock = vi.mocked(invoke) as unknown as ReturnType<typeof vi.fn>;
|
||||
const listenMock = vi.mocked(listen) as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
invokeMock.mockImplementation(async (cmd: string, args?: unknown) => {
|
||||
const handler = invokeHandlers.get(cmd);
|
||||
if (!handler) {
|
||||
throw new Error(
|
||||
`Unhandled invoke('${cmd}'). Register via onInvoke('${cmd}', …) in the test.`,
|
||||
);
|
||||
}
|
||||
return await handler(args);
|
||||
});
|
||||
|
||||
listenMock.mockImplementation(
|
||||
async (event: string, cb: (e: { payload: unknown }) => void) => {
|
||||
const wrapped: EventCallback = (payload) =>
|
||||
cb({ payload } as { payload: unknown });
|
||||
const arr = eventListeners.get(event) ?? [];
|
||||
arr.push(wrapped);
|
||||
eventListeners.set(event, arr);
|
||||
return () => {
|
||||
const list = eventListeners.get(event);
|
||||
if (!list) return;
|
||||
const i = list.indexOf(wrapped);
|
||||
if (i >= 0) list.splice(i, 1);
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
/** Register a handler for `invoke('<cmd>', …)`. Last-write-wins per command. */
|
||||
export function onInvoke(cmd: string, handler: InvokeHandler): void {
|
||||
invokeHandlers.set(cmd, handler);
|
||||
}
|
||||
|
||||
/** Synchronously deliver an `<event>` payload to every active listener. */
|
||||
export function emitTauriEvent(event: string, payload: unknown): void {
|
||||
for (const cb of eventListeners.get(event) ?? []) cb(payload);
|
||||
}
|
||||
|
||||
/** Clear all handlers + listeners + call counts. Wired to `beforeEach` below. */
|
||||
export function resetTauriMocks(): void {
|
||||
invokeHandlers.clear();
|
||||
eventListeners.clear();
|
||||
invokeMock.mockClear();
|
||||
listenMock.mockClear();
|
||||
}
|
||||
|
||||
export { invokeMock, listenMock };
|
||||
|
||||
beforeEach(resetTauriMocks);
|
||||
@@ -0,0 +1,100 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { afterEach, vi } from 'vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Node 25 ships a native `localStorage` global that is broken on this
|
||||
// platform — `typeof localStorage === 'object'` but `localStorage.getItem`
|
||||
// is `undefined`. jsdom 26 simply forwards to it, so both globalThis and
|
||||
// window expose a non-functional storage. Any code that runs
|
||||
// `localStorage.getItem(...)` at module load (e.g. `i18n.ts`, `authStore.ts`)
|
||||
// crashes before tests start.
|
||||
//
|
||||
// Fix: install a Map-backed polyfill that conforms to the DOM Storage
|
||||
// interface, on both globalThis and window. Per-test isolation comes from
|
||||
// the `afterEach(() => store.clear())` hook below.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
class MemoryStorage implements Storage {
|
||||
private map = new Map<string, string>();
|
||||
get length(): number {
|
||||
return this.map.size;
|
||||
}
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.map.keys())[index] ?? null;
|
||||
}
|
||||
getItem(key: string): string | null {
|
||||
return this.map.has(key) ? (this.map.get(key) as string) : null;
|
||||
}
|
||||
setItem(key: string, value: string): void {
|
||||
this.map.set(String(key), String(value));
|
||||
}
|
||||
removeItem(key: string): void {
|
||||
this.map.delete(String(key));
|
||||
}
|
||||
clear(): void {
|
||||
this.map.clear();
|
||||
}
|
||||
}
|
||||
|
||||
const memLocal = new MemoryStorage();
|
||||
const memSession = new MemoryStorage();
|
||||
|
||||
function installStorage(globalKey: 'localStorage' | 'sessionStorage', store: Storage) {
|
||||
try {
|
||||
Object.defineProperty(globalThis, globalKey, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: store,
|
||||
});
|
||||
} catch {
|
||||
/* ignore — non-configurable global */
|
||||
}
|
||||
if (typeof window !== 'undefined') {
|
||||
try {
|
||||
Object.defineProperty(window, globalKey, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: store,
|
||||
});
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
installStorage('localStorage', memLocal);
|
||||
installStorage('sessionStorage', memSession);
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Global Tauri mocks.
|
||||
//
|
||||
// Every test file that imports `@tauri-apps/api/core` or `@tauri-apps/api/event`
|
||||
// gets these stubs. They start as bare `vi.fn()`s; the helpers in
|
||||
// `src/test/mocks/tauri.ts` attach programmable implementations the first time
|
||||
// they are imported by a test file. Tests that don't need Tauri can ignore
|
||||
// the helpers entirely.
|
||||
//
|
||||
// We mock here (in setupFiles) rather than per-test-file so individual tests
|
||||
// don't have to repeat `vi.mock('@tauri-apps/api/core', …)` boilerplate.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
vi.mock('@tauri-apps/api/core', () => ({
|
||||
invoke: vi.fn(),
|
||||
convertFileSrc: vi.fn((p: string) => `tauri://localhost/${p}`),
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/api/event', () => ({
|
||||
listen: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
once: vi.fn(),
|
||||
}));
|
||||
|
||||
// Linker for Tauri shell / dialog / store plugins — same idea. Extend as needed.
|
||||
vi.mock('@tauri-apps/plugin-shell', () => ({
|
||||
open: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
memLocal.clear();
|
||||
memSession.clear();
|
||||
});
|
||||
Reference in New Issue
Block a user