Compare commits

...
Author SHA1 Message Date
Claude 42f897b7df Add test scaffolding and Tier 1 + migration test suite
Set up Vitest with a jsdom-based harness that loads the real index.html
so the shipped game logic is testable without refactoring the single-file
app. Adds 40 tests covering the highest-risk code:

- Scoring rules: base-running advancement, forced advances on walks,
  run/RBI crediting, substitution-aware stats, game-over and walk-off
  detection.
- migrateGame(): the single source of truth for backward-compatible
  loading of older saved/imported games.

https://claude.ai/code/session_01NQDAZBpAV6Q283Dm2e4wJM
2026-05-31 01:28:27 +00:00
8 changed files with 2495 additions and 1 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
node_modules/
coverage/
*.log
+26 -1
View File
@@ -1 +1,26 @@
# baseballscorecard
# baseballscorecard
A single-file baseball scorecard web app. The entire app — markup, styles, and
logic — lives in [`index.html`](index.html); just open it in a browser.
## Tests
The game-logic and schema-migration code is covered by a small
[Vitest](https://vitest.dev/) suite. The tests load the real `index.html` into a
[jsdom](https://github.com/jsdom/jsdom) window (see
`test/helpers/loadApp.js`), so they exercise the shipped code directly with no
build step or refactor required.
```sh
npm install # one-time
npm test # run the suite once
npm run test:watch
```
Current coverage focuses on the highest-risk pure logic:
- **Scoring rules** (`test/game-logic.test.js`): base-running advancement,
forced advances on walks, run/RBI crediting, substitution-aware stats, and
game-end / walk-off detection.
- **Schema migrations** (`test/migrate.test.js`): `migrateGame()`, the single
source of truth for loading older saved/imported games.
+2062
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
{
"name": "baseballscorecard",
"version": "1.0.0",
"description": "A single-file baseball scorecard web app",
"private": true,
"type": "module",
"scripts": {
"test": "vitest run",
"test:watch": "vitest"
},
"devDependencies": {
"jsdom": "^25.0.1",
"vitest": "^4.1.7"
}
}
+226
View File
@@ -0,0 +1,226 @@
// Tier 1 — pure game-logic tests.
//
// These exercise the scoring "rules engine": base-running advancement, run/RBI
// crediting, runner lookup, sub-aware stat selection, and game-end detection.
// Each test gets a fresh app instance (own window + own G) via loadApp().
import { describe, it, expect, beforeEach } from 'vitest';
import { loadApp } from './helpers/loadApp.js';
let w; // the loaded app window — functions and G live here
beforeEach(() => {
w = loadApp();
});
describe('advanceRunners', () => {
it('moves runners forward by N bases without overwriting', () => {
// Runners on 1B and 3B, advance everyone 1 base.
w.G.bases = ['R1', null, 'R3'];
const runs = w.advanceRunners('away', 1);
// R3 scores; R1 -> 2B.
expect(runs).toBe(1);
expect(w.G.bases).toEqual([null, 'R1', null]);
});
it('processes 3B -> 1B so a trailing runner never clobbers a lead runner', () => {
// Bases loaded, advance 1: the 3B->2B->1B order matters or names get lost.
w.G.bases = ['R1', 'R2', 'R3'];
const runs = w.advanceRunners('away', 1);
expect(runs).toBe(1); // R3 scores
expect(w.G.bases).toEqual([null, 'R1', 'R2']);
});
it('scores every runner on a multi-base advance (e.g. HR with two on)', () => {
w.G.bases = ['R1', null, 'R3'];
const runs = w.advanceRunners('away', 4); // grand-slam-style clearing
expect(runs).toBe(2);
expect(w.G.bases).toEqual([null, null, null]);
});
it('updates the running total and the current inning line score', () => {
w.G.inning = 3;
w.G.bases = [null, null, 'R3'];
w.advanceRunners('away', 1);
expect(w.G.rhe.away[0]).toBe(1);
expect(w.G.scores.away[2]).toBe(1); // inning 3 -> index 2
});
});
describe('forceAdvance (walks / HBP / IBB)', () => {
it('puts the batter on 1B with the bases empty and forces no one', () => {
w.G.bases = [null, null, null];
const runs = w.forceAdvance('away', 'Batter');
expect(runs).toBe(0);
expect(w.G.bases).toEqual(['Batter', null, null]);
});
it('forces in a run only when the bases are loaded', () => {
w.G.inning = 1;
w.G.bases = ['R1', 'R2', 'R3'];
const runs = w.forceAdvance('away', 'Batter');
expect(runs).toBe(1); // R3 forced home
expect(w.G.bases).toEqual(['Batter', 'R1', 'R2']);
expect(w.G.rhe.away[0]).toBe(1);
});
it('does NOT advance a non-forced runner (runner on 2B only)', () => {
// Classic rule: with 1B open, the runner on 2B is not forced on a walk.
w.G.bases = [null, 'R2', null];
const runs = w.forceAdvance('away', 'Batter');
expect(runs).toBe(0);
expect(w.G.bases).toEqual(['Batter', 'R2', null]);
});
it('advances the chain up to the first open base (runner on 1B only)', () => {
w.G.bases = ['R1', null, null];
const runs = w.forceAdvance('away', 'Batter');
expect(runs).toBe(0);
expect(w.G.bases).toEqual(['Batter', 'R1', null]);
});
});
describe('findRunnerSlot', () => {
beforeEach(() => {
w.G.lineup.away[0].name = 'Alice';
w.G.lineup.away[3].name = 'Bob';
});
it('finds a runner by current lineup name', () => {
expect(w.findRunnerSlot('away', 'Alice')).toBe(0);
expect(w.findRunnerSlot('away', 'Bob')).toBe(3);
});
it('returns -1 for unknown / sentinel runner values', () => {
expect(w.findRunnerSlot('away', 'Nobody')).toBe(-1);
expect(w.findRunnerSlot('away', '?')).toBe(-1);
expect(w.findRunnerSlot('away', null)).toBe(-1);
expect(w.findRunnerSlot('away', true)).toBe(-1);
});
});
describe('creditRun / creditRBI', () => {
it('credits the run to the slot of the runner who scored', () => {
w.G.lineup.away[2].name = 'Scorer';
w.creditRun('away', 'Scorer');
expect(w.activeHits('away', 2).r).toBe(1);
});
it('does not throw and credits nothing for an unknown runner', () => {
const before = w.G.lineup.away.map((s) => s.hits.r);
expect(() => w.creditRun('away', 'Ghost')).not.toThrow();
expect(w.G.lineup.away.map((s) => s.hits.r)).toEqual(before);
});
it('credits RBI(s) to the current batter', () => {
w.G.awayBatter = 4;
w.creditRBI('away', 2);
expect(w.activeHits('away', 4).rbi).toBe(2);
});
it('ignores zero / negative RBI counts', () => {
w.G.awayBatter = 1;
w.creditRBI('away', 0);
w.creditRBI('away', -3);
expect(w.activeHits('away', 1).rbi).toBe(0);
});
});
describe('activeHits (substitution-aware)', () => {
it('returns the starter hits object when there are no subs', () => {
expect(w.activeHits('home', 0)).toBe(w.G.lineup.home[0].hits);
});
it('returns the latest sub hits object once a sub exists', () => {
const sub = w.mkSlot();
sub.name = 'Pinch';
w.G.lineup.home[0].subs.push(sub);
expect(w.activeHits('home', 0)).toBe(sub.hits);
});
});
describe('isGameOver', () => {
const setState = (over) => Object.assign(w.G, over);
it('is not over before the 9th inning', () => {
setState({ inning: 8, half: 'bot', outs: 3 });
w.G.rhe.home[0] = 5;
w.G.rhe.away[0] = 3;
expect(w.isGameOver()).toBe(false);
});
it('ends after the bottom of the 9th when not tied', () => {
setState({ inning: 9, half: 'bot', outs: 3 });
w.G.rhe.home[0] = 5;
w.G.rhe.away[0] = 3;
expect(w.isGameOver()).toBe(true);
});
it('continues into extras when tied after the bottom of the 9th', () => {
setState({ inning: 9, half: 'bot', outs: 3 });
w.G.rhe.home[0] = 3;
w.G.rhe.away[0] = 3;
expect(w.isGameOver()).toBe(false);
});
it('ends after the top of the 9th if the home team already leads', () => {
setState({ inning: 9, half: 'top', outs: 3 });
w.G.rhe.home[0] = 5;
w.G.rhe.away[0] = 3;
expect(w.isGameOver()).toBe(true);
});
it('requires the bottom of the 9th if the home team trails after the top', () => {
setState({ inning: 9, half: 'top', outs: 3 });
w.G.rhe.home[0] = 3;
w.G.rhe.away[0] = 5;
expect(w.isGameOver()).toBe(false);
});
it('is not over mid-inning (fewer than 3 outs)', () => {
setState({ inning: 9, half: 'bot', outs: 2 });
w.G.rhe.home[0] = 5;
w.G.rhe.away[0] = 3;
expect(w.isGameOver()).toBe(false);
});
});
describe('checkWalkoff', () => {
it('flags a walk-off when the home team takes the lead in the bottom 9th+', () => {
Object.assign(w.G, { inning: 9, half: 'bot' });
w.G.rhe.home[0] = 4;
w.G.rhe.away[0] = 3;
expect(w.checkWalkoff()).toBe(true);
});
it('is not a walk-off when the game is still tied', () => {
Object.assign(w.G, { inning: 9, half: 'bot' });
w.G.rhe.home[0] = 3;
w.G.rhe.away[0] = 3;
expect(w.checkWalkoff()).toBe(false);
});
it('never fires in the top half of an inning', () => {
Object.assign(w.G, { inning: 9, half: 'top' });
w.G.rhe.home[0] = 4;
w.G.rhe.away[0] = 3;
expect(w.checkWalkoff()).toBe(false);
});
it('never fires before the 9th inning', () => {
Object.assign(w.G, { inning: 7, half: 'bot' });
w.G.rhe.home[0] = 4;
w.G.rhe.away[0] = 3;
expect(w.checkWalkoff()).toBe(false);
});
});
describe('recalc', () => {
it('sums the inning line scores into the R total for each side', () => {
w.G.scores.home = [1, 0, 2, null, 0, null, null, null, 1];
w.G.scores.away = [0, 0, 0, 0, 0, 0, 0, 0, 0];
w.recalc();
expect(w.G.rhe.home[0]).toBe(4);
expect(w.G.rhe.away[0]).toBe(0);
});
});
+31
View File
@@ -0,0 +1,31 @@
// Test harness for the single-file baseball scorecard app.
//
// The whole app lives in index.html as inline <script>. Rather than refactor it
// into modules, we load the real file into a jsdom window with scripts enabled.
// Every top-level `function foo(){}` and `var x` in that script becomes a
// property of the jsdom `window`, so tests can call the real game-logic
// functions (window.advanceRunners, window.migrateGame, ...) and read/mutate the
// real game state (window.G) exactly as the app does in a browser.
//
// init() runs on load. On a fresh DOM no team is selected, so init() never hits
// the network (fetch/StatsAPI) — it only touches the DOM, which jsdom provides.
import { JSDOM } from 'jsdom';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const __dirname = dirname(fileURLToPath(import.meta.url));
const HTML_PATH = join(__dirname, '..', '..', 'index.html');
const HTML = readFileSync(HTML_PATH, 'utf8');
// Load a fresh, fully-initialized copy of the app. Each call is isolated:
// a new jsdom window with its own DOM, its own `G`, and its own localStorage.
export function loadApp() {
const dom = new JSDOM(HTML, {
runScripts: 'dangerously',
pretendToBeVisual: true, // provides requestAnimationFrame
url: 'http://localhost/',
});
return dom.window;
}
+122
View File
@@ -0,0 +1,122 @@
// Tier 2 — schema migration tests.
//
// migrateGame() is documented in index.html as "the SINGLE source of truth for
// backward compatibility". Every saved/imported game flows through it, so a
// regression here silently corrupts (or fails to load) real user data. These
// tests feed it old-shape fixtures and assert it backfills the current shape.
import { describe, it, expect, beforeEach } from 'vitest';
import { loadApp } from './helpers/loadApp.js';
let w;
beforeEach(() => {
w = loadApp();
});
describe('migrateGame — defensive guards', () => {
it('returns falsy input untouched', () => {
expect(w.migrateGame(null)).toBe(null);
expect(w.migrateGame(undefined)).toBe(undefined);
});
it('mutates and returns the same object', () => {
const g = {};
expect(w.migrateGame(g)).toBe(g);
});
});
describe('migrateGame — v1 -> v2 (batterLog)', () => {
it('adds a batterLog with both sides when missing', () => {
const g = w.migrateGame({});
expect(g.batterLog).toEqual({ home: {}, away: {} });
});
it('fills in a missing side without dropping existing data', () => {
const g = w.migrateGame({ batterLog: { home: { 0: 'X' } } });
expect(g.batterLog.home).toEqual({ 0: 'X' });
expect(g.batterLog.away).toEqual({});
});
});
describe('migrateGame — v2 -> v3 (notes) and v3 -> v4 (abs)', () => {
it('adds a notes object with the expected default keys', () => {
const g = w.migrateGame({});
expect(g.notes).toBeTypeOf('object');
expect(g.notes).toMatchObject({ date: '', venue: '', weather: '' });
});
it('adds ABS challenge tracking for both sides', () => {
const g = w.migrateGame({});
expect(g.abs).toEqual({
home: { challenged: 0, overturned: 0 },
away: { challenged: 0, overturned: 0 },
});
});
it('repairs a partially-present abs object', () => {
const g = w.migrateGame({ abs: { home: { challenged: 2, overturned: 1 } } });
expect(g.abs.home).toEqual({ challenged: 2, overturned: 1 });
expect(g.abs.away).toEqual({ challenged: 0, overturned: 0 });
});
});
describe('migrateGame — bases normalization (very early saves)', () => {
it('converts legacy boolean bases to name/null form', () => {
const g = w.migrateGame({ bases: [true, false, true] });
expect(g.bases).toEqual(['?', null, '?']);
});
it('leaves modern name/null bases alone', () => {
const g = w.migrateGame({ bases: ['Alice', null, 'Bob'] });
expect(g.bases).toEqual(['Alice', null, 'Bob']);
});
});
describe('migrateGame — hit-key backfill on lineup slots and subs', () => {
it('gives a slot with no hits object a full default hits object', () => {
const g = w.migrateGame({
lineup: { home: [{ name: 'NoHits', subs: [] }], away: [] },
});
const expected = w.mkHits();
expect(g.lineup.home[0].hits).toEqual(expected);
});
it('backfills newly-added hit keys onto an old (partial) hits object', () => {
// Simulate a save made before `ibb` and `wp` existed.
const partial = { s: 2, d: 1 }; // missing every other key
const g = w.migrateGame({
lineup: { home: [{ name: 'Old', hits: partial, subs: [] }], away: [] },
});
const hits = g.lineup.home[0].hits;
expect(hits.s).toBe(2); // existing values preserved
expect(hits.d).toBe(1);
expect(hits.ibb).toBe(0); // new keys backfilled to 0
expect(hits.wp).toBe(0);
// Every key from the current schema is present.
Object.keys(w.mkHits()).forEach((k) => {
expect(hits[k]).toBeTypeOf('number');
});
});
it('backfills hits on subs from pre-per-sub-stats saves', () => {
const g = w.migrateGame({
lineup: {
home: [{ name: 'Starter', hits: w.mkHits(), subs: [{ name: 'Sub' }] }],
away: [],
},
});
expect(g.lineup.home[0].subs[0].hits).toEqual(w.mkHits());
});
});
describe('migrateGame — a current-shape game is a no-op', () => {
it('passes a freshly-created game through unchanged in structure', () => {
const fresh = w.mkGame();
const migrated = w.migrateGame(fresh);
expect(migrated).toBe(fresh);
expect(Object.keys(migrated.lineup.home[0].hits).sort()).toEqual(
Object.keys(w.mkHits()).sort()
);
});
});
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
// The app is loaded into its own jsdom window by test/helpers/loadApp.js,
// so the test runner itself only needs a plain node environment.
environment: 'node',
include: ['test/**/*.test.js'],
},
});