Add unit and integration test suites

- Shared: link building, feed ordering, input schemas, API client
- API unit: track matching, private-address blocking, token crypto,
  plan expiry, provider response parsing
- API integration against Postgres and Redis: auth, follows and pins,
  now-playing state, webhooks, OAuth return URLs, realtime, rate limits
- Tests use a dedicated *_test database and Redis DB, and refuse to wipe
  anything else; fetch is stubbed so they never hit the network
- Pin Node to 22.13+ (.nvmrc), which Vite's native bindings require

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzFywujuH9TiuXbr9vjoX8
This commit is contained in:
2026-10-03 11:28:17 -04:00
co-authored by Claude Opus 5.5
parent 95cd740e51
commit fe503307df
29 changed files with 3281 additions and 10 deletions
+43
View File
@@ -0,0 +1,43 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { ApiError, createApiClient } from './client';
function stubFetch(status: number, body: unknown) {
const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => new Response(JSON.stringify(body), { status }));
vi.stubGlobal('fetch', fetchMock);
return fetchMock;
}
afterEach(() => vi.unstubAllGlobals());
describe('createApiClient', () => {
it('sends the bearer token and JSON body', async () => {
const fetchMock = stubFetch(200, { ok: true });
const api = createApiClient({ baseUrl: 'https://api.test', getToken: () => 'tok' });
await api.connectUsername('lastfm', 'rj');
const [url, init] = fetchMock.mock.calls[0]!;
expect(url).toBe('https://api.test/connections/lastfm');
expect(init?.method).toBe('POST');
expect(init?.headers).toMatchObject({ Authorization: 'Bearer tok', 'Content-Type': 'application/json' });
expect(JSON.parse(init?.body as string)).toEqual({ username: 'rj' });
});
it('omits auth when there is no token and encodes path segments', async () => {
const fetchMock = stubFetch(200, {});
const api = createApiClient({ baseUrl: 'https://api.test', credentials: 'include' });
await api.profile('a/b');
const [url, init] = fetchMock.mock.calls[0]!;
expect(url).toBe('https://api.test/users/a%2Fb');
expect(init?.headers).not.toHaveProperty('Authorization');
expect(init?.credentials).toBe('include');
});
it('throws ApiError with the server message and status', async () => {
stubFetch(402, { error: 'You can pin up to 3 friends on your plan' });
const api = createApiClient({ baseUrl: 'https://api.test' });
const err = await api.pin('bob').catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect(err).toMatchObject({ status: 402, message: 'You can pin up to 3 friends on your plan' });
});
});
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest';
import { sortFeed, type FeedItemDTO } from './dto';
function item(username: string, opts: { pinnedAt?: string; isPlaying?: boolean; updatedAt?: string }): FeedItemDTO {
return {
user: { id: username, username, displayName: null, avatarUrl: null },
track: { id: 't', title: 't', artist: 'a', album: null, artworkUrl: null, durationMs: null, isrc: null, links: {} },
isPlaying: opts.isPlaying ?? false,
source: 'spotify',
progressMs: null,
updatedAt: opts.updatedAt ?? '2026-01-01T00:00:00.000Z',
pinnedAt: opts.pinnedAt ?? null,
};
}
const names = (items: FeedItemDTO[]) => items.map((i) => i.user.username);
describe('sortFeed', () => {
it('puts pinned friends first, in the order they were pinned', () => {
const feed = sortFeed([
item('live', { isPlaying: true }),
item('pinnedSecond', { pinnedAt: '2026-01-02T00:00:00.000Z' }),
item('pinnedFirst', { pinnedAt: '2026-01-01T00:00:00.000Z' }),
]);
expect(names(feed)).toEqual(['pinnedFirst', 'pinnedSecond', 'live']);
});
it('then live listeners, then most recently updated', () => {
const feed = sortFeed([
item('old', { updatedAt: '2026-01-01T00:00:00.000Z' }),
item('recent', { updatedAt: '2026-01-03T00:00:00.000Z' }),
item('live', { isPlaying: true, updatedAt: '2025-12-01T00:00:00.000Z' }),
]);
expect(names(feed)).toEqual(['live', 'recent', 'old']);
});
it('does not mutate its input', () => {
const input = [item('b', {}), item('a', { isPlaying: true })];
sortFeed(input);
expect(names(input)).toEqual(['b', 'a']);
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { registerSchema, setFeaturedSchema, updateMeSchema } from './schemas';
describe('registerSchema', () => {
it('normalizes username and email', () => {
const parsed = registerSchema.parse({ username: ' Alice_1 ', email: ' Alice@Example.COM ', password: 'password123' });
expect(parsed).toMatchObject({ username: 'alice_1', email: 'alice@example.com' });
});
it.each(['ab', 'has space', 'émoji', 'a'.repeat(33)])('rejects username %j', (username) => {
expect(registerSchema.safeParse({ username, email: 'a@b.co', password: 'password123' }).success).toBe(false);
});
it('requires 8+ character passwords', () => {
const result = registerSchema.safeParse({ username: 'alice', email: 'a@b.co', password: 'short' });
expect(result.success).toBe(false);
});
});
describe('updateMeSchema', () => {
it('only accepts known streaming services', () => {
expect(updateMeSchema.safeParse({ preferredService: 'spotify' }).success).toBe(true);
expect(updateMeSchema.safeParse({ preferredService: 'napster' }).success).toBe(false);
});
});
describe('setFeaturedSchema', () => {
it('accepts a Deezer id or an existing track id', () => {
expect(setFeaturedSchema.safeParse({ deezerId: '3135553' }).success).toBe(true);
expect(setFeaturedSchema.safeParse({ trackId: '7ce84c24-e5d2-4af7-8d9c-4424ff70c373' }).success).toBe(true);
});
it('caps comments at 280 characters', () => {
expect(setFeaturedSchema.safeParse({ deezerId: '1', comment: 'x'.repeat(281) }).success).toBe(false);
});
});
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest';
import { STREAMING_SERVICES, openUrl, searchUrl } from './services';
const track = { title: 'Midnight City', artist: 'M83', links: { spotify: 'https://open.spotify.com/track/abc' } };
describe('openUrl', () => {
it('uses the direct link when the service has one', () => {
expect(openUrl(track, 'spotify')).toEqual({ url: 'https://open.spotify.com/track/abc', exact: true });
});
it('falls back to a search on that service', () => {
const result = openUrl(track, 'apple_music');
expect(result.exact).toBe(false);
expect(result.url).toBe('https://music.apple.com/search?term=M83%20Midnight%20City');
});
});
describe('searchUrl', () => {
it.each(STREAMING_SERVICES)('builds an https URL for %s with the query encoded', (service) => {
const url = new URL(searchUrl(service, 'Café & Co', 'Ünïcode'));
expect(url.protocol).toBe('https:');
expect(decodeURIComponent(url.href)).toContain('Ünïcode Café & Co');
});
});
+20
View File
@@ -0,0 +1,20 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { timeAgo } from './time';
describe('timeAgo', () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-10-03T12:00:00Z'));
});
afterEach(() => vi.useRealTimers());
it.each([
['2026-10-03T11:59:30Z', 'just now'],
['2026-10-03T11:55:00Z', '5m ago'],
['2026-10-03T09:00:00Z', '3h ago'],
['2026-09-30T12:00:00Z', '3d ago'],
['2026-10-03T12:00:10Z', 'just now'], // slight clock skew into the future
])('%s → %s', (iso, expected) => {
expect(timeAgo(iso)).toBe(expected);
});
});