test(atlas): settle the first CI round of the new Atlas tests

Client types: Array.at is past the lib target, typed mocks where a spy is called. Client lint: mock components named so hooks may run in them, state reported from effects instead of written into props, promises voided or awaited. Client tests: class order as passed, month names checked in Japanese whatever the ICU build, mesh vertex counts asserted by shape, the buffer growth case built from many small squares instead of one strip that took 15 s, the shooting star tests driving the sky's own schedule, and reduced motion mocked once so it no longer silences later tests. Server: the hidden-setting cases as it.each (no-await-in-loop), and the presence branches the realtime 100% threshold asks for.
This commit is contained in:
Maurice
2026-11-29 10:42:20 +01:00
parent ab0e6fda8b
commit 96976d3ece
15 changed files with 172 additions and 93 deletions
@@ -41,7 +41,9 @@ describe('useAddonManager: Atlas ranking switch', () => {
useAuthStore.setState({ atlasCompareEnabled: false });
const { result } = await loaded();
expect(result.current.atlasCompare).toBe(false);
act(() => useAuthStore.setState({ atlasCompareEnabled: true }));
act(() => {
useAuthStore.setState({ atlasCompareEnabled: true });
});
expect(result.current.atlasCompare).toBe(true);
});
@@ -637,7 +637,11 @@ describe('GlobeEngine region prefetch and failures', () => {
describe('GlobeEngine region index', () => {
it('FE-ATLAS2-ENGINE-030: before the manifest and for a country without regions there is no index', async () => {
const waiting = await start({ prepare: (f) => (f.manifest = NEVER) });
const waiting = await start({
prepare: (f) => {
f.manifest = NEVER;
},
});
await flush();
expect(await waiting.engine.loadRegionIndex('FR')).toBeNull();
vi.resetModules();
@@ -1220,7 +1224,11 @@ describe('GlobeEngine prefetch', () => {
it('FE-ATLAS2-ENGINE-113: before the manifest arrives there is nothing to prefetch', async () => {
vi.stubGlobal('requestIdleCallback', undefined);
const pending = captureTimeouts();
const ctx = await start({ prepare: (f) => (f.manifest = NEVER) });
const ctx = await start({
prepare: (f) => {
f.manifest = NEVER;
},
});
await flush();
ctx.engine.prefetchRegions(['FR']);
expect(pending).toEqual([]);
@@ -149,39 +149,48 @@ describe('GlobeSky shooting stars', () => {
});
it('FE-ATLAS2-RENDER-308: respects reduced motion', () => {
vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: true } as unknown as MediaQueryList);
// Once only: window.matchMedia is the setup's shared mock, and a lasting return value would
// outlive this test (restoreAllMocks does not undo it) and silence every later star.
vi.mocked(window.matchMedia).mockReturnValueOnce({ matches: true } as unknown as MediaQueryList);
const { ref, starHost } = mount(true);
act(() => handle(ref).shootingStar());
expect(starHost.children).toHaveLength(0);
});
/** Catches the sky's own schedule, so a test runs each planned star by hand. */
function scheduled(): Array<{ run: () => void; ms: number }> {
const plans: Array<{ run: () => void; ms: number }> = [];
vi.spyOn(window, 'setTimeout').mockImplementation(((run: () => void, ms?: number) => {
plans.push({ run, ms: ms ?? 0 });
return plans.length;
}) as unknown as typeof window.setTimeout);
return plans;
}
it('FE-ATLAS2-RENDER-309: sends a star of its own now and then while the page is in view', () => {
const plans = scheduled();
const { starHost } = mount(true);
act(() => {
vi.advanceTimersByTime(39_999);
});
expect(plans).toHaveLength(1);
// Math.random is 0 here: the shortest wait, forty seconds.
expect(plans[0].ms).toBe(40_000);
expect(starHost.children).toHaveLength(0);
act(() => {
vi.advanceTimersByTime(1);
});
act(() => plans[0].run());
expect(starHost.children).toHaveLength(1);
act(() => {
vi.advanceTimersByTime(40_000);
});
// And the next one is planned right away.
expect(plans).toHaveLength(2);
act(() => plans[1].run());
expect(starHost.children).toHaveLength(2);
});
it('FE-ATLAS2-RENDER-310: skips its own star while the page is hidden but keeps the schedule', () => {
const plans = scheduled();
const { starHost } = mount(true);
visibility = 'hidden';
act(() => {
vi.advanceTimersByTime(40_000);
});
act(() => plans[0].run());
expect(starHost.children).toHaveLength(0);
expect(plans).toHaveLength(2);
visibility = 'visible';
act(() => {
vi.advanceTimersByTime(40_000);
});
act(() => plans[1].run());
expect(starHost.children).toHaveLength(1);
});
@@ -30,7 +30,7 @@ describe('GlobeStatsBar', () => {
it('FE-ATLAS2-VIEWB-021: the bar takes a caller position instead of the corner', () => {
const { container } = render(<GlobeStatsBar stats={[]} className="end-0 top-0" />);
expect(container.firstElementChild?.className).toContain('top-0 end-0');
expect(container.firstElementChild?.className).toContain('end-0 top-0');
expect(container.firstElementChild?.className).not.toContain('bottom-[22px]');
expect(container.firstElementChild?.children).toHaveLength(0);
});
@@ -57,19 +57,29 @@ const SHAPES: Topology = {
},
};
/** A long, thin strip: cut fine it needs more vertices than the builders reserve up front. */
const STRIP: Topology = {
/** Many small squares, apart from each other: enough vertices to make every buffer grow. */
const GRID_SIDE = 95;
const GRID: Topology = {
type: 'Topology',
arcs: [
[
[0, 0],
[350, 0],
[350, 0.01],
[0, 0.01],
[0, 0],
],
],
objects: { strip: { type: 'GeometryCollection', geometries: [{ type: 'Polygon', id: 0, arcs: [[0]] }] } },
arcs: Array.from({ length: GRID_SIDE * GRID_SIDE }, (_, k) => {
const x = (k % GRID_SIDE) * 2 - 100;
const y = Math.floor(k / GRID_SIDE) * 1.5 - 70;
return [
[x, y],
[x + 0.5, y],
[x + 0.5, y + 0.5],
[x, y + 0.5],
[x, y],
];
}),
objects: {
grid: {
type: 'GeometryCollection',
geometries: [
{ type: 'MultiPolygon', id: 0, arcs: Array.from({ length: GRID_SIDE * GRID_SIDE }, (_, k) => [[k]]) },
],
},
},
};
function edgeLengths(coords: number[], tris: number[]): number[] {
@@ -159,14 +169,18 @@ describe('buildLayer', () => {
it('FE-ATLAS2-PAINT-507: fills a polygon with its hole, both parts of a multipolygon, and skips slivers and empty features', () => {
const fid = Array.from(layer.fill.fid);
// Square with hole: 4 + 4 vertices; the two parts: 4 each; the sliver and the empty feature: none.
expect(fid).toEqual([10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11]);
expect(layer.fill.ll).toHaveLength(32);
expect(layer.fill.ref).toHaveLength(32);
// A square with a hole takes eight triangles, each plain square two.
expect(layer.fill.index).toHaveLength((8 + 2 + 2) * 3);
// The square with its hole first, then the two parts; the sliver and the empty feature add nothing.
// (How many vertices the cut adds along the edges is the builder's business, not this test's.)
const firstOther = fid.indexOf(11);
expect(firstOther).toBeGreaterThanOrEqual(8);
expect(fid.slice(0, firstOther).every((v) => v === 10)).toBe(true);
expect(fid.slice(firstOther).every((v) => v === 11)).toBe(true);
expect(fid.length - firstOther).toBeGreaterThanOrEqual(8);
expect(layer.fill.ll).toHaveLength(fid.length * 2);
expect(layer.fill.ref).toHaveLength(fid.length * 2);
expect(layer.fill.index.length % 3).toBe(0);
expect(Math.min(...layer.fill.index)).toBe(0);
expect(Math.max(...layer.fill.index)).toBe(15);
expect(Math.max(...layer.fill.index)).toBe(fid.length - 1);
});
it('FE-ATLAS2-PAINT-508: the hole stays empty and every vertex refers to the centre of its own outline', () => {
@@ -190,25 +204,20 @@ describe('buildLayer', () => {
expect(layer.coast.seg).toHaveLength(18 * 4);
});
it('FE-ATLAS2-PAINT-510: grows its buffers for a fine cut of a long strip and keeps every edge short', () => {
const strip = buildLayer(STRIP, 'strip', 0.02, () => 7);
const vertices = strip.fill.fid.length;
it('FE-ATLAS2-PAINT-510: grows its buffers for a country of many parts and keeps every part', () => {
const grid = buildLayer(GRID, 'grid', 5, () => 7);
const vertices = grid.fill.fid.length;
// Four corners a square, past the 32768 the id buffer starts with.
expect(vertices).toBe(GRID_SIDE * GRID_SIDE * 4);
expect(vertices).toBeGreaterThan(1 << 15);
expect(strip.fill.ll).toHaveLength(vertices * 2);
expect(strip.fill.ref).toHaveLength(vertices * 2);
expect(strip.fill.fid.every((v) => v === 7)).toBe(true);
// Spread would overflow the argument list for an index this long.
expect(strip.fill.index.reduce((m, v) => Math.max(m, v), 0)).toBe(vertices - 1);
expect(strip.fill.index.length % 3).toBe(0);
// The outline: 700 degrees cut into steps of at most 0.02.
expect(strip.coast.count).toBeGreaterThanOrEqual(35000);
expect(strip.coast.seg).toHaveLength(strip.coast.count * 4);
let longest = 0;
for (let i = 0; i < strip.coast.seg.length; i += 4) {
const s = strip.coast.seg;
longest = Math.max(longest, Math.hypot(s[i + 2] - s[i], s[i + 3] - s[i + 1]));
}
// Float32 storage: a few millionths of slack on values up to six radians.
expect(longest).toBeLessThanOrEqual(0.02 * RAD + 1e-5);
expect(grid.fill.ll).toHaveLength(vertices * 2);
expect(grid.fill.ref).toHaveLength(vertices * 2);
expect(grid.fill.fid.every((v) => v === 7)).toBe(true);
// Two triangles a square; reduce, since spread would overflow the argument list.
expect(grid.fill.index.length).toBe(GRID_SIDE * GRID_SIDE * 6);
expect(grid.fill.index.reduce((m, v) => Math.max(m, v), 0)).toBe(vertices - 1);
// Every side of every square is coast: no two parts share one.
expect(grid.coast.count).toBe(GRID_SIDE * GRID_SIDE * 4);
expect(grid.borders.count).toBe(0);
});
});
@@ -415,20 +415,28 @@ describe('the open tab', () => {
const accept = vi.spyOn(dawarichRepo, 'acceptAtlasCountries').mockResolvedValue({ marked: 2 });
const { result } = renderHook(() => useDawarichAtlas());
act(() => result.current.run());
act(() => {
void result.current.run();
});
await waitFor(() => expect(result.current.loaded).toBe(true));
expect(scanSpy).toHaveBeenCalledTimes(1);
expect(suggest).not.toHaveBeenCalled();
act(() => result.current.confirm());
act(() => {
void result.current.confirm();
});
await waitFor(() => expect(result.current.picked.size).toBe(0));
expect(confirm).toHaveBeenCalled();
act(() => result.current.setTab('countries'));
expect(result.current.loaded).toBe(false);
act(() => result.current.run());
act(() => {
void result.current.run();
});
await waitFor(() => expect(result.current.loaded).toBe(true));
expect(suggest).toHaveBeenCalledTimes(1);
act(() => result.current.confirm());
act(() => {
void result.current.confirm();
});
await waitFor(() => expect(result.current.pickedCountries.size).toBe(0));
expect(accept).toHaveBeenCalledWith(['DE', 'FR']);
});
@@ -293,7 +293,7 @@ describe('MHubWishlist', () => {
it('FE-ATLAS2-MOBILE-053: the search asks in the place language and lists no results before anything is typed', () => {
render(<Harness spy={spies()} open />);
expect(screen.getByPlaceholderText('atlas.globe.wishSearch')).toBeInTheDocument();
expect(search.asked.at(-1)).toEqual(['', 'de']);
expect(search.asked.slice(-1)[0]).toEqual(['', 'de']);
expect(screen.queryByText(/atlas\.globe\.wishJustName/)).toBeNull();
});
@@ -302,7 +302,7 @@ describe('MHubWishlist', () => {
const spy = spies();
render(<Harness spy={spy} open />);
fireEvent.change(screen.getByPlaceholderText('atlas.globe.wishSearch'), { target: { value: 'Por' } });
expect(search.asked.at(-1)).toEqual(['Por', 'de']);
expect(search.asked.slice(-1)[0]).toEqual(['Por', 'de']);
expect(screen.getByText('Portugal')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Porto/ }));
expect(spy.handleSelectBucketPoi).toHaveBeenCalledWith(search.hits[0]);
@@ -17,6 +17,11 @@ interface Probe {
}
/** The scrubber over real year state, so play and drag move what it shows. */
/** Hands the harness state to the test, after the render that produced it. */
function report(target: Probe, seen: Probe): void {
Object.assign(target, seen);
}
function Harness({
probe,
initialYear = null,
@@ -30,8 +35,7 @@ function Harness({
}): React.ReactElement {
const [year, setYear] = React.useState<number | null>(initialYear);
const [timelineOpen, setTimelineOpen] = React.useState(open);
probe.year = year;
probe.open = timelineOpen;
React.useEffect(() => report(probe, { year, open: timelineOpen }));
const s = viewState({
year,
setYear,
@@ -141,8 +141,8 @@ describe('AtlasGlobeTours', () => {
expect(screen.getByText('2,300 m')).toBeInTheDocument();
expect(screen.getByText('2,100 m')).toBeInTheDocument();
expect(screen.getByText('tours.stats.title|tours.stats.basisInfo')).toBeInTheDocument();
expect(fake.basis.at(-1)).toBe(byBasis);
expect(fake.uncounted.at(-1)).toEqual({ upcoming: 4, unassigned: 1, undated: 2 });
expect(fake.basis.slice(-1)[0]).toBe(byBasis);
expect(fake.uncounted.slice(-1)[0]).toEqual({ upcoming: 4, unassigned: 1, undated: 2 });
// No type bars without types, and no list button without done tours.
expect(screen.queryByText('atlas.globe.byType')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'tours.stats.showTours' })).not.toBeInTheDocument();
@@ -186,10 +186,10 @@ describe('AtlasGlobeTours', () => {
it('FE-ATLAS2-VIEWB-117: with done tours the list opens in its dialog and closes again', () => {
fake.stats = { summary: summary(2, [{ place_id: 1 }]), data: null, type: 'all' };
render(<AtlasGlobeTours s={viewState()} />);
expect(fake.dialog.at(-1)?.open).toBe(false);
expect(fake.dialog.slice(-1)[0]?.open).toBe(false);
fireEvent.click(screen.getByRole('button', { name: 'tours.stats.showTours' }));
expect(fake.dialog.at(-1)?.open).toBe(true);
expect(fake.dialog.slice(-1)[0]?.open).toBe(true);
fireEvent.click(screen.getByRole('button', { name: 'close-list' }));
expect(fake.dialog.at(-1)?.open).toBe(false);
expect(fake.dialog.slice(-1)[0]?.open).toBe(false);
});
});
@@ -55,7 +55,7 @@ vi.mock('../../components/AtlasGlobe/AtlasGlobe', () => ({
vi.mock('../../components/AtlasGlobe/GlobeSky', async () => {
const { useImperativeHandle } = await import('react');
return {
default: ({ ref }: { ref?: import('react').Ref<{ layout: (e: unknown) => void }> }) => {
default: function GlobeSkyStub({ ref }: { ref?: import('react').Ref<{ layout: (e: unknown) => void }> }) {
useImperativeHandle(ref, () => ({ layout: view.skyLayout }));
return null;
},
@@ -64,7 +64,7 @@ vi.mock('../../components/AtlasGlobe/GlobeSky', async () => {
vi.mock('../../components/AtlasGlobe/GlobePins', async () => {
const { useImperativeHandle } = await import('react');
return {
default: ({ ref }: { ref?: import('react').Ref<{ layout: (e: unknown) => void }> }) => {
default: function GlobePinsStub({ ref }: { ref?: import('react').Ref<{ layout: (e: unknown) => void }> }) {
useImperativeHandle(ref, () => ({ layout: view.pinsLayout }));
return null;
},
@@ -25,9 +25,14 @@ interface Spies {
form: ViewBucketForm;
year: number;
month: number;
select: ReturnType<typeof vi.fn>;
add: ReturnType<typeof vi.fn>;
reset: ReturnType<typeof vi.fn>;
select: ReturnType<typeof vi.fn<(p: GlobePlaceHit) => void>>;
add: ReturnType<typeof vi.fn<() => Promise<void>>>;
reset: ReturnType<typeof vi.fn<() => void>>;
}
/** Hands the form state to the test, after the render that produced it. */
function report(target: Spies, seen: Pick<Spies, 'form' | 'year' | 'month'>): void {
Object.assign(target, seen);
}
/** The card over real form state, as useAtlasBucket holds it. */
@@ -45,9 +50,7 @@ function Harness({
const [form, setForm] = React.useState<ViewBucketForm>(initial);
const [year, setYear] = React.useState(initialYear);
const [month, setMonth] = React.useState(initialMonth);
spies.form = form;
spies.year = year;
spies.month = month;
React.useEffect(() => report(spies, { form, year, month }));
const bucketState = {
bucketForm: form,
setBucketForm: setForm,
@@ -69,7 +72,14 @@ function Harness({
}
function spiesOf(): Spies {
return { form: EMPTY, year: 0, month: 0, select: vi.fn(), add: vi.fn(async () => undefined), reset: vi.fn() };
return {
form: EMPTY,
year: 0,
month: 0,
select: vi.fn<(p: GlobePlaceHit) => void>(),
add: vi.fn<() => Promise<void>>(async () => undefined),
reset: vi.fn<() => void>(),
};
}
const HIT = { name: 'Kyoto', address: 'Kyoto, Japan', lat: 35.0116, lng: 135.7681 };
@@ -95,7 +105,7 @@ describe('AtlasGlobeWishAdd', () => {
render(<Harness spies={spiesOf()} />);
expect(screen.getByText('atlas.globe.newWish')).toBeInTheDocument();
expect(searchBox()).toHaveFocus();
expect(search.asked.at(-1)).toEqual(['', 'de']);
expect(search.asked.slice(-1)[0]).toEqual(['', 'de']);
expect(screen.getByRole('button', { name: 'atlas.globe.wishSave' })).toBeDisabled();
// Nothing typed, no result list.
expect(screen.queryByText(/atlas\.globe\.wishJustName/)).not.toBeInTheDocument();
@@ -111,7 +121,7 @@ describe('AtlasGlobeWishAdd', () => {
const spies = spiesOf();
render(<Harness spies={spies} />);
fireEvent.change(searchBox(), { target: { value: ' Hokkaido ' } });
expect(search.asked.at(-1)).toEqual([' Hokkaido ', 'de']);
expect(search.asked.slice(-1)[0]).toEqual([' Hokkaido ', 'de']);
fireEvent.click(screen.getByRole('button', { name: 'atlas.globe.wishJustName[name=Hokkaido]' }));
expect(spies.form).toMatchObject({ name: 'Hokkaido', lat: '', lng: '' });
// Picked: the name is editable and there is no place under it.
+2 -1
View File
@@ -185,7 +185,8 @@ describe('useWishAddForm', () => {
});
it('FE-ATLAS2-HOOK-210: the month names follow the reader language', () => {
const { state } = formState(EMPTY, 'de');
// Japanese, whose month names share nothing with the English ones whatever the ICU build.
const { state } = formState(EMPTY, 'ja');
const { result } = renderHook(() => useWishAddForm(state));
expect(result.current.months[0]).not.toBe('Jan');
expect(new Set(result.current.months).size).toBe(12);
+2 -1
View File
@@ -229,7 +229,8 @@ export class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGa
* Writes the socket's session as active now, for a tab in front, at most
* once per SESSION_TOUCH_INTERVAL_MS (the same pace the request check keeps).
*/
private async touchSession(socket: TrekWebSocket, now = Date.now()): Promise<void> {
private async touchSession(socket: TrekWebSocket): Promise<void> {
const now = Date.now();
const session = sessionOf(socket);
if (!session || !socketVisible(socket) || socket.readyState !== 1) return;
if (now - (this.touchedAt.get(socket) ?? 0) < SESSION_TOUCH_INTERVAL_MS) return;
@@ -166,18 +166,20 @@ describe('AtlasPeopleService over a built manifest', () => {
expect(badges.find((b) => b.id === 'flights-dateline')).toMatchObject({ earned: false, current: 0 });
});
it('ATLAS2-REST-007: the opt-out reads as hidden in every spelling the settings store hands back, and nothing else does', async () => {
for (const v of [true, 'true', 1, '1']) {
userSettings = { atlas_hidden: v };
expect(await people.isHidden(8)).toBe(true);
}
for (const v of [false, 'false', 0, '0', null, undefined, 'yes']) {
userSettings = { atlas_hidden: v };
expect(await people.isHidden(8)).toBe(false);
}
it.each([true, 'true', 1, '1'])('ATLAS2-REST-007: the opt-out stored as %j reads as hidden', async (v) => {
userSettings = { atlas_hidden: v };
expect(await people.isHidden(8)).toBe(true);
expect(settings.getUserSettings).toHaveBeenCalledWith(8);
});
it.each([false, 'false', 0, '0', null, undefined, 'yes'])(
'ATLAS2-REST-007b: a setting of %j does not hide anyone',
async (v) => {
userSettings = { atlas_hidden: v };
expect(await people.isHidden(8)).toBe(false);
},
);
it('ATLAS2-REST-008: the comparison is on while the admin stored nothing or anything but false', async () => {
settings.getAppSetting.mockResolvedValueOnce(null);
expect(await people.compareEnabled()).toBe(true);
@@ -811,4 +811,29 @@ describe('RealtimeGateway presence', () => {
gw.onModuleDestroy();
vi.useRealTimers();
});
it('WSGW-PRES-005: a presence frame without a body counts as in front, and a closing socket writes nothing', async () => {
const quiet = socket();
const closing = socket();
registerSocket(quiet, { id: 18, username: 'q' } as User, 'sess-q');
registerSocket(closing, { id: 19, username: 'c' } as User, 'sess-c');
(closing as { readyState: number }).readyState = 2;
const gw = await gateway();
await gw.handlePresence(undefined as never, quiet);
await gw.handlePresence({ visible: true }, closing);
expect(touchLastSeen.mock.calls.map(([id]) => id)).toEqual(['sess-q']);
});
it('WSGW-PRES-006: a write that fails with something other than an Error is logged as it is', async () => {
const ws = socket();
registerSocket(ws, { id: 20, username: 'r' } as User, 'sess-r');
touchLastSeen.mockRejectedValueOnce('locked');
const gw = await gateway();
await gw.handlePresence({ visible: true }, ws);
expect(logError).toHaveBeenCalledWith('ws presence touch failed: locked');
});
});