Files
TREK/client/src/pages/AtlasPage.test.tsx
T
Vini 7277e35a96 serve each country's regions from its own file, so the server no longer holds them all
The Atlas server no longer keeps the admin-1 regions of every country in memory. Each country's regions are now a pre-gzipped file of their own, sent to the map as they are.

**Why:** `GET /addons/atlas/regions/geo?countries=…` built `admin1Store` (every country's region text, kept until restart), then joined the requested countries, `JSON.parse`d them, and Nest stringified them again. On the 512 MB – 1 GB boxes TREK runs on, the first z≥5 view could OOM the server (same shape as #1576).

**What changes:**
- `server/assets/atlas/admin1/<ISO_A2>.geojson.gz`: 198 files, 14.85 MB, the same 3,447 features as `admin1.geojson.gz`.
- New `GET /addons/atlas/regions/geo/:code` with a Zod contract (`regionGeoParamsSchema` in `@trek/shared`: two letters, any case). It sends the country's file as it is, with `Content-Encoding: gzip` and the current 1-day `Cache-Control`, as `countries/geo` does. A country without regions gets an empty FeatureCollection. Anything that is not two letters gets a 400.
- `useAtlas.ts` fetches one URL per uncached country and still rebuilds the layer once. Each country has a stable URL, so a country evicted by `REGION_CACHE_MAX` comes back from the browser cache.
- `getRegionFeatures` reads only the country it needs. `admin1Store` is removed.
- `?countries=` keeps working for cached PWA clients. It joins the per-country files as bytes, without a parse.
- The migrations are untouched. `admin1.geojson.gz` still ships, only for `Migration20200101021500` and `Migration20200101031500`. This costs ~15 MB of disk in the image and no RAM. `build-atlas-geo.mjs` writes both, and ATLAS-BUNDLE-008 keeps them equal.

**Memory** (real `atlas-geo` module, first z≥5 view over Europe = 49 country codes, JS heap + Buffers):

| | peak | kept after |
|---|---|---|
| before, first view (builds the store) | +372 MB | +61 MB |
| before, later views | +115 MB | 0 |
| after, `/regions/geo/:code` | +4.7 MB | 0 |
| after, legacy `?countries=` | +59 MB | 0 |

**Tests:**
- New: `atlas-region-files.test.ts` (moved from `atlas.service.test.ts`, plus join and dedupe cases), the `regionGeoParamsSchema` spec, ATLAS-BUNDLE-007 (the file format the byte join depends on), ATLAS-BUNDLE-008 (bundle and per-country files are equal), ATLAS-016/017/018 (the new route over HTTP, including the 400).
- The `getVisitedRegions` tests (ATLAS-UNIT-019..024) used to pass only when `getRegionGeo`'s `beforeAll` had built the store first. They now also pass on their own.
- The shared, server and client gates pass. Baselines go down only where this change removed code (`no-console`, `no-explicit-any`, `no-swallowed-catch`, file sizes).

**Trade-offs:**
- A first zoom over Europe sends ~49 small parallel requests instead of 1. Over HTTP/1.1 the browser queues them 6 at a time. The total bytes are the same (4.4 MB gz).
- The per-country URLs are unversioned and cached for a day, like `countries/geo`. After an upgrade that changes a country's regions, a browser can show the old shapes for up to 24 h.

Approved on Discord in #github-pr: <paste the thread link here>
Related: #1576, #2559

- [x] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

- [ ] I have read the [Contributing Guidelines](https://github.com/liketrek/TREK/wiki/Contributing)
- [ ] My branch is [up to date with `dev`](https://github.com/liketrek/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date)
- [x] This PR targets the `dev` branch, not `main` *(wiki-only PRs are exempt)*
- [x] I have tested my changes locally
- [x] I have added/updated tests that prove my fix is effective or that my feature works
- [x] I have updated documentation if needed
2026-10-31 00:40:23 +00:00

1845 lines
72 KiB
TypeScript

import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { render, screen, waitFor, fireEvent } from '../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../tests/helpers/store';
import { buildUser, buildSettings } from '../../tests/helpers/factories';
import { useAuthStore } from '../store/authStore';
import { useSettingsStore } from '../store/settingsStore';
import { useAddonStore } from '../store/addonStore';
import AtlasPage from './AtlasPage';
import { maplibreGL } from '@maplibre/maplibre-gl-leaflet';
// ── Captured style() results, for tests asserting fill/border on a specific
// feature (e.g. the wishlist hatch pattern) without duplicating the mock's
// internal geoJSON wiring ────────────────────────────────────────────────────
const { capturedStyles } = vi.hoisted(() => ({ capturedStyles: [] as { feature: any; result: any }[] }));
// ── Leaflet mock ──────────────────────────────────────────────────────────────
// maplibre-gl-leaflet hangs the vector basemap into Leaflet's tile pane. The mock
// only has to be callable and hand back a layer with the three methods the callers
// use, since nothing here renders WebGL.
vi.mock('@maplibre/maplibre-gl-leaflet', () => ({
maplibreGL: vi.fn(() => {
// One GL map per layer, kept stable: a fresh object per call would hand the
// assertions a different spy than the code just used.
const gl = {
setStyle: vi.fn(), on: vi.fn(), isStyleLoaded: () => false,
getStyle: () => ({ layers: [] }), setLayoutProperty: vi.fn(),
}
const layer: Record<string, unknown> = { remove: vi.fn(), getMaplibreMap: vi.fn(() => gl) }
layer.addTo = vi.fn(() => layer)
return layer
}),
}));
vi.mock('../components/Map/engines/maplibre', () => ({ default: {} }));
vi.mock('leaflet', () => {
// Mock layer returned by onEachFeature — supports event registration
const makeMockLayer = () => {
const layer: any = {
bindTooltip: vi.fn().mockReturnThis(),
on: vi.fn().mockImplementation((event: string, cb: Function) => {
// Immediately invoke mouseover/mouseout/click to cover callback bodies
if (event === 'mouseover' || event === 'mouseout' || event === 'click') {
try { cb({ target: layer }); } catch { /* ignore null ref errors */ }
}
return layer;
}),
setStyle: vi.fn(),
getBounds: vi.fn(() => ({ isValid: vi.fn(() => true) })),
resetStyle: vi.fn(),
removeFrom: vi.fn(),
};
return layer;
};
const mockMap = {
setView: vi.fn().mockReturnThis(),
on: vi.fn().mockImplementation((event: string, cb: Function) => {
if (event === 'zoomend') {
// Invoke with zoom=5 to cover the shouldShow=true branch (loadRegionsForViewport)
const origGetZoom = mockMap.getZoom;
mockMap.getZoom = vi.fn(() => 5);
try { cb(); } catch { /* ignore */ }
// Invoke with zoom=4 to cover the shouldShow=false else branch (lines 335-338)
mockMap.getZoom = vi.fn(() => 4);
try { cb(); } catch { /* ignore */ }
mockMap.getZoom = origGetZoom;
} else if (event === 'moveend') {
try { cb(); } catch { /* ignore */ }
}
return mockMap;
}),
off: vi.fn().mockReturnThis(),
remove: vi.fn(),
invalidateSize: vi.fn(),
fitBounds: vi.fn(),
addLayer: vi.fn(),
removeLayer: vi.fn(),
getContainer: vi.fn(() => document.createElement('div')),
getZoom: vi.fn(() => 4),
createPane: vi.fn(),
getPane: vi.fn(() => ({ style: {} })),
// intersects=true so loadRegionsForViewport can fetch region geo data
getBounds: vi.fn(() => ({ intersects: vi.fn(() => true) })),
hasLayer: vi.fn(() => false),
getCenter: vi.fn(() => ({ lat: 25, lng: 0 })),
};
const L = {
map: vi.fn(() => mockMap),
tileLayer: vi.fn(() => ({ addTo: vi.fn().mockReturnThis(), setUrl: vi.fn() })),
// Call onEachFeature and style callbacks for each feature so those paths are covered
geoJSON: vi.fn((data: any, options: any) => {
if (options?.onEachFeature && data?.features) {
for (const feature of data.features) {
const layer = makeMockLayer();
try {
if (options.style) capturedStyles.push({ feature, result: options.style(feature) });
options.onEachFeature(feature, layer);
} catch {
// ignore errors from callbacks in mock
}
}
}
return {
addTo: vi.fn().mockReturnThis(),
remove: vi.fn(),
clearLayers: vi.fn(),
resetStyle: vi.fn(),
removeFrom: vi.fn(),
};
}),
divIcon: vi.fn(() => ({})),
marker: vi.fn(() => {
let tooltip: { options: Record<string, unknown>; getElement: () => null } | undefined;
const m = {
addTo: vi.fn().mockReturnThis(),
on: vi.fn(() => m),
off: vi.fn(() => m),
remove: vi.fn(),
getLatLng: vi.fn(() => ({ lat: 0, lng: 0 })),
bindTooltip: vi.fn(() => {
tooltip = { options: { direction: 'top', offset: [0, -14] }, getElement: () => null };
return m;
}),
getTooltip: vi.fn(() => tooltip),
closeTooltip: vi.fn(),
};
return m;
}),
latLngBounds: vi.fn(() => ({ extend: vi.fn(), isValid: vi.fn(() => true) })),
layerGroup: vi.fn(() => ({ addTo: vi.fn().mockReturnThis(), clearLayers: vi.fn() })),
canvas: vi.fn(() => ({})),
svg: vi.fn(() => ({})),
control: { zoom: vi.fn(() => ({ addTo: vi.fn() })) },
};
return { default: L, ...L };
});
// ── Navbar mock ───────────────────────────────────────────────────────────────
vi.mock('../components/Layout/Navbar', () => ({
default: () => React.createElement('nav', { 'data-testid': 'navbar' }),
}));
// ── GeoJSON fixture with a real feature to exercise search/select paths ───────
const geoJsonWithFR = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {
ISO_A2: 'FR',
ADM0_A3: 'FRA',
ISO_A3: 'FRA',
NAME: 'France',
ADMIN: 'France',
},
geometry: null,
},
],
};
const makeGeoJsonWithA3Fallback = (a3: string, name: string) => ({
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: {
ISO_A2: '-99',
ADM0_A3: a3,
ISO_A3: a3,
NAME: name,
ADMIN: name,
},
geometry: null,
},
],
});
// ── Atlas API response fixture ────────────────────────────────────────────────
const atlasStatsResponse = {
countries: [{ code: 'FR', tripCount: 2, placeCount: 5, firstVisit: '2023-01-01', lastVisit: '2024-06-01' }],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 1, totalDays: 14, totalCities: 3 },
mostVisited: null,
continents: { Europe: 1 },
lastTrip: { id: 1, title: 'Paris Trip' },
nextTrip: null,
streak: 2,
firstYear: 2022,
tripsThisYear: 1,
};
const emptyAtlasResponse = {
countries: [],
stats: { totalTrips: 0, totalPlaces: 0, totalCountries: 0, totalDays: 0, totalCities: 0 },
mostVisited: null,
continents: {},
lastTrip: null,
nextTrip: null,
streak: 0,
firstYear: null,
tripsThisYear: 0,
};
// ── Default MSW handlers for atlas endpoints ──────────────────────────────────
function useDefaultAtlasHandlers() {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(atlasStatsResponse)),
http.get('/api/addons/atlas/bucket-list', () => HttpResponse.json({ items: [] })),
http.get('/api/addons/atlas/regions', () => HttpResponse.json({ regions: {} })),
// Country-border GeoJSON (admin-0) — served by the API now. Tests that need real
// country features override this handler via server.use(...).
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json({ type: 'FeatureCollection', features: [] })),
// Handler for region GeoJSON fetch (triggered by loadRegionsForViewport when intersects=true)
http.get('/api/addons/atlas/regions/geo/:code', () => HttpResponse.json({ features: [] })),
);
}
// ── Test suite ────────────────────────────────────────────────────────────────
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
capturedStyles.length = 0;
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false }) });
useDefaultAtlasHandlers();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('AtlasPage', () => {
describe('FE-PAGE-ATLAS-001: loading spinner shown on initial render', () => {
it('displays a spinner while atlas data is being fetched', async () => {
server.use(
http.get('/api/addons/atlas/stats', async () => {
await new Promise((r) => setTimeout(r, 200));
return HttpResponse.json(atlasStatsResponse);
}),
);
render(<AtlasPage />);
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
});
});
describe('FE-PAGE-ATLAS-002: stats grid renders totalCountries count', () => {
it('shows the total countries count after data loads', async () => {
render(<AtlasPage />);
await waitFor(() => {
// totalCountries = 1 — appears in both mobile bar and desktop panel
expect(screen.getAllByText('1').length).toBeGreaterThan(0);
});
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
describe('FE-PAGE-ATLAS-003: streak displayed', () => {
it('shows streak count and years-in-a-row label', async () => {
render(<AtlasPage />);
await waitFor(() => {
expect(screen.getByText(/years in a row/i)).toBeInTheDocument();
});
// streak value 2 is visible alongside the label
const streakLabel = screen.getByText(/years in a row/i);
const streakContainer = streakLabel.closest('div') as HTMLElement;
expect(streakContainer).toBeTruthy();
});
});
describe('FE-PAGE-ATLAS-004: the highlights row no longer carries a last-trip tile', () => {
it('keeps the trip out of the stats bar even when the API still returns one', async () => {
render(<AtlasPage />);
// The row is stats only now; the trip lives in the country detail below.
await waitFor(() => expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0));
expect(screen.queryByText('Paris Trip')).not.toBeInTheDocument();
});
});
describe('FE-PAGE-ATLAS-005: sidebar panel renders with stats after load', () => {
it('renders the desktop stats panel with countries and trips labels', async () => {
render(<AtlasPage />);
await waitFor(() => {
// Both "Countries" labels (mobile + desktop) should be present
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
expect(screen.getAllByText(/trips/i).length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-006: bucket list tab switch shows bucket content', () => {
it('clicking the Bucket List tab reveals bucket-list content', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for data to load so tabs are visible
await waitFor(() => {
expect(screen.getByText('Bucket List')).toBeInTheDocument();
});
await user.click(screen.getByText('Bucket List'));
await waitFor(() => {
expect(screen.getByText(/add places you dream of visiting/i)).toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-007: bucket list tab switch (alternate)', () => {
it('stats tab is active by default, can switch to bucket tab', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => {
expect(screen.getByText('Stats')).toBeInTheDocument();
expect(screen.getByText('Bucket List')).toBeInTheDocument();
});
// Switch to bucket list
await user.click(screen.getByText('Bucket List'));
// Bucket empty state appears
await waitFor(() => {
expect(screen.getByText(/add places you dream of visiting/i)).toBeInTheDocument();
});
// Switch back to stats
await user.click(screen.getByText('Stats'));
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-008: empty atlas data shows zero stats', () => {
it('renders zero counts when API returns no data', async () => {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(emptyAtlasResponse)),
);
render(<AtlasPage />);
await waitFor(() => {
// Multiple zeros should be present (totalCountries=0, totalTrips=0, etc.)
const zeros = screen.getAllByText('0');
expect(zeros.length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-009: mobile stats bar is present in DOM', () => {
it('renders the mobile bottom stats bar with country and trip counts', async () => {
render(<AtlasPage />);
await waitFor(() => {
// Mobile bar always renders; check for the stats labels
const countryLabels = screen.getAllByText(/countr(y|ies)/i);
expect(countryLabels.length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-010: continent breakdown rendered', () => {
it('shows Europe continent count from MSW response', async () => {
render(<AtlasPage />);
await waitFor(() => {
// Continent label text appears in the desktop panel
expect(screen.getAllByText(/europe/i).length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-011: tripsThisYear shows trips-in-year label', () => {
it('shows tripsThisYear count and "trips in YEAR" label when > 1', async () => {
server.use(
http.get('/api/addons/atlas/stats', () =>
HttpResponse.json({ ...atlasStatsResponse, tripsThisYear: 3 }),
),
);
render(<AtlasPage />);
await waitFor(() => {
expect(screen.getByText(/trips in/i)).toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-012: empty state shows noData message in sidebar', () => {
it('shows "No travel data yet" when no countries and no lastTrip', async () => {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(emptyAtlasResponse)),
);
render(<AtlasPage />);
await waitFor(() => {
// The empty state now renders the shared mascot EmptyState with a single title
// (atlas.noData = "No travel data yet"). The old "create a trip and add places"
// hint subtitle was dropped in the mobile rewrite, so only the title renders.
expect(screen.getByText(/no travel data yet/i)).toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-013: bucket tab Add Place button opens form', () => {
it('clicking Add Place in bucket tab reveals the bucket add form', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => expect(screen.getAllByText('Bucket List').length).toBeGreaterThan(0));
// Switch to bucket tab — click first "Bucket List" tab button
await user.click(screen.getAllByText('Bucket List')[0]);
// Find the "+ Add place" button — use exact text to avoid matching the hint "Add places..."
await waitFor(() => expect(screen.getAllByRole('button', { name: /add place/i }).length).toBeGreaterThan(0));
// Click the Add place button
await user.click(screen.getAllByRole('button', { name: /add place/i })[0]);
// Form appears with name/search input
await waitFor(() => {
expect(screen.getByPlaceholderText(/name \(country, city, place\.\.\.\)/i)).toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-014: bucket form cancel closes form', () => {
it('clicking Cancel in bucket form hides the form again', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => expect(screen.getAllByText('Bucket List').length).toBeGreaterThan(0));
await user.click(screen.getAllByText('Bucket List')[0]);
await waitFor(() => expect(screen.getAllByRole('button', { name: /add place/i }).length).toBeGreaterThan(0));
await user.click(screen.getAllByRole('button', { name: /add place/i })[0]);
await waitFor(() =>
expect(screen.getByPlaceholderText(/name \(country, city, place\.\.\.\)/i)).toBeInTheDocument(),
);
// Click Cancel
const cancelBtn = screen.getAllByText(/cancel/i)[0];
await user.click(cancelBtn);
await waitFor(() =>
expect(screen.queryByPlaceholderText(/name \(country, city, place\.\.\.\)/i)).not.toBeInTheDocument(),
);
});
});
describe('FE-PAGE-ATLAS-015: bucket items render when list has items', () => {
it('shows bucket list items from the API', async () => {
server.use(
http.get('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({
items: [
{ id: 1, name: 'Kyoto', country_code: 'JP', lat: null, lng: null, notes: null, target_date: '2027-04' },
],
}),
),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => expect(screen.getByText('Bucket List')).toBeInTheDocument());
await user.click(screen.getByText('Bucket List'));
await waitFor(() => {
expect(screen.getByText('Kyoto')).toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-016: country search input renders on page', () => {
it('renders the country search input field after data loads', async () => {
render(<AtlasPage />);
// Search input is in the main render (only after loading completes)
await waitFor(() => {
expect(screen.getByPlaceholderText(/search a country/i)).toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-017: country search filters options from GeoJSON', () => {
it('typing in search updates the input value', async () => {
// Override fetch to return GeoJSON with FR feature
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for data to load so geoData is set and search input is rendered
await waitFor(() => expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
expect(searchInput).toHaveValue('fr');
});
});
describe('FE-PAGE-ATLAS-018: search clear button resets input', () => {
it('clicking the X button clears the search input', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for data to load so main render (with search input) is shown
await waitFor(() => {
expect(screen.getByPlaceholderText(/search a country/i)).toBeInTheDocument();
});
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'Paris');
// Clear button appears when there is input
await waitFor(() => {
expect(screen.getByLabelText(/clear/i)).toBeInTheDocument();
});
await user.click(screen.getByLabelText(/clear/i));
expect(searchInput).toHaveValue('');
});
});
describe('FE-PAGE-ATLAS-019: confirm popup shows via Enter on search with GeoJSON', () => {
it('pressing Enter in search with matching GeoJSON result triggers confirm popup', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
server.use(
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for both atlas data and geoData to load (search input renders after load)
await waitFor(() => expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0));
const searchInput = screen.getByPlaceholderText(/search a country/i);
// Type search term
await user.type(searchInput, 'fr');
// Press Enter to select first result (if options populated)
fireEvent.keyDown(searchInput, { key: 'Enter' });
// If options populated, confirm popup should appear
await waitFor(
() => {
const popup = screen.queryByText(/mark as visited/i);
if (popup) {
expect(popup).toBeInTheDocument();
} else {
// No popup if search results were empty — search input still present
expect(searchInput).toBeInTheDocument();
}
},
{ timeout: 2000 },
);
});
});
describe('FE-PAGE-ATLAS-020: dark mode variant renders correctly', () => {
it('renders page without errors in dark mode', async () => {
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: true }) });
render(<AtlasPage />);
// Loading spinner shows in dark mode too
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
// Eventually loads
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-021: mouse events on panel do not throw', () => {
it('mouseMove and mouseLeave events on the desktop panel work without errors', async () => {
render(<AtlasPage />);
await waitFor(() => expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0));
// Find the desktop panel container and fire events
const panel = document.querySelector('.hidden.md\\:flex') as HTMLElement | null;
if (panel) {
fireEvent.mouseMove(panel, { clientX: 200, clientY: 100 });
fireEvent.mouseLeave(panel);
}
// No error thrown; DOM is still intact
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
describe('FE-PAGE-ATLAS-022: confirm popup for bucket type shows month/year selects', () => {
it('selecting Add to bucket list in confirm popup shows month/year pickers', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for data and search input to be ready
await waitFor(() => expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
fireEvent.keyDown(searchInput, { key: 'Enter' });
// If confirm popup appears, click "Add to bucket list"
await waitFor(
async () => {
const addToBucketBtns = screen.queryAllByText(/add to bucket list/i);
if (addToBucketBtns.length > 0) {
await user.click(addToBucketBtns[0]);
await waitFor(() => {
expect(screen.queryByText(/when do you plan to visit/i)).toBeInTheDocument();
});
} else {
// No popup if search had no results — that's acceptable
expect(searchInput).toBeInTheDocument();
}
},
{ timeout: 2000 },
);
});
});
describe('FE-PAGE-ATLAS-031: confirm popup opens and mark-visited action works', () => {
it('opens confirm popup via search and clicking Mark as visited closes it', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
server.use(
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for search input to appear (loading done AND geoData loaded)
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
// Wait until atlas_country_results is populated — the dropdown button should appear
await waitFor(
() => {
const dropdownBtns = screen.queryAllByRole('button').filter(
(b) => b.textContent?.includes('France') || b.textContent?.includes('FR'),
);
expect(dropdownBtns.length).toBeGreaterThan(0);
},
{ timeout: 3000 },
).catch(() => {
// If no dropdown appeared, fall back to Enter key
});
// Press Enter to select first result
fireEvent.keyDown(searchInput, { key: 'Enter' });
// Strictly wait for popup — if it appears, test it; otherwise skip gracefully
try {
await waitFor(
() => {
expect(screen.getByText(/mark as visited/i)).toBeInTheDocument();
},
{ timeout: 3000 },
);
// Popup appeared — verify its content
expect(screen.getAllByText(/add to bucket list/i).length).toBeGreaterThan(0);
// Click Mark as visited (inline handler on the choose type button)
const markBtn = screen.getByText(/mark as visited/i);
await user.click(markBtn);
await waitFor(() => {
expect(screen.queryByText(/mark as visited/i)).not.toBeInTheDocument();
});
} catch {
// Popup didn't appear — search had no matching results
expect(searchInput).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-032: confirm popup Add to Bucket opens bucket type', () => {
it('clicking Add to bucket list in choose popup switches to bucket type', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
fireEvent.keyDown(searchInput, { key: 'Enter' });
try {
await waitFor(
() => {
expect(screen.getByText(/mark as visited/i)).toBeInTheDocument();
},
{ timeout: 3000 },
);
// Click "Add to bucket list" in choose popup
const addToBucketBtns = screen.getAllByText(/add to bucket list/i);
await user.click(addToBucketBtns[0]);
// Popup switches to bucket type showing month/year
await waitFor(() => {
expect(screen.getByText(/when do you plan to visit/i)).toBeInTheDocument();
});
// Back button returns to choose
await user.click(screen.getByText(/back/i));
await waitFor(() => {
expect(screen.getByText(/mark as visited/i)).toBeInTheDocument();
});
} catch {
// Popup didn't appear — acceptable fallback
expect(searchInput).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-025: delete bucket item via X button', () => {
it('clicking the X button on a bucket item removes it', async () => {
server.use(
http.get('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({
items: [
{ id: 5, name: 'Santorini', country_code: 'GR', lat: null, lng: null, notes: null, target_date: null },
],
}),
),
http.delete('/api/addons/atlas/bucket-list/:id', () => HttpResponse.json({ success: true })),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for Santorini to appear in the bucket list
await waitFor(() => expect(screen.getByText('Santorini')).toBeInTheDocument());
// Find the delete button inside the Santorini container
const santoriniEl = screen.getByText('Santorini');
const container = santoriniEl.closest('div[style*="position: relative"]') as HTMLElement | null;
const deleteBtn = container?.querySelector('button') ?? null;
if (deleteBtn) {
await user.click(deleteBtn);
await waitFor(() => {
expect(screen.queryByText('Santorini')).not.toBeInTheDocument();
});
} else {
// Fallback: verify Santorini is rendered
expect(screen.getByText('Santorini')).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-027: search clear via backspace triggers empty onChange branch', () => {
it('clearing the search input by backspace covers the empty-query onChange branch', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
// Type then clear
await user.type(searchInput, 'x');
await user.clear(searchInput);
expect(searchInput).toHaveValue('');
});
});
describe('FE-PAGE-ATLAS-028: Escape key in search closes dropdown', () => {
it('pressing Escape in the search input covers the Escape handler branch', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'ger');
// Press Escape
fireEvent.keyDown(searchInput, { key: 'Escape' });
// Search input is still present after Escape
expect(searchInput).toBeInTheDocument();
});
});
describe('FE-PAGE-ATLAS-029: confirm popup opens via search dropdown click', () => {
it('clicking a country in the search dropdown opens the confirm action popup', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
server.use(
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Wait for data to load AND geoData (search input visible)
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
// Wait for a dropdown item to appear (France or FR)
let foundDropdownItem = false;
await waitFor(
() => {
const allButtons = screen.getAllByRole('button');
// Dropdown buttons have no aria-label but have text with country name
const franceBtn = allButtons.find(
(b) => b.textContent?.includes('France') || b.textContent?.includes('FR'),
);
if (franceBtn && !franceBtn.getAttribute('data-testid')) {
foundDropdownItem = true;
}
// Either found item or search worked fine
expect(searchInput).toHaveValue('fr');
},
{ timeout: 2000 },
);
if (foundDropdownItem) {
// Try pressing Enter to select
fireEvent.keyDown(searchInput, { key: 'Enter' });
await waitFor(
() => {
const popup = screen.queryByText(/mark as visited/i);
if (popup) {
expect(popup).toBeInTheDocument();
} else {
expect(searchInput).toBeInTheDocument();
}
},
{ timeout: 2000 },
);
}
});
});
describe('FE-PAGE-ATLAS-030: confirm popup overlay click closes it', () => {
it('clicking the overlay backdrop closes the confirm popup', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
fireEvent.keyDown(searchInput, { key: 'Enter' });
// If popup appears, click backdrop to close it
await waitFor(
async () => {
const popup = screen.queryByText(/mark as visited/i);
if (popup) {
// Click the backdrop: the DialogShell overlay around the dialog panel
const backdrop = screen.queryByRole('dialog')?.parentElement ?? null;
if (backdrop) {
await user.click(backdrop);
await waitFor(() => {
expect(screen.queryByText(/mark as visited/i)).not.toBeInTheDocument();
});
}
} else {
expect(searchInput).toBeInTheDocument();
}
},
{ timeout: 2000 },
);
});
});
describe('FE-PAGE-ATLAS-023: totals display all stat labels', () => {
it('shows all five stat labels after data loads', async () => {
render(<AtlasPage />);
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
expect(screen.getAllByText(/trips/i).length).toBeGreaterThan(0);
expect(screen.getAllByText(/places/i).length).toBeGreaterThan(0);
expect(screen.getAllByText(/days/i).length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-024: bucket form input accepts typed text', () => {
it('typing in bucket form search input updates the field and shows search button', async () => {
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => expect(screen.getAllByText('Bucket List').length).toBeGreaterThan(0));
await user.click(screen.getAllByText('Bucket List')[0]);
await waitFor(() => expect(screen.getAllByRole('button', { name: /add place/i }).length).toBeGreaterThan(0));
await user.click(screen.getAllByRole('button', { name: /add place/i })[0]);
const nameInput = await screen.findByPlaceholderText(/name \(country, city, place\.\.\.\)/i);
await user.type(nameInput, 'Tokyo');
// The input has the typed value
expect(nameInput).toHaveValue('Tokyo');
// A search (magnifier) button is present
const searchButtons = screen.getAllByRole('button');
expect(searchButtons.length).toBeGreaterThan(0);
});
});
describe('FE-PAGE-ATLAS-051: bucket search results escape the panel that clips them', () => {
it('renders the result list outside the overflow-hidden desktop panel (#1899)', async () => {
server.use(
http.post('/api/maps/search', () => HttpResponse.json({
places: [
{ name: 'Amsterdam', address: 'Amsterdam, North Holland, Netherlands', lat: 52.37, lng: 4.89 },
{ name: 'New Amsterdam Island', address: 'French Southern and Antarctic Lands, France', lat: -37.8, lng: 77.5 },
{ name: 'City of Amsterdam', address: 'North Holland, Netherlands', lat: 52.35, lng: 4.9 },
],
})),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => expect(screen.getAllByText('Bucket List').length).toBeGreaterThan(0));
await user.click(screen.getAllByText('Bucket List')[0]);
await waitFor(() => expect(screen.getAllByRole('button', { name: /add place/i }).length).toBeGreaterThan(0));
await user.click(screen.getAllByRole('button', { name: /add place/i })[0]);
const nameInput = await screen.findByPlaceholderText(/name \(country, city, place\.\.\.\)/i);
await user.type(nameInput, 'Amsterdam{Enter}');
// The first hit must be present — it is the one the panel used to swallow.
const firstHit = await screen.findByText('Amsterdam, North Holland, Netherlands');
const list = firstHit.closest('button')!.parentElement as HTMLElement;
// Portalled straight onto the body, so no ancestor's overflow can clip it.
expect(list.style.position).toBe('fixed');
expect(list.parentElement).toBe(document.body);
expect(list.closest('.overflow-hidden')).toBeNull();
expect(screen.getByText('City of Amsterdam')).toBeInTheDocument();
});
});
describe('FE-PAGE-ATLAS-033: GeoJSON with unvisited country covers onEachFeature else branch', () => {
it('loads map with visited FR and unvisited DE, covering both onEachFeature branches', async () => {
const geoJsonFRandDE = {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { ISO_A2: 'FR', ADM0_A3: 'FRA', ISO_A3: 'FRA', NAME: 'France', ADMIN: 'France' }, geometry: null },
{ type: 'Feature', properties: { ISO_A2: 'DE', ADM0_A3: 'DEU', ISO_A3: 'DEU', NAME: 'Germany', ADMIN: 'Germany' }, geometry: null },
],
};
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonFRandDE)),
);
render(<AtlasPage />);
// FR is in atlasStatsResponse.countries → visited branch
// DE is not → unvisited else branch in onEachFeature
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
// Both branches covered via Leaflet mock calling onEachFeature for each feature
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
describe('FE-PAGE-ATLAS-049: bucket-list country renders hatched wishlist fill', () => {
it('styles an unvisited bucket-list country with the wishlist hatch, not the flat unvisited gray', async () => {
const geoJsonFRandJP = {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { ISO_A2: 'FR', ADM0_A3: 'FRA', ISO_A3: 'FRA', NAME: 'France', ADMIN: 'France' }, geometry: null },
{ type: 'Feature', properties: { ISO_A2: 'JP', ADM0_A3: 'JPN', ISO_A3: 'JPN', NAME: 'Japan', ADMIN: 'Japan' }, geometry: null },
],
};
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonFRandJP)),
http.get('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({
items: [{ id: 1, name: 'Kyoto', country_code: 'JP', lat: null, lng: null, notes: null, target_date: null }],
}),
),
);
render(<AtlasPage />);
await waitFor(() => {
expect(capturedStyles.some((s) => s.feature.properties.ADM0_A3 === 'JPN')).toBe(true);
});
// FR is visited → keeps the normal solid fill, in its own hash-derived color
// from the palette (stable regardless of visit order or list contents).
const frStyle = capturedStyles.find((s) => s.feature.properties.ADM0_A3 === 'FRA')!.result;
expect(frStyle.fillColor).toBe('#dc2626');
expect(frStyle.dashArray).toBeUndefined();
// JP is on the bucket list and not visited → hatch, in JP's own hash-derived
// color — distinct from FR's, and unaffected by FR being visited.
const jpStyle = capturedStyles.find((s) => s.feature.properties.ADM0_A3 === 'JPN')!.result;
expect(jpStyle.fillColor).toBe('#0ea5e9');
expect(jpStyle.dashArray).toBe('3 2');
expect(jpStyle.fillColor).not.toBe(frStyle.fillColor);
});
});
describe('FE-PAGE-ATLAS-034: dropdown button click + mouse events', () => {
it('clicking France dropdown button covers onClick and mouse event handlers', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
server.use(
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
// Type character by character and check after each
await user.type(searchInput, 'fr');
// After user.type completes, React state is flushed — check for dropdown
// The dropdown renders when atlas_country_open && atlas_country_results.length > 0
let franceBtn: HTMLElement | null = null;
// Poll for France button to appear in the dropdown
await waitFor(() => {
const btns = Array.from(document.querySelectorAll('button'));
const btn = btns.find(
(b) => b.textContent?.toLowerCase().includes('france') && b.style.width === '100%',
);
if (btn) {
franceBtn = btn;
return;
}
throw new Error('France dropdown button not found yet');
}, { timeout: 3000 }).catch(() => {
// France button not found — fall back to Enter key
});
if (franceBtn) {
// Fire mouse events on dropdown button (covers onMouseEnter/Leave on button)
fireEvent.mouseEnter(franceBtn);
fireEvent.mouseLeave(franceBtn);
// Fire mouse leave on the dropdown wrapper div (closes it — covers onMouseLeave)
const parent = (franceBtn as HTMLElement).parentElement;
if (parent) {
fireEvent.mouseLeave(parent);
}
// Click the France button → select_country_from_search → setConfirmAction (covers onClick)
fireEvent.click(franceBtn);
await waitFor(() => {
const popup = screen.queryByText(/mark as visited/i);
if (popup) {
expect(popup).toBeInTheDocument();
} else {
expect(searchInput).toBeInTheDocument();
}
});
} else {
// Dropdown not available — use Enter fallback
fireEvent.keyDown(searchInput, { key: 'Enter' });
expect(searchInput).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-035: mark unvisited country + popup mouse events', () => {
it('marks an unvisited country covering line 983 and popup mouse events', async () => {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(emptyAtlasResponse)),
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
);
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
// Press Enter to select (or wait for dropdown click)
fireEvent.keyDown(searchInput, { key: 'Enter' });
try {
await waitFor(
() => { expect(screen.getByText(/mark as visited/i)).toBeInTheDocument(); },
{ timeout: 3000 },
);
// Fire mouse events on the "Mark as visited" button (covers onMouseEnter/Leave)
const markBtn = screen.getByText(/mark as visited/i);
const markButton = markBtn.closest('button') as HTMLButtonElement;
if (markButton) {
fireEvent.mouseEnter(markButton);
fireEvent.mouseLeave(markButton);
}
// Fire mouse events on "Add to bucket list" button
const addToBucketBtns = screen.queryAllByText(/add to bucket list/i);
if (addToBucketBtns.length > 0) {
const bucketButton = addToBucketBtns[0].closest('button') as HTMLButtonElement;
if (bucketButton) {
fireEvent.mouseEnter(bucketButton);
fireEvent.mouseLeave(bucketButton);
}
}
// Click "Mark as visited" — covers lines 979-986 and line 983 (country not in empty list)
await user.click(markButton || screen.getByText(/mark as visited/i));
await waitFor(() => {
expect(screen.queryByText(/mark as visited/i)).not.toBeInTheDocument();
});
} catch {
// Popup didn't appear — acceptable
expect(searchInput).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-050: choose popup offers Remove from wishlist for a bucket-list country', () => {
it('shows Remove from wishlist when the searched country is already on the bucket list, and removing it clears the item', async () => {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(emptyAtlasResponse)),
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
http.get('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({
items: [{ id: 42, name: 'Paris', country_code: 'FR', lat: null, lng: null, notes: null, target_date: null }],
}),
),
http.delete('/api/addons/atlas/bucket-list/:id', () => HttpResponse.json({ success: true })),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
fireEvent.keyDown(searchInput, { key: 'Enter' });
await waitFor(() => {
expect(screen.getByText(/remove from wishlist/i)).toBeInTheDocument();
});
await user.click(screen.getByText(/remove from wishlist/i));
await waitFor(() => {
expect(screen.queryByText(/remove from wishlist/i)).not.toBeInTheDocument();
});
// Bucket List tab no longer shows the removed item
await user.click(screen.getAllByText('Bucket List')[0]);
await waitFor(() => {
expect(screen.queryByText('Paris')).not.toBeInTheDocument();
});
});
it('does not show Remove from wishlist for a country with no bucket-list entry', async () => {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(emptyAtlasResponse)),
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
fireEvent.keyDown(searchInput, { key: 'Enter' });
await waitFor(() => {
expect(screen.getByText(/mark as visited/i)).toBeInTheDocument();
});
expect(screen.queryByText(/remove from wishlist/i)).not.toBeInTheDocument();
});
});
describe('FE-PAGE-ATLAS-036: bucket popup submit action', () => {
it('submits a bucket list item from the confirm popup', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
server.use(
http.post('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({ item: { id: 99, name: 'France', country_code: 'FR', lat: null, lng: null, notes: null, target_date: null } }),
),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
fireEvent.keyDown(searchInput, { key: 'Enter' });
try {
await waitFor(
() => { expect(screen.getByText(/mark as visited/i)).toBeInTheDocument(); },
{ timeout: 3000 },
);
// Switch to 'bucket' type by clicking "Add to bucket list"
const addToBucketBtns = screen.getAllByText(/add to bucket list/i);
await user.click(addToBucketBtns[0]);
// 'bucket' type renders with "when do you plan to visit" + submit button
await waitFor(() => {
expect(screen.getByText(/when do you plan to visit/i)).toBeInTheDocument();
});
// Click the "Add to Bucket" / save button (covers lines 1149-1156)
const addBtn = screen.queryAllByText(/add to bucket/i).find(
(el) => el.tagName === 'BUTTON' || el.closest('button'),
);
if (addBtn) {
const btn = addBtn.tagName === 'BUTTON' ? addBtn as HTMLButtonElement : addBtn.closest('button') as HTMLButtonElement;
await user.click(btn);
// Popup closes after submit
await waitFor(() => {
expect(screen.queryByText(/when do you plan to visit/i)).not.toBeInTheDocument();
});
}
} catch {
// Popup or bucket switch didn't work — acceptable
expect(searchInput).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-037: bucket item with notes renders note text', () => {
it('shows bucket item notes when target_date is absent', async () => {
server.use(
http.get('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({
items: [
{ id: 10, name: 'Patagonia', country_code: 'AR', lat: null, lng: null, notes: 'Dream destination', target_date: null },
],
}),
),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => expect(screen.getByText('Bucket List')).toBeInTheDocument());
await user.click(screen.getByText('Bucket List'));
await waitFor(() => {
expect(screen.getByText('Patagonia')).toBeInTheDocument();
expect(screen.getByText('Dream destination')).toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-038: handleBucketPoiSearch and handleSelectBucketPoi', () => {
it('searching for a POI in bucket form and selecting a result fills the form', async () => {
server.use(
http.post('/api/maps/search', () =>
HttpResponse.json({
places: [
{ name: 'Tokyo', lat: 35.6762, lng: 139.6503, address: 'Japan' },
],
}),
),
http.post('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({ item: { id: 77, name: 'Tokyo', country_code: null, lat: 35.6762, lng: 139.6503, notes: null, target_date: null } }),
),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Switch to bucket tab
await waitFor(() => expect(screen.getByText('Bucket List')).toBeInTheDocument());
await user.click(screen.getByText('Bucket List'));
// Open add form
await waitFor(() => expect(screen.getAllByRole('button', { name: /add place/i }).length).toBeGreaterThan(0));
await user.click(screen.getAllByRole('button', { name: /add place/i })[0]);
// Type in search field
const nameInput = await screen.findByPlaceholderText(/name \(country, city, place\.\.\.\)/i);
await user.type(nameInput, 'Tokyo');
// Press Enter to trigger search (or click search button)
fireEvent.keyDown(nameInput, { key: 'Enter' });
// Wait for Tokyo result to appear
const tokyoResult = await waitFor(
() => {
const els = screen.queryAllByText('Tokyo');
// Filter to those that are inside the search results dropdown (not the input itself)
const resultEl = els.find((el) => el.tagName !== 'INPUT' && el.closest('div[style*="position: fixed"]'));
if (!resultEl) throw new Error('Tokyo result not found in dropdown');
return resultEl;
},
{ timeout: 3000 },
).catch(() => null);
if (tokyoResult) {
// Click the Tokyo result → handleSelectBucketPoi
const resultBtn = tokyoResult.closest('button') as HTMLButtonElement;
if (resultBtn) {
await user.click(resultBtn);
}
// Form should now have Tokyo as the name
await waitFor(() => {
expect(nameInput).toHaveValue('Tokyo');
});
// Click Add to submit → handleAddBucketItem
const addBtn = screen.queryAllByRole('button').find((b) => b.textContent?.trim() === 'Add' || b.textContent?.trim() === 'add');
if (addBtn) {
await user.click(addBtn);
}
} else {
// Search results didn't appear — just verify form is there
expect(nameInput).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-040: GeoJSON loop builds A2_TO_A3 for novel code', () => {
it('GeoJSON with a code not in A2_TO_A3_BASE covers A2_TO_A3[a2] = a3 assignment', async () => {
const geoJsonWithXK = {
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: { ISO_A2: 'XK', ADM0_A3: 'XKX', ISO_A3: 'XKX', NAME: 'Kosovo', ADMIN: 'Kosovo' },
geometry: null,
},
],
};
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithXK)),
);
render(<AtlasPage />);
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
// XK is not in A2_TO_A3_BASE, so the geoJSON loop covers the `A2_TO_A3[a2] = a3` line
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
describe('FE-PAGE-ATLAS-041: country search falls back from A3 when ISO_A2 is invalid', () => {
it.each([
{ a3: 'FRA', name: 'France', query: 'france' },
{ a3: 'NOR', name: 'Norway', query: 'norway' },
])('returns $name in search results when GeoJSON provides ADM0_A3=$a3 but ISO_A2 is -99', async ({ a3, name, query }) => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(makeGeoJsonWithA3Fallback(a3, name))),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => {
expect(screen.getByPlaceholderText(/search a country/i)).toBeInTheDocument();
});
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, query);
await waitFor(() => {
const countryButton = screen.getAllByRole('button').find((button) => button.textContent?.includes(name));
expect(countryButton).toBeTruthy();
});
});
});
describe('FE-PAGE-ATLAS-042: bucket form submit with actual name value', () => {
it('submitting bucket form with a non-empty name covers handleAddBucketItem', async () => {
server.use(
http.post('/api/maps/search', () =>
HttpResponse.json({
places: [{ name: 'Bali', lat: -8.3405, lng: 115.0920, address: 'Indonesia' }],
}),
),
http.post('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({ item: { id: 55, name: 'Bali', country_code: 'ID', lat: -8.3405, lng: 115.0920, notes: null, target_date: null } }),
),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Switch to bucket tab
await waitFor(() => expect(screen.getByText('Bucket List')).toBeInTheDocument());
await user.click(screen.getByText('Bucket List'));
// Open add form
await waitFor(() => expect(screen.getAllByRole('button', { name: /add place/i }).length).toBeGreaterThan(0));
await user.click(screen.getAllByRole('button', { name: /add place/i })[0]);
const nameInput = await screen.findByPlaceholderText(/name \(country, city, place\.\.\.\)/i);
// Type "Bali" — goes to setBucketSearch since bucketForm.name is initially empty
await user.type(nameInput, 'Bali');
expect(nameInput).toHaveValue('Bali');
// Press Enter → handleBucketPoiSearch (since bucketForm.name is empty, key 'Enter' triggers search)
fireEvent.keyDown(nameInput, { key: 'Enter' });
// Wait for Bali in the dropdown results
const baliResult = await waitFor(
() => {
const els = Array.from(document.querySelectorAll('button'));
const el = els.find((e) => e.textContent?.includes('Bali') && e !== nameInput);
if (!el) throw new Error('Bali result not found');
return el;
},
{ timeout: 3000 },
).catch(() => null);
if (baliResult) {
// Click Bali result → handleSelectBucketPoi (sets bucketForm.name='Bali', lat/lng)
await user.click(baliResult);
// Now bucketForm.name is set — the "Add" button should be enabled
await waitFor(() => {
const addBtns = screen.queryAllByRole('button').filter(b => b.textContent?.includes('Add') || b.textContent?.trim() === 'Add');
return addBtns.length > 0;
}).catch(() => {});
// Find and click the Add button (should be enabled now since bucketForm.name is set)
const addButtons = screen.queryAllByRole('button').filter(
(b) => !(b as HTMLButtonElement).disabled && (b.textContent?.trim() === 'Add' || b.textContent?.includes('Add')),
);
if (addButtons.length > 0) {
await user.click(addButtons[addButtons.length - 1]);
// handleAddBucketItem fires → apiClient.post → item added to list
}
} else {
// Fallback — just verify form is working
expect(nameInput).toBeInTheDocument();
}
});
});
describe('FE-PAGE-ATLAS-043: API error in Promise.all covers catch branch', () => {
it('when stats API fails, loading is set to false via catch handler', async () => {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.error()),
);
render(<AtlasPage />);
// Spinner shows briefly while data loads
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
// After error, setLoading(false) runs in catch → loading spinner disappears
await waitFor(() => {
expect(document.querySelector('.animate-spin')).not.toBeInTheDocument();
});
});
});
describe('FE-PAGE-ATLAS-044: direct France dropdown button click', () => {
it('directly finds and clicks the France button in the dropdown to cover onClick', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
server.use(
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
);
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => screen.getByPlaceholderText(/search a country/i));
const searchInput = screen.getByPlaceholderText(/search a country/i);
await user.type(searchInput, 'fr');
// After typing, look for any span/button that contains France text (dropdown renders)
// Use direct DOM query since the dropdown is in the document
let clicked = false;
await waitFor(() => {
// Find all elements containing 'France' in text
const allElements = Array.from(document.querySelectorAll('button, span'));
const franceElements = allElements.filter(
(el) => el.textContent?.trim() === 'France' || el.textContent?.includes('France'),
);
// Try to find a button that's a dropdown item (not the main search area)
for (const el of franceElements) {
const btn = el.tagName === 'BUTTON' ? el : el.closest('button');
if (btn && (btn as HTMLButtonElement).style?.width === '100%') {
fireEvent.click(btn);
clicked = true;
return;
}
}
throw new Error('France dropdown button not found');
}, { timeout: 3000 }).catch(() => {
// Not found — use Enter key as fallback to at minimum cover select_country_from_search
fireEvent.keyDown(searchInput, { key: 'Enter' });
});
// Verify popup or search input is still visible
await waitFor(() => {
const popup = screen.queryByText(/mark as visited/i);
if (popup) {
expect(popup).toBeInTheDocument();
} else {
expect(searchInput).toBeInTheDocument();
}
});
});
});
describe('FE-PAGE-ATLAS-045: dark mode toggle covers map re-init + loadRegionsForViewport', () => {
it('switching to dark mode re-initializes map and covers region loading code path', async () => {
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonWithFR)),
);
server.use(
http.get('/api/addons/atlas/regions/geo/:code', () => HttpResponse.json({ features: [] })),
);
render(<AtlasPage />);
// Wait for initial data to load and geoJSON layer to be built
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
// Change dark mode setting — this re-triggers the map init useEffect [dark]
// which calls map.on('zoomend', ...) with zoom=5 (our mock).
// At this point, country_layer_by_a2_ref has FR → loadRegionsForViewport runs
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: true }) });
// After dark mode change, the page re-renders and map re-initializes
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
});
describe('FE-PAGE-ATLAS-046: clear button in bucket form covers line 1321', () => {
it('clicking the X clear button after POI selection covers line 1321 onClick', async () => {
server.use(
http.post('/api/maps/search', () =>
HttpResponse.json({
places: [{ name: 'Paris', lat: 48.8566, lng: 2.3522, address: 'France' }],
}),
),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Switch to bucket tab
await waitFor(() => expect(screen.getByText('Bucket List')).toBeInTheDocument());
await user.click(screen.getByText('Bucket List'));
// Open add form
await waitFor(() => expect(screen.getAllByRole('button', { name: /add place/i }).length).toBeGreaterThan(0));
await user.click(screen.getAllByRole('button', { name: /add place/i })[0]);
// Type and press Enter to trigger handleBucketPoiSearch
const nameInput = await screen.findByPlaceholderText(/name \(country, city, place\.\.\.\)/i);
await user.type(nameInput, 'Paris');
fireEvent.keyDown(nameInput, { key: 'Enter' });
// Wait for Paris result in the dropdown (portalled, fixed-position list)
const parisBtn = await waitFor(
() => {
const btns = Array.from(document.querySelectorAll('button'));
const btn = btns.find(
(b) => b.textContent?.includes('Paris') && b.closest('[style*="position: fixed"]'),
);
if (!btn) throw new Error('Paris dropdown result not found');
return btn;
},
{ timeout: 3000 },
);
// Click result → handleSelectBucketPoi → sets bucketForm.name='Paris', lat/lng
await user.click(parisBtn);
// Wait for the input to show 'Paris' (bucketForm.name is now set)
await waitFor(() => {
expect(nameInput).toHaveValue('Paris');
});
// Clear button now renders (bucketForm.name truthy).
// It is the only button in the flex container that holds the input.
const clearBtn = nameInput.parentElement?.querySelector('button') as HTMLButtonElement | null;
if (clearBtn) {
await user.click(clearBtn);
}
// After clear: bucketForm.name='', bucketSearch='' → input shows ''
await waitFor(() => {
expect(nameInput).toHaveValue('');
}).catch(() => {});
expect(nameInput).toBeInTheDocument();
});
});
describe('FE-PAGE-ATLAS-047: layer click triggers handleUnmarkCountry + executeConfirmAction', () => {
it('clicking a visited country with no trips/places opens unmark popup and confirms it', async () => {
// Use atlas stats with IT (placeCount=0, tripCount=0) — qualifies for handleUnmarkCountry
const statsWithIT = {
...atlasStatsResponse,
countries: [
{ code: 'FR', tripCount: 2, placeCount: 5, firstVisit: '2023-01-01', lastVisit: '2024-06-01' },
{ code: 'IT', tripCount: 0, placeCount: 0, firstVisit: null, lastVisit: null },
],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 2, totalDays: 14, totalCities: 3 },
};
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(statsWithIT)),
http.delete('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
);
// Provide GeoJSON with both FR and IT features
// IT (ITA) is in A2_TO_A3_BASE so countryMap['ITA'] = IT country data
const geoJsonFRandIT = {
type: 'FeatureCollection',
features: [
{ type: 'Feature', properties: { ISO_A2: 'FR', ADM0_A3: 'FRA', ISO_A3: 'FRA', NAME: 'France', ADMIN: 'France' }, geometry: null },
{ type: 'Feature', properties: { ISO_A2: 'IT', ADM0_A3: 'ITA', ISO_A3: 'ITA', NAME: 'Italy', ADMIN: 'Italy' }, geometry: null },
],
};
server.use(
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(geoJsonFRandIT)),
);
render(<AtlasPage />);
// Wait for data to load and geoJSON layer to be built.
// The layer mock immediately invokes click callbacks: IT (placeCount=0, tripCount=0)
// → handleUnmarkCountry('IT') → setConfirmAction({ type: 'unmark', code: 'IT', name: 'Italy' })
await waitFor(() => {
// The unmark popup shows t('atlas.unmark') = 'Remove' button
expect(
screen.queryAllByRole('button').some((b) => b.textContent?.trim() === 'Remove'),
).toBe(true);
}, { timeout: 5000 });
// Find and click the "Remove" button (atlas.unmark) → executeConfirmAction runs
const removeBtn = screen.queryAllByRole('button').find((b) => b.textContent?.trim() === 'Remove');
if (removeBtn) {
fireEvent.click(removeBtn);
}
// After executeConfirmAction: popup closes
await waitFor(() => {
expect(screen.queryAllByRole('button').some((b) => b.textContent?.trim() === 'Remove')).toBe(false);
}, { timeout: 3000 }).catch(() => {});
// Page is still rendered
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
describe('FE-PAGE-ATLAS-048: clicking a visited (place-derived, not manually-marked) region opens the hide-region popup', () => {
it('offers to remove a region that came from real place data, not just a manually-marked one', async () => {
// FR keeps real tripCount/placeCount from atlasStatsResponse so the country layer's
// own click handler (only active for a zero-count country) stays a no-op — this test
// is only about the region layer. The region entry has no `manuallyMarked` flag,
// which used to make a region click open the country-detail view instead of an
// unmark option at all.
server.use(
http.get('/api/addons/atlas/regions', () => HttpResponse.json({
regions: { FR: [{ code: 'FR-IDF', name: 'Île-de-France', placeCount: 3 }] },
})),
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json({
type: 'FeatureCollection',
features: [{ type: 'Feature', properties: { ISO_A2: 'FR', ADM0_A3: 'FRA', ISO_A3: 'FRA', NAME: 'France', ADMIN: 'France' }, geometry: null }],
})),
http.get('/api/addons/atlas/regions/geo/:code', () => HttpResponse.json({
type: 'FeatureCollection',
features: [{ type: 'Feature', properties: { iso_a2: 'FR', iso_3166_2: 'FR-IDF', name: 'Île-de-France', name_en: 'Île-de-France', admin: 'France' }, geometry: null }],
})),
http.delete('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ success: true })),
);
render(<AtlasPage />);
// Wait for initial data to load before the region layer can build (loadRegionsForViewport
// needs country_layer_by_a2_ref already populated, which only happens once the country
// layer's own effect has run) — see FE-PAGE-ATLAS-045 for the same recipe. Toggling dark
// mode re-initializes the map, re-registers zoomend, and by then FR's country layer
// already exists, so loadRegionsForViewport actually fetches /regions/geo this time.
await waitFor(() => {
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: true }) });
// The layer mock immediately invokes click callbacks once the region layer is built:
// FR-IDF is visited (place-derived) → confirmAction becomes { type: 'unmark-region', ... }
await waitFor(() => {
expect(
screen.queryAllByRole('button').some((b) => b.textContent?.trim() === 'Remove'),
).toBe(true);
}, { timeout: 5000 });
const removeBtn = screen.queryAllByRole('button').find((b) => b.textContent?.trim() === 'Remove');
if (removeBtn) {
fireEvent.click(removeBtn);
}
await waitFor(() => {
expect(screen.queryAllByRole('button').some((b) => b.textContent?.trim() === 'Remove')).toBe(false);
}, { timeout: 3000 }).catch(() => {});
expect(screen.getAllByText(/countr(y|ies)/i).length).toBeGreaterThan(0);
});
});
describe('FE-PAGE-ATLAS-039: bucket item with lat/lng renders on map (markers useEffect)', () => {
it('renders bucket items with coordinates causing marker useEffect to run', async () => {
server.use(
http.get('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({
items: [
{ id: 20, name: 'Machu Picchu', country_code: 'PE', lat: -13.1631, lng: -72.5450, notes: null, target_date: '2028-06' },
],
}),
),
);
const user = userEvent.setup();
render(<AtlasPage />);
// Switch to bucket tab so bucket items render
await waitFor(() => expect(screen.getByText('Bucket List')).toBeInTheDocument());
await user.click(screen.getByText('Bucket List'));
await waitFor(() => {
expect(screen.getByText('Machu Picchu')).toBeInTheDocument();
});
// target_date renders as formatted date
// The item is in the bucket list — also verifies the bucket list useEffect ran (lat/lng → marker)
expect(screen.getByText('Machu Picchu')).toBeInTheDocument();
});
});
describe('FE-PAGE-ATLAS-052: the Tours tab shows the own tour activities (STA-02)', () => {
it('offers the tab only with the Tours addon and reads the activities once it is opened', async () => {
let reads = 0;
server.use(
http.get('/api/tours/activity-stats', () => {
reads += 1;
return HttpResponse.json({ entries: [], uncounted: { unassigned: 0, undated: 0 } });
}),
);
const first = render(<AtlasPage />);
await waitFor(() => expect(screen.getByText('Bucket List')).toBeInTheDocument());
expect(screen.queryByRole('button', { name: 'Tours' })).not.toBeInTheDocument();
first.unmount();
seedStore(useAddonStore, {
addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: 'route', enabled: true }],
});
const user = userEvent.setup();
render(<AtlasPage />);
await waitFor(() => expect(screen.getByRole('button', { name: 'Tours' })).toBeInTheDocument());
expect(reads).toBe(0);
await user.click(screen.getByRole('button', { name: 'Tours' }));
await waitFor(() => expect(screen.getByText('No completed tours yet')).toBeInTheDocument());
expect(reads).toBe(1);
});
});
});