tests/sims/astar.test.ts
The automated tests for the /simulators/astar-pathfinding simulator. They run the model on its own, outside the browser, and compare it with a reference that doesn't depend on the model being right. They run on every change to the simulator's code.
- On 4,000 random grids, every admissible heuristic finds a path exactly as short as breadth-first search does.
- Every path returned is a chain of single steps through open cells, as long as its stated cost.
// /simulators/astar-pathfinding: A* on a grid with each heuristic, against breadth-first search.
import { test } from 'node:test';
import { search, bfs, HEURISTICS } from '../../src/lib/sims/astar.ts';
import { checker, lcg } from './check.ts';
const R = 14, C = 22;
function grids(n: number) {
const r = lcg(3);
return Array.from({ length: n }, () => {
const dens = r() * 0.4;
const wall = Array.from({ length: R * C }, () => r() < dens);
const s = { r: Math.floor(r() * R), c: Math.floor(r() * C) }, g = { r: Math.floor(r() * R), c: Math.floor(r() * C) };
wall[s.r * C + s.c] = false;
wall[g.r * C + g.c] = false;
return { wall, s, g };
});
}
test('on 4,000 random grids, every admissible heuristic finds a path exactly as short as breadth-first search does', () => {
const { ok, done } = checker();
for (const { wall, s, g } of grids(4000)) {
const ref = bfs(R, C, wall, s, g);
for (const H of HEURISTICS) {
const r = search(R, C, wall, s, g, H.id);
if (!isFinite(ref)) { ok(!r.found, `${H.id} found a path where none exists`); continue; }
ok(r.found, `${H.id} missed a reachable goal`);
if (H.admissible) ok(r.cost === ref, `${H.id} cost ${r.cost}, shortest is ${ref}`);
else ok(r.cost <= 2 * ref, `${H.id} (weight 2) cost ${r.cost} is over twice the shortest ${ref}`);
}
}
done();
});
test('every path returned is a chain of single steps through open cells, as long as its stated cost', () => {
const { ok, done } = checker();
for (const { wall, s, g } of grids(1000)) for (const H of HEURISTICS) {
const r = search(R, C, wall, s, g, H.id);
if (!r.found) continue;
ok(r.path.length === r.cost + 1, `${H.id}: ${r.path.length} cells for cost ${r.cost}`);
ok(r.path[0].r === s.r && r.path[0].c === s.c && r.path.at(-1)!.r === g.r && r.path.at(-1)!.c === g.c, `${H.id}: path does not join start and goal`);
for (let i = 1; i < r.path.length; i++) {
const a = r.path[i - 1], b = r.path[i];
ok(Math.abs(a.r - b.r) + Math.abs(a.c - b.c) === 1 && !wall[b.r * C + b.c], `${H.id}: bad step at ${i}`);
}
}
done();
});
Shared helpers: tests/sims/check.ts. The model under test is imported from src/lib/sims/.