Files
LivingDexTracker/tests/integration/defaultForm.integration.test.ts
T
Josh Creek 4af33709a3 test: make the suite's assertions falsifiable and its state isolated
Several assertions could not fail:

- "the catch update remains saved" was `caught.isChecked() || notes.includes(...)`
  shared by two scenarios, so either half satisfied both. Split into two steps
  that each assert the outcome their own scenario is about.
- The token-refresh check read a global counter with `> 0` and asserted an upload
  had happened `some(...)`, both already satisfied by the preceding scenario. It
  now asserts exactly one refresh, ordered before the upload.
- The box step ignored its box argument and asserted on the first N entries on
  the page; it now scopes to that box and checks its full contents.
- The filter step asserted on whichever entry was first after filtering; it now
  records the caught entry beforehand and names it, and checks the filter did not
  exclude everything.
- The empty-state precondition asserted emptiness instead of establishing it,
  which a fresh user satisfies for free.
- Offline coverage was `caches.keys().length > 0`. It now checks the precache
  contract: one workbox cache holding the shell and a revisioned web manifest,
  with _app/immutable assets cached without a revision query. The scenario that
  claimed to test a trailing slash did not; it is replaced with real offline
  client-side navigation.

The mock provider kept recorded requests, its refresh counter and the
fail-uploads switch in one process-wide object that only one step reset, so
scenario order was load-bearing and the failing-upload scenario poisoned
everything after it. An auto fixture now resets it per scenario, and the mock no
longer records its own control-plane calls. That reset is why the suite stays on
a single worker, which is now documented.

Coverage was gated at 90% per file over an allowlist of exactly the five files
that had tests, so new code was invisible to it permanently. It now measures all
of src/lib with global thresholds at the measured baseline, and no longer runs
the unit tests twice.

Also: a global teardown removes the users each run creates, the Supabase wrapper
distinguishes a stopped stack from a broken CLI call and detects an unseeded
database, the sign-in rate limit is raised above what one serial run needs, and
the integration suite no longer falls back to a hard-coded anon key that would
mask a misconfigured run.

The password-reset scenarios are renamed to what they actually cover: following a
real recovery link bounces to /signin, because the browser client persists no
cookies and so cannot keep the session it parses out of the URL. The helper for
the real flow is left in place and the gap is documented.
2026-09-13 17:38:42 +01:00

187 lines
6.9 KiB
TypeScript

import { describe, it, expect, beforeAll } from 'vitest';
import { createClient, type SupabaseClient } from '@supabase/supabase-js';
import CombinedDataRepository from '$lib/repositories/CombinedDataRepository';
import { readRepoCsv } from '../support/csv';
/**
* Black-box data and repository regressions. These tests deliberately use only the schema
* available before the fix: on master they load normally and fail on behavior, while the
* fix branch makes the same assertions pass without test-only schema knowledge.
*/
const SUPABASE_URL = process.env.TEST_SUPABASE_URL ?? 'http://127.0.0.1:54321';
const SETUP_HINT =
'Run integration tests through "npm run test:integration", which reads the local keys from "supabase status".';
// No baked-in key: a fallback would silently point a misconfigured run at the wrong stack
// instead of failing with the instruction above.
function requireAnonKey(): string {
const key = process.env.TEST_SUPABASE_ANON_KEY;
if (!key) throw new Error(`Integration tests require TEST_SUPABASE_ANON_KEY. ${SETUP_HINT}`);
return key;
}
async function requireSupabase() {
const key = requireAnonKey();
try {
const res = await fetch(`${SUPABASE_URL}/rest/v1/pokedex_entries?select=id&limit=1`, {
headers: { apikey: key, Authorization: `Bearer ${key}` },
signal: AbortSignal.timeout(2000)
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
} catch (error) {
throw new Error(
`Local Supabase is required for integration tests at ${SUPABASE_URL}. Run "npm run supabase:start" and "npm run supabase:reset" first. ${String(error)}`
);
}
}
type Row = {
id: number;
pokedexNumber: number;
pokemon: string;
form: string | null;
spriteKey: string | null;
isDefaultForm: boolean;
notes: string | null;
};
describe('pokedex behavior regressions', () => {
let supabase: SupabaseClient;
let rows: Row[];
beforeAll(async () => {
await requireSupabase();
supabase = createClient(SUPABASE_URL, requireAnonKey());
const all: Row[] = [];
for (let from = 0; ; from += 1000) {
const { data, error } = await supabase
.from('pokedex_entries')
.select('id, pokedexNumber, pokemon, form, spriteKey, isDefaultForm, notes')
.order('id', { ascending: true })
.range(from, from + 999);
if (error) throw new Error(error.message);
if (!data?.length) break;
all.push(...(data as Row[]));
if (data.length < 1000) break;
}
rows = all;
});
it('returns one canonical representative for species whose forms are all named', async () => {
const repo = new CombinedDataRepository(supabase, null, null);
const entries = (await repo.findAllCombinedData('', false)).map((item) => item.pokedexEntry);
for (const [species, form] of Object.entries({
Basculin: 'Red-striped',
Tornadus: 'Incarnate Form',
Oricorio: 'Baile (Red)',
Zygarde: '50%',
Gimmighoul: 'Box Form',
Rotom: 'Lightbulb'
})) {
const found = entries.filter((entry) => entry.pokemon === species);
expect(found, `${species} should appear exactly once`).toHaveLength(1);
expect(found[0].form).toBe(form);
}
expect(entries.filter((entry) => entry.pokemon === 'Beautifly').map((e) => e.form)).toEqual([
'male'
]);
expect(entries.filter((entry) => entry.pokemon === 'Unown').map((e) => e.form)).toEqual(['A']);
});
it('returns every alternate form exactly once when forms are enabled', async () => {
const repo = new CombinedDataRepository(supabase, null, null);
const entries = (await repo.findAllCombinedData('', true)).map((item) => item.pokedexEntry);
expect(
entries
.filter((entry) => entry.pokemon === 'Basculin')
.map((entry) => entry.form)
.sort()
).toEqual(['Blue-striped', 'Red-striped', 'White-striped']);
expect(entries.filter((entry) => entry.pokemon === 'Alcremie')).toHaveLength(63);
expect(entries.filter((entry) => entry.pokemon === 'Unown')).toHaveLength(28);
expect(new Set(entries.map((entry) => entry._id)).size).toBe(entries.length);
});
it('keeps named default forms in a game-scoped form dex without duplicates', async () => {
const repo = new CombinedDataRepository(supabase, null, null);
const rotom = (await repo.findAllCombinedData('', true, '', 'Black', ['black-unova']))
.map((item) => item.pokedexEntry)
.filter((entry) => entry.pokemon === 'Rotom');
expect(rotom.map((entry) => entry.form)).toContain('Lightbulb');
expect(rotom).toHaveLength(6);
expect(new Set(rotom.map((entry) => entry._id)).size).toBe(rotom.length);
});
it('uses the correct national dex numbers and sprite for corrected rows', () => {
const wyrdeer = rows.find((row) => row.pokemon === 'Wyrdeer');
expect(wyrdeer).toMatchObject({ pokedexNumber: 899, spriteKey: '899' });
expect(rows.find((row) => row.pokemon === 'Gimmighoul')?.pokedexNumber).toBe(999);
expect(
rows.find((row) => row.pokemon === 'Ursaluna' && row.form === 'Bloodmoon')?.pokedexNumber
).toBe(901);
});
it('returns every expected entry despite the PostgREST row cap', async () => {
const { calculateExpectedEntries } = await import('$lib/services/PokedexMappingService');
const baseDex = {
id: 'test',
name: 'test',
isLivingDex: true,
isShinyDex: false,
isOriginDex: false,
isFormDex: false,
gameScope: null,
dexScopes: []
};
const baseIds = await calculateExpectedEntries(supabase, baseDex as never);
const formIds = await calculateExpectedEntries(supabase, {
...baseDex,
isFormDex: true
} as never);
expect(baseIds).toHaveLength(1025);
expect(new Set(baseIds).size).toBe(baseIds.length);
expect(formIds).toHaveLength(rows.length);
expect(new Set(formIds).size).toBe(formIds.length);
});
it('keeps the tracked CSV synchronized with the database', () => {
const fromCsv = new Map(
readRepoCsv('data/csvs/pokemon.csv').map((row) => [
`${row.pokemon}|${row.form}`,
row.pokedexNumber
])
);
const fromDb = new Map(
rows.map((row) => [`${row.pokemon}|${row.form ?? ''}`, String(row.pokedexNumber)])
);
expect({
onlyInCsv: [...fromCsv.keys()].filter((key) => !fromDb.has(key)),
onlyInDb: [...fromDb.keys()].filter((key) => !fromCsv.has(key)),
differing: [...fromCsv.entries()]
.filter(([key, value]) => fromDb.has(key) && fromDb.get(key) !== value)
.map(([key, value]) => `${key}: csv ${value} vs db ${fromDb.get(key)}`)
}).toEqual({ onlyInCsv: [], onlyInDb: [], differing: [] });
});
it('projects exactly one default form per species through the public view', () => {
const bySpecies = new Map<string, Row[]>();
for (const row of rows)
bySpecies.set(row.pokemon, [...(bySpecies.get(row.pokemon) ?? []), row]);
const invalid = [...bySpecies]
.filter(([, entries]) => entries.filter((entry) => entry.isDefaultForm).length !== 1)
.map(([species, entries]) => ({
species,
defaults: entries.filter((entry) => entry.isDefaultForm).map((entry) => entry.form)
}));
expect(invalid).toEqual([]);
expect(rows[0]).toHaveProperty('notes');
});
});