mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 06:37:33 +00:00
test(components): cover map, collections, settings, journey and admin
This commit is contained in:
@@ -0,0 +1,88 @@
|
||||
// FE-COMP-MAPCOMPASS-001 to FE-COMP-MAPCOMPASS-006
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent, act } from '../../../tests/helpers/render'
|
||||
import { MapCompassPill, type CompassMap } from './MapCompassPill'
|
||||
|
||||
function fakeCompassMap(initialBearing = 0) {
|
||||
const listeners: Array<() => void> = []
|
||||
let bearing = initialBearing
|
||||
const map = {
|
||||
getBearing: vi.fn(() => bearing),
|
||||
on: vi.fn((_type: 'rotate', fn: () => void) => { listeners.push(fn) }),
|
||||
off: vi.fn((_type: 'rotate', fn: () => void) => {
|
||||
const i = listeners.indexOf(fn)
|
||||
if (i >= 0) listeners.splice(i, 1)
|
||||
}),
|
||||
easeTo: vi.fn(),
|
||||
}
|
||||
return {
|
||||
map: map as unknown as CompassMap,
|
||||
spies: map,
|
||||
listenerCount: () => listeners.length,
|
||||
rotateTo: (next: number) => {
|
||||
bearing = next
|
||||
act(() => { listeners.forEach(fn => fn()) })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const needle = () => screen.getByRole('button', { name: 'Reset north' }).querySelector('svg') as SVGElement
|
||||
|
||||
describe('MapCompassPill', () => {
|
||||
it('FE-COMP-MAPCOMPASS-001: points the needle against the current map bearing', () => {
|
||||
const { map } = fakeCompassMap(45)
|
||||
render(<MapCompassPill map={map} />)
|
||||
// The map rotated 45° clockwise, so the needle turns 45° back to keep pointing north.
|
||||
expect(needle().style.transform).toBe('rotate(-45deg)')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-002: follows the map while it rotates', () => {
|
||||
const compass = fakeCompassMap(0)
|
||||
render(<MapCompassPill map={compass.map} />)
|
||||
expect(needle().style.transform).toBe('rotate(0deg)')
|
||||
|
||||
compass.rotateTo(120)
|
||||
expect(needle().style.transform).toBe('rotate(-120deg)')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-003: snaps the camera back to north and flat on click', () => {
|
||||
const compass = fakeCompassMap(75)
|
||||
render(<MapCompassPill map={compass.map} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Reset north' }))
|
||||
expect(compass.spies.easeTo).toHaveBeenCalledWith({ bearing: 0, pitch: 0, duration: 300 })
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-004: unsubscribes from the rotate event on unmount', () => {
|
||||
const compass = fakeCompassMap(0)
|
||||
const { unmount } = render(<MapCompassPill map={compass.map} />)
|
||||
expect(compass.listenerCount()).toBe(1)
|
||||
|
||||
unmount()
|
||||
expect(compass.spies.off).toHaveBeenCalledWith('rotate', expect.any(Function))
|
||||
expect(compass.listenerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-005: resubscribes when the map instance is swapped (style rebuild)', () => {
|
||||
const first = fakeCompassMap(10)
|
||||
const second = fakeCompassMap(200)
|
||||
const { rerender } = render(<MapCompassPill map={first.map} />)
|
||||
|
||||
rerender(<MapCompassPill map={second.map} />)
|
||||
expect(first.listenerCount()).toBe(0)
|
||||
expect(second.listenerCount()).toBe(1)
|
||||
expect(needle().style.transform).toBe('rotate(-200deg)')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPCOMPASS-006: highlights the button on hover and clears it again', () => {
|
||||
const { map } = fakeCompassMap(0)
|
||||
render(<MapCompassPill map={map} />)
|
||||
const button = screen.getByRole('button', { name: 'Reset north' })
|
||||
|
||||
fireEvent.mouseEnter(button)
|
||||
expect(button.style.background).toBe('var(--bg-hover)')
|
||||
fireEvent.mouseLeave(button)
|
||||
expect(button.style.background).toBe('transparent')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,211 @@
|
||||
// FE-COMP-MAPPLUGINLAYERS-001 to FE-COMP-MAPPLUGINLAYERS-009
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import type { PluginMapLayer, PluginMapLayerFeature } from '../../api/client'
|
||||
|
||||
interface PathProps {
|
||||
positions?: [number, number][]
|
||||
center?: [number, number]
|
||||
radius?: number
|
||||
pathOptions?: Record<string, unknown>
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
// react-leaflet primitives are replaced by markers that surface exactly what the
|
||||
// component controls: geometry, the path options and the pane it draws into.
|
||||
const mapHolder = vi.hoisted(() => ({ current: {} as Record<string, unknown> }))
|
||||
|
||||
vi.mock('react-leaflet', () => ({
|
||||
Polyline: ({ positions, pathOptions, children }: PathProps) => (
|
||||
<div data-testid="polyline" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>{children}</div>
|
||||
),
|
||||
Polygon: ({ positions, pathOptions, children }: PathProps) => (
|
||||
<div data-testid="polygon" data-points={JSON.stringify(positions)} data-path-options={JSON.stringify(pathOptions)}>{children}</div>
|
||||
),
|
||||
Circle: ({ center, radius, pathOptions, children }: PathProps) => (
|
||||
<div data-testid="circle" data-center={JSON.stringify(center)} data-radius={radius} data-path-options={JSON.stringify(pathOptions)}>{children}</div>
|
||||
),
|
||||
Tooltip: ({ children }: { children?: React.ReactNode }) => <span data-testid="tooltip">{children}</span>,
|
||||
useMap: () => mapHolder.current,
|
||||
}))
|
||||
|
||||
import { PluginMapLayers } from './MapPluginLayers'
|
||||
|
||||
function paneMap(preexisting = false) {
|
||||
const panes = new Map<string, HTMLElement>()
|
||||
if (preexisting) panes.set('trek-plugin-layers', document.createElement('div'))
|
||||
return {
|
||||
panes,
|
||||
getPane: vi.fn((name: string) => panes.get(name)),
|
||||
createPane: vi.fn((name: string) => {
|
||||
const el = document.createElement('div')
|
||||
panes.set(name, el)
|
||||
return el
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
function feature(overrides: Partial<PluginMapLayerFeature> = {}): PluginMapLayerFeature {
|
||||
return {
|
||||
type: 'polyline',
|
||||
points: [[48.85, 2.35], [48.86, 2.36]],
|
||||
tone: 'default',
|
||||
width: 3,
|
||||
dash: 'solid',
|
||||
opacity: 0.8,
|
||||
fill: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function layer(features: PluginMapLayerFeature[], overrides: Partial<PluginMapLayer> = {}): PluginMapLayer {
|
||||
return { pluginId: 'ev-router', id: 'corridor', features, ...overrides }
|
||||
}
|
||||
|
||||
function serveLayers(layers: PluginMapLayer[]) {
|
||||
server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ layers })))
|
||||
}
|
||||
|
||||
const optionsOf = (el: HTMLElement) => JSON.parse(el.getAttribute('data-path-options') || '{}') as Record<string, unknown>
|
||||
|
||||
beforeEach(() => {
|
||||
mapHolder.current = paneMap() as unknown as Record<string, unknown>
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('PluginMapLayers', () => {
|
||||
it('FE-COMP-MAPPLUGINLAYERS-001: renders nothing without a trip', async () => {
|
||||
let requests = 0
|
||||
server.use(http.get('/api/map-layers/:tripId', () => { requests += 1; return HttpResponse.json({ layers: [] }) }))
|
||||
|
||||
render(<PluginMapLayers />)
|
||||
await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull())
|
||||
expect(requests).toBe(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-002: creates the below-overlay pane and draws into it', async () => {
|
||||
const map = paneMap()
|
||||
mapHolder.current = map as unknown as Record<string, unknown>
|
||||
serveLayers([layer([feature()])])
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
|
||||
expect(map.createPane).toHaveBeenCalledWith('trek-plugin-layers')
|
||||
// Core geometry (overlayPane, 400) has to stay on top of plugin shapes.
|
||||
expect(map.panes.get('trek-plugin-layers')?.style.zIndex).toBe('399')
|
||||
expect(optionsOf(line).pane).toBe('trek-plugin-layers')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-003: reuses an existing pane instead of creating a second one', async () => {
|
||||
const map = paneMap(true)
|
||||
mapHolder.current = map as unknown as Record<string, unknown>
|
||||
serveLayers([layer([feature()])])
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
|
||||
expect(map.createPane).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-004: still draws on a map without the pane API, just without a pane', async () => {
|
||||
mapHolder.current = {}
|
||||
serveLayers([layer([feature()])])
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
expect(optionsOf(line)).not.toHaveProperty('pane')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-005: draws polylines, polygons and metric circles', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ type: 'polyline' }),
|
||||
feature({ type: 'polygon', points: [[48, 2], [48, 3], [49, 3]] }),
|
||||
feature({ type: 'circle', points: undefined, center: [48.8, 2.3], radiusM: 750 }),
|
||||
])])
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
|
||||
expect(JSON.parse(screen.getByTestId('polygon').getAttribute('data-points') || '')).toEqual([[48, 2], [48, 3], [49, 3]])
|
||||
const circle = screen.getByTestId('circle')
|
||||
expect(JSON.parse(circle.getAttribute('data-center') || '')).toEqual([48.8, 2.3])
|
||||
expect(circle.getAttribute('data-radius')).toBe('750')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-006: maps tone, width, dash and fill onto the leaflet path options', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ tone: 'danger', width: 6, dash: 'dash', opacity: 0.5 }),
|
||||
feature({ type: 'polygon', tone: 'success', dash: 'dot', opacity: 0.9, fill: true }),
|
||||
])])
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
|
||||
expect(optionsOf(line)).toMatchObject({
|
||||
color: '#ef4444',
|
||||
weight: 6,
|
||||
opacity: 0.5,
|
||||
dashArray: '8, 8',
|
||||
fill: false,
|
||||
fillOpacity: 0,
|
||||
})
|
||||
// A filled shape is capped at 0.25 so it never hides the basemap underneath.
|
||||
expect(optionsOf(screen.getByTestId('polygon'))).toMatchObject({
|
||||
color: '#10b981',
|
||||
dashArray: '1, 7',
|
||||
fill: true,
|
||||
fillOpacity: 0.25,
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-007: only a labelled feature gets a tooltip and stays clickable', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ label: 'Charging corridor' }),
|
||||
feature({ type: 'polygon' }),
|
||||
])])
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
const line = await screen.findByTestId('polyline')
|
||||
|
||||
expect(screen.getByTestId('tooltip')).toHaveTextContent('Charging corridor')
|
||||
expect(optionsOf(line).interactive).toBe(true)
|
||||
// Unlabelled shapes must never steal a map click.
|
||||
expect(optionsOf(screen.getByTestId('polygon')).interactive).toBe(false)
|
||||
expect(screen.getAllByTestId('tooltip')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-008: skips features whose geometry is incomplete', async () => {
|
||||
serveLayers([layer([
|
||||
feature({ type: 'polyline', points: undefined }),
|
||||
feature({ type: 'polygon', points: undefined }),
|
||||
feature({ type: 'circle', points: undefined, center: [48, 2] }),
|
||||
feature({ type: 'circle', points: undefined, radiusM: 500 }),
|
||||
feature({ label: 'kept' }),
|
||||
])])
|
||||
|
||||
render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
|
||||
expect(screen.getAllByTestId('polyline')).toHaveLength(1)
|
||||
expect(screen.queryByTestId('polygon')).toBeNull()
|
||||
expect(screen.queryByTestId('circle')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPPLUGINLAYERS-009: a failing request leaves the map without plugin overlays', async () => {
|
||||
serveLayers([layer([feature()])])
|
||||
const { rerender } = render(<PluginMapLayers tripId={4} />)
|
||||
await screen.findByTestId('polyline')
|
||||
|
||||
server.use(http.get('/api/map-layers/:tripId', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
|
||||
rerender(<PluginMapLayers tripId={9} />)
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId('polyline')).toBeNull())
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import { fireEvent, waitFor } from '@testing-library/react'
|
||||
import { act, fireEvent, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { resetAllStores } from '../../../tests/helpers/store'
|
||||
import { buildPlace, buildReservation } from '../../../tests/helpers/factories'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { CATEGORY_ICON_MAP } from '../shared/categoryIcons'
|
||||
import * as photoService from '../../services/photoService'
|
||||
|
||||
const mapMock = vi.hoisted(() => ({
|
||||
@@ -16,19 +18,50 @@ const mapMock = vi.hoisted(() => ({
|
||||
off: vi.fn(),
|
||||
panBy: vi.fn(),
|
||||
latLngToContainerPoint: vi.fn(() => ({ x: 0, y: 0, distanceTo: () => 1000 })),
|
||||
// Panes: jsdom has none, so keep them in a map the pane tests can read back.
|
||||
panes: new Map<string, HTMLElement>(),
|
||||
getPane: vi.fn(function (this: void, name: string) { return mapMock.panes.get(name) }),
|
||||
createPane: vi.fn(function (this: void, name: string) {
|
||||
const el = document.createElement('div')
|
||||
mapMock.panes.set(name, el)
|
||||
return el
|
||||
}),
|
||||
getBounds: vi.fn(() => ({ getSouth: () => 47, getWest: () => 1, getNorth: () => 49, getEast: () => 3 })),
|
||||
whenReady: vi.fn((cb: () => void) => { cb() }),
|
||||
}))
|
||||
|
||||
// Live-location fixture; tests flip this before rendering.
|
||||
const geoMock = vi.hoisted(() => ({
|
||||
position: null as { lat: number; lng: number; accuracy: number; heading: number | null } | null,
|
||||
mode: 'off' as 'off' | 'show' | 'follow',
|
||||
error: null as string | null,
|
||||
cycleMode: vi.fn(),
|
||||
setMode: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../hooks/useGeolocation', () => ({
|
||||
useGeolocation: () => geoMock,
|
||||
}))
|
||||
|
||||
// onThumbReady callbacks are captured so a test can play back a photo landing
|
||||
// after the map already rendered.
|
||||
const thumbCallbacks = vi.hoisted(() => new Map<string, (thumb: string) => void>())
|
||||
|
||||
vi.mock('react-leaflet', () => ({
|
||||
// center/zoom are surfaced so tests can assert the camera the map is built with.
|
||||
MapContainer: ({ children, center, zoom }: any) => (
|
||||
<div data-testid="map-container" data-center={JSON.stringify(center)} data-zoom={zoom}>{children}</div>
|
||||
),
|
||||
TileLayer: () => <div data-testid="tile-layer" />,
|
||||
Marker: ({ children, eventHandlers, position }: any) => (
|
||||
Marker: ({ children, eventHandlers, position, icon, zIndexOffset }: any) => (
|
||||
<div
|
||||
data-testid="marker"
|
||||
data-lat={position[0]}
|
||||
data-lng={position[1]}
|
||||
data-zindex={zIndexOffset}
|
||||
// The divIcon mock hands its options straight back, so the generated
|
||||
// marker HTML is assertable without a real Leaflet.
|
||||
data-icon-html={icon?.html ?? ''}
|
||||
onClick={() => eventHandlers?.click?.()}
|
||||
>
|
||||
<button
|
||||
@@ -37,6 +70,14 @@ vi.mock('react-leaflet', () => ({
|
||||
// hover-simulation must not trigger the marker's click handler.
|
||||
onClick={(e: any) => { e.stopPropagation(); eventHandlers?.mouseover?.({ originalEvent: { clientX: 100, clientY: 100 } }) }}
|
||||
/>
|
||||
<button
|
||||
data-testid="marker-move-trigger"
|
||||
onClick={(e: any) => { e.stopPropagation(); eventHandlers?.mousemove?.({ originalEvent: { clientX: 150, clientY: 160 } }) }}
|
||||
/>
|
||||
<button
|
||||
data-testid="marker-out-trigger"
|
||||
onClick={(e: any) => { e.stopPropagation(); eventHandlers?.mouseout?.() }}
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
@@ -64,27 +105,42 @@ vi.mock('react-leaflet', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('react-leaflet-cluster', () => ({
|
||||
default: ({ children }: any) => <div data-testid="cluster-group">{children}</div>,
|
||||
// The real cluster group calls iconCreateFunction itself; the probe button
|
||||
// lets a test invoke it with a chosen child count.
|
||||
default: ({ children, iconCreateFunction }: any) => (
|
||||
<div data-testid="cluster-group">
|
||||
<button
|
||||
data-testid="cluster-icon-probe"
|
||||
onClick={(e: any) => {
|
||||
const count = Number(e.currentTarget.getAttribute('data-count') || 0)
|
||||
const icon = iconCreateFunction?.({ getChildCount: () => count })
|
||||
e.currentTarget.setAttribute('data-icon-html', icon?.html ?? '')
|
||||
}}
|
||||
/>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
vi.mock('leaflet', () => ({
|
||||
default: {
|
||||
divIcon: vi.fn(() => ({})),
|
||||
vi.mock('leaflet', () => {
|
||||
const divIcon = vi.fn((options: any) => ({ ...options }))
|
||||
const leaflet = {
|
||||
divIcon,
|
||||
Icon: { Default: { prototype: {}, mergeOptions: vi.fn() } },
|
||||
latLngBounds: vi.fn(() => ({ isValid: () => true })),
|
||||
point: vi.fn((x: number, y: number) => [x, y]),
|
||||
},
|
||||
divIcon: vi.fn(() => ({})),
|
||||
Icon: { Default: { prototype: {}, mergeOptions: vi.fn() } },
|
||||
latLngBounds: vi.fn(() => ({ isValid: () => true })),
|
||||
point: vi.fn((x: number, y: number) => [x, y]),
|
||||
}))
|
||||
}
|
||||
return { default: leaflet, ...leaflet }
|
||||
})
|
||||
|
||||
vi.mock('../../services/photoService', () => ({
|
||||
getCached: vi.fn(() => null),
|
||||
isLoading: vi.fn(() => false),
|
||||
fetchPhoto: vi.fn(),
|
||||
onThumbReady: vi.fn(() => () => {}),
|
||||
onThumbReady: vi.fn((key: string, cb: (thumb: string) => void) => {
|
||||
thumbCallbacks.set(key, cb)
|
||||
return () => { thumbCallbacks.delete(key) }
|
||||
}),
|
||||
getAllThumbs: vi.fn(() => ({})),
|
||||
}))
|
||||
|
||||
@@ -102,9 +158,17 @@ function buildMapPlace(overrides: Record<string, any> = {}) {
|
||||
} as any
|
||||
}
|
||||
|
||||
const ORIGINAL_WIDTH = window.innerWidth
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetAllStores()
|
||||
mapMock.panes.clear()
|
||||
thumbCallbacks.clear()
|
||||
geoMock.position = null
|
||||
geoMock.mode = 'off'
|
||||
geoMock.error = null
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: ORIGINAL_WIDTH })
|
||||
})
|
||||
|
||||
describe('MapView', () => {
|
||||
@@ -456,4 +520,491 @@ describe('MapView', () => {
|
||||
render(<MapView reservations={[reservation]} visibleConnectionIds={[42]} />)
|
||||
expect(screen.getAllByTestId('polyline').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-073: a category icon that throws leaves the marker circle intact', () => {
|
||||
// Icon components come from a lookup table a plugin can extend; one that
|
||||
// throws must not take the whole map down, only its own glyph.
|
||||
const key = '__ExplodingIcon'
|
||||
CATEGORY_ICON_MAP[key] = (() => { throw new Error('icon blew up') }) as unknown as typeof CATEGORY_ICON_MAP['MapPin']
|
||||
try {
|
||||
render(<MapView places={[buildMapPlace({ id: 5, lat: 48, lng: 2, category_icon: key })]} />)
|
||||
const html = screen.getByTestId('marker').getAttribute('data-icon-html') || ''
|
||||
expect(html).toContain('border-radius:50%')
|
||||
expect(html).not.toContain('<svg')
|
||||
} finally {
|
||||
delete CATEGORY_ICON_MAP[key]
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// ── FE-COMP-MAPVIEW-030 onwards ───────────────────────────────────────────────
|
||||
|
||||
const leafletMock = async () => ((await import('leaflet')).default) as unknown as {
|
||||
divIcon: ReturnType<typeof vi.fn>
|
||||
latLngBounds: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
const iconHtmlOf = (el: HTMLElement) => el.getAttribute('data-icon-html') || ''
|
||||
const markersWithZ = (z: string) => screen.queryAllByTestId('marker').filter(m => m.getAttribute('data-zindex') === z)
|
||||
const handlerFor = (event: string) => mapMock.on.mock.calls.find(c => c[0] === event)?.[1] as (() => void) | undefined
|
||||
|
||||
function buildPoi(overrides: Record<string, any> = {}) {
|
||||
return {
|
||||
osm_id: 'node/1',
|
||||
name: 'Café Central',
|
||||
lat: 48.21,
|
||||
lng: 16.36,
|
||||
category: 'cafe',
|
||||
poi_type: 'cafe',
|
||||
address: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
opening_hours: null,
|
||||
cuisine: null,
|
||||
source: 'openstreetmap',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('MapView clusters and badges', () => {
|
||||
it('FE-COMP-MAPVIEW-030: the cluster icon grows with the number of markers it hides', () => {
|
||||
render(<MapView places={[buildMapPlace({ id: 1, lat: 48, lng: 2 })]} />)
|
||||
const probe = screen.getByTestId('cluster-icon-probe')
|
||||
|
||||
const iconFor = (count: number) => {
|
||||
probe.setAttribute('data-count', String(count))
|
||||
fireEvent.click(probe)
|
||||
return probe.getAttribute('data-icon-html') || ''
|
||||
}
|
||||
|
||||
expect(iconFor(4)).toContain('width:36px')
|
||||
expect(iconFor(4)).toContain('<span>4</span>')
|
||||
expect(iconFor(20)).toContain('width:42px')
|
||||
expect(iconFor(120)).toContain('width:48px')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-031: a place on one day gets a single order badge', () => {
|
||||
render(<MapView places={[buildMapPlace({ id: 3, lat: 48, lng: 2 })]} dayOrderMap={{ 3: [2] }} />)
|
||||
const html = iconHtmlOf(screen.getAllByTestId('marker')[0])
|
||||
expect(html).toContain('>2</span>')
|
||||
expect(html).toContain('height:18px')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-032: a place visited on several days gets a wider combined badge', () => {
|
||||
render(<MapView places={[buildMapPlace({ id: 4, lat: 48, lng: 2 })]} dayOrderMap={{ 4: [1, 3] }} />)
|
||||
const html = iconHtmlOf(screen.getAllByTestId('marker')[0])
|
||||
expect(html).toContain('>1 · 3</span>')
|
||||
expect(html).toContain('height:16px')
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView explore POIs', () => {
|
||||
it('FE-COMP-MAPVIEW-033: renders a pin per POI in its category colour with a name tooltip', () => {
|
||||
render(<MapView pois={[buildPoi()]} />)
|
||||
const poiMarker = markersWithZ('500')[0]
|
||||
expect(poiMarker).toBeTruthy()
|
||||
expect(iconHtmlOf(poiMarker)).toContain('#B45309') // cafe
|
||||
expect(poiMarker.textContent).toContain('Café Central')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-034: clicking a POI hands the whole POI back to the caller', () => {
|
||||
const onPoiClick = vi.fn()
|
||||
const poi = buildPoi({ osm_id: 'node/7' })
|
||||
render(<MapView pois={[poi]} onPoiClick={onPoiClick} />)
|
||||
fireEvent.click(markersWithZ('500')[0])
|
||||
expect(onPoiClick).toHaveBeenCalledWith(poi)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-035: an unknown POI category falls back to grey and draws no glyph', () => {
|
||||
render(<MapView pois={[buildPoi({ osm_id: 'node/8', category: 'not-a-category' })]} />)
|
||||
const html = iconHtmlOf(markersWithZ('500')[0])
|
||||
expect(html).toContain('#6b7280')
|
||||
expect(html).not.toContain('<svg')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-036: POIs of one category share a single cached icon', async () => {
|
||||
const L = await leafletMock()
|
||||
render(<MapView pois={[
|
||||
buildPoi({ osm_id: 'node/10', category: 'museum' }),
|
||||
buildPoi({ osm_id: 'node/11', category: 'museum', lat: 48.3 }),
|
||||
]} />)
|
||||
const poiIcons = L.divIcon.mock.calls.filter(c => JSON.stringify((c[0] as { iconSize: number[] }).iconSize) === '[26,26]')
|
||||
expect(markersWithZ('500')).toHaveLength(2)
|
||||
expect(poiIcons).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView plugin route vias', () => {
|
||||
const via = (overrides: Record<string, any> = {}) => ({ lat: 48.5, lng: 2.5, tone: 'default', ...overrides })
|
||||
|
||||
it('FE-COMP-MAPVIEW-037: draws a tone dot for each via point', () => {
|
||||
render(<MapView routeVias={[via({ tone: 'success' }), via({ tone: 'danger', lat: 48.7 })]} />)
|
||||
const vias = markersWithZ('800')
|
||||
expect(vias).toHaveLength(2)
|
||||
expect(iconHtmlOf(vias[0])).toContain('#10b981')
|
||||
expect(iconHtmlOf(vias[1])).toContain('#ef4444')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-038: an unknown tone falls back to the default indigo', () => {
|
||||
render(<MapView routeVias={[via({ tone: 'chartreuse' })]} />)
|
||||
expect(iconHtmlOf(markersWithZ('800')[0])).toContain('#4F46E5')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-039: vias of the same tone share one cached icon', async () => {
|
||||
const L = await leafletMock()
|
||||
render(<MapView routeVias={[via({ tone: 'warn' }), via({ tone: 'warn', lat: 48.9 })]} />)
|
||||
const viaIcons = L.divIcon.mock.calls.filter(c => JSON.stringify((c[0] as { iconSize: number[] }).iconSize) === '[13,13]')
|
||||
expect(markersWithZ('800')).toHaveLength(2)
|
||||
expect(viaIcons).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-040: a via tooltip joins its label and its dwell time', () => {
|
||||
render(<MapView routeVias={[via({ label: 'Supercharger', dwellSeconds: 5400 })]} />)
|
||||
expect(markersWithZ('800')[0].textContent).toContain('Supercharger · 1 h 30 min')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-041: a dwell under an hour is shown in minutes alone', () => {
|
||||
render(<MapView routeVias={[via({ dwellSeconds: 1500 })]} />)
|
||||
expect(markersWithZ('800')[0].textContent).toContain('25 min')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-042: a bare via carries no tooltip at all', () => {
|
||||
render(<MapView routeVias={[via()]} />)
|
||||
expect(markersWithZ('800')[0].textContent).toBe('')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-074: a via with a label but no dwell shows the label alone', () => {
|
||||
render(<MapView routeVias={[via({ label: 'Rest area' })]} />)
|
||||
expect(markersWithZ('800')[0].textContent).toBe('Rest area')
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView map event wiring', () => {
|
||||
it('FE-COMP-MAPVIEW-043: reports the viewport bbox once the map is ready and again on every move', () => {
|
||||
const onViewportChange = vi.fn()
|
||||
render(<MapView onViewportChange={onViewportChange} />)
|
||||
expect(onViewportChange).toHaveBeenCalledWith({ south: 47, west: 1, north: 49, east: 3 })
|
||||
|
||||
const moveend = handlerFor('moveend')
|
||||
const zoomend = handlerFor('zoomend')
|
||||
expect(moveend).toBeTypeOf('function')
|
||||
moveend!()
|
||||
zoomend!()
|
||||
expect(onViewportChange).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-044: no viewport callback means no listeners at all', () => {
|
||||
render(<MapView />)
|
||||
expect(mapMock.on.mock.calls.some(c => c[0] === 'moveend')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-045: unmounting detaches the viewport listeners', () => {
|
||||
const { unmount } = render(<MapView onViewportChange={vi.fn()} />)
|
||||
unmount()
|
||||
expect(mapMock.off).toHaveBeenCalledWith('moveend', expect.any(Function))
|
||||
expect(mapMock.off).toHaveBeenCalledWith('zoomend', expect.any(Function))
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-046: a map-click handler is attached and detached again', () => {
|
||||
const onMapClick = vi.fn()
|
||||
const { unmount } = render(<MapView onMapClick={onMapClick} />)
|
||||
expect(mapMock.on).toHaveBeenCalledWith('click', onMapClick)
|
||||
unmount()
|
||||
expect(mapMock.off).toHaveBeenCalledWith('click', onMapClick)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-047: without a click handler nothing is bound', () => {
|
||||
render(<MapView onMapClick={null} />)
|
||||
expect(mapMock.on.mock.calls.some(c => c[0] === 'click')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-048: a context-menu handler is attached and detached again', () => {
|
||||
const onMapContextMenu = vi.fn()
|
||||
const { unmount } = render(<MapView onMapContextMenu={onMapContextMenu} />)
|
||||
expect(mapMock.on).toHaveBeenCalledWith('contextmenu', onMapContextMenu)
|
||||
unmount()
|
||||
expect(mapMock.off).toHaveBeenCalledWith('contextmenu', onMapContextMenu)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-049: changing the center prop moves the camera there', () => {
|
||||
const places = [buildMapPlace({ id: 1, lat: 48, lng: 2 })]
|
||||
const { rerender } = render(<MapView places={places} center={[48, 2]} zoom={9} />)
|
||||
mapMock.setView.mockClear()
|
||||
|
||||
rerender(<MapView places={places} center={[35.01, 135.76]} zoom={11} />)
|
||||
expect(mapMock.setView).toHaveBeenCalledWith([35.01, 135.76], 11)
|
||||
|
||||
// The same center again must not re-issue the camera move.
|
||||
mapMock.setView.mockClear()
|
||||
rerender(<MapView places={places} center={[35.01, 135.76]} zoom={11} />)
|
||||
expect(mapMock.setView).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView track casing pane (#776)', () => {
|
||||
it('FE-COMP-MAPVIEW-050: creates the casing pane under the overlay pane and draws casings into it', () => {
|
||||
render(<MapView places={[buildMapPlace({
|
||||
id: 1, lat: 48, lng: 2, route_geometry: '[[48.0,2.0],[49.0,3.0]]', route_color: '#059669',
|
||||
})]} />)
|
||||
|
||||
expect(mapMock.createPane).toHaveBeenCalledWith('trek-track-casing')
|
||||
expect(mapMock.panes.get('trek-track-casing')!.style.zIndex).toBe('398')
|
||||
|
||||
const casing = screen.getAllByTestId('polyline')
|
||||
.find(el => JSON.parse(el.getAttribute('data-path-options') || '{}').weight === 6.5)
|
||||
expect(casing!.getAttribute('data-pane')).toBe('trek-track-casing')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-072: a renderer without pane support still draws every track', () => {
|
||||
const paneless = mapMock as unknown as Record<string, unknown>
|
||||
const { getPane, createPane } = paneless
|
||||
delete paneless.getPane
|
||||
delete paneless.createPane
|
||||
try {
|
||||
render(<MapView places={[buildMapPlace({
|
||||
id: 1, lat: 48, lng: 2, route_geometry: '[[48.0,2.0],[49.0,3.0]]',
|
||||
})]} />)
|
||||
// Casing, line and hit area are all mounted — just in insertion order.
|
||||
expect(screen.getAllByTestId('polyline')).toHaveLength(3)
|
||||
const casing = screen.getAllByTestId('polyline')
|
||||
.find(el => JSON.parse(el.getAttribute('data-path-options') || '{}').weight === 6.5)
|
||||
expect(casing!.getAttribute('data-pane')).toBe('')
|
||||
} finally {
|
||||
paneless.getPane = getPane
|
||||
paneless.createPane = createPane
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView selection panning (#921)', () => {
|
||||
it('FE-COMP-MAPVIEW-051: pans to the padding-corrected point when the map can project', () => {
|
||||
const projectable = mapMock as unknown as Record<string, unknown>
|
||||
const add = vi.fn(() => ({ x: 5, y: 6 }))
|
||||
projectable.project = vi.fn(() => ({ add }))
|
||||
projectable.unproject = vi.fn(() => [49, 4])
|
||||
try {
|
||||
const places = [buildMapPlace({ id: 8, lat: 48, lng: 2 })]
|
||||
const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)
|
||||
rerender(<MapView places={places} selectedPlaceId={8} />)
|
||||
|
||||
expect(projectable.project).toHaveBeenCalledWith([48, 2])
|
||||
// The offset is half the difference between the two padding corners.
|
||||
expect(add).toHaveBeenCalledWith([0, 0])
|
||||
expect(mapMock.panTo).toHaveBeenCalledWith([49, 4], { animate: true })
|
||||
} finally {
|
||||
delete projectable.project
|
||||
delete projectable.unproject
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-052: falls back to a plain pan when the map cannot project', () => {
|
||||
const places = [buildMapPlace({ id: 9, lat: 48, lng: 2 })]
|
||||
const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)
|
||||
rerender(<MapView places={places} selectedPlaceId={9} />)
|
||||
expect(mapMock.panTo).toHaveBeenCalledWith([48, 2], { animate: true })
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-053: a selected place without coordinates is not panned to', () => {
|
||||
const places = [buildMapPlace({ id: 10, lat: null, lng: null })]
|
||||
const { rerender } = render(<MapView places={places} selectedPlaceId={null} />)
|
||||
rerender(<MapView places={places} selectedPlaceId={10} />)
|
||||
expect(mapMock.panTo).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView hover card', () => {
|
||||
const place = () => buildMapPlace({ id: 12, name: 'Eiffel Tower', lat: 48.85, lng: 2.29 })
|
||||
|
||||
it('FE-COMP-MAPVIEW-054: mousemove keeps the card following the cursor', () => {
|
||||
render(<MapView places={[place()]} />)
|
||||
fireEvent.click(screen.getByTestId('marker-move-trigger'))
|
||||
const card = screen.getByTestId('tooltip')
|
||||
expect(card.textContent).toContain('Eiffel Tower')
|
||||
expect(card.style.left).toBe('164px') // 150 + 14
|
||||
expect(card.style.top).toBe('150px') // 160 - 10
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-055: mouseout clears the card', () => {
|
||||
render(<MapView places={[place()]} />)
|
||||
fireEvent.click(screen.getByTestId('marker-hover-trigger'))
|
||||
expect(screen.getByTestId('tooltip')).toBeTruthy()
|
||||
|
||||
fireEvent.click(screen.getByTestId('marker-out-trigger'))
|
||||
expect(screen.queryByTestId('tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-056: scrolling the page drops the card so it cannot get orphaned', () => {
|
||||
render(<MapView places={[place()]} />)
|
||||
fireEvent.click(screen.getByTestId('marker-hover-trigger'))
|
||||
expect(screen.getByTestId('tooltip')).toBeTruthy()
|
||||
|
||||
fireEvent.scroll(window)
|
||||
expect(screen.queryByTestId('tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-057: hoverDisabled suppresses the card entirely', () => {
|
||||
render(<MapView places={[place()]} hoverDisabled />)
|
||||
fireEvent.click(screen.getByTestId('marker-hover-trigger'))
|
||||
fireEvent.click(screen.getByTestId('marker-move-trigger'))
|
||||
expect(screen.queryByTestId('tooltip')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView live location', () => {
|
||||
const fix = (over: Record<string, any> = {}) => ({ lat: 48.2, lng: 16.37, accuracy: 25, heading: null, ...over })
|
||||
|
||||
it('FE-COMP-MAPVIEW-058: no fix means no dot, circle or heading cone', () => {
|
||||
render(<MapView />)
|
||||
expect(screen.queryByTestId('circle-marker')).toBeNull()
|
||||
expect(screen.queryByTestId('circle')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-059: a fix draws the blue dot and its accuracy circle', () => {
|
||||
geoMock.position = fix()
|
||||
geoMock.mode = 'show'
|
||||
render(<MapView />)
|
||||
expect(screen.getByTestId('circle-marker')).toBeTruthy()
|
||||
expect(screen.getByTestId('circle')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-060: a city-level fix draws the dot but no accuracy circle', () => {
|
||||
geoMock.position = fix({ accuracy: 900 })
|
||||
geoMock.mode = 'show'
|
||||
render(<MapView />)
|
||||
expect(screen.getByTestId('circle-marker')).toBeTruthy()
|
||||
expect(screen.queryByTestId('circle')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-061: a compass heading adds a rotated cone marker', () => {
|
||||
geoMock.position = fix({ heading: 135 })
|
||||
geoMock.mode = 'show'
|
||||
render(<MapView />)
|
||||
const cone = screen.getAllByTestId('marker').find(m => iconHtmlOf(m).includes('rotate(135deg)'))
|
||||
expect(cone).toBeTruthy()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-062: show mode recentres once and then leaves the camera alone', () => {
|
||||
geoMock.position = fix()
|
||||
geoMock.mode = 'show'
|
||||
const { rerender } = render(<MapView />)
|
||||
expect(mapMock.setView).toHaveBeenCalledWith([48.2, 16.37], 15)
|
||||
|
||||
mapMock.setView.mockClear()
|
||||
geoMock.position = fix({ lat: 48.25 })
|
||||
// A prop change forces the re-render the new fix would otherwise not cause.
|
||||
rerender(<MapView hoverDisabled />)
|
||||
expect(mapMock.setView).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-063: follow mode recentres on every fix at navigation zoom', () => {
|
||||
geoMock.position = fix()
|
||||
geoMock.mode = 'follow'
|
||||
render(<MapView />)
|
||||
expect(mapMock.setView).toHaveBeenCalledWith([48.2, 16.37], 16, { animate: true, duration: 0.35 })
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-064: a mobile viewport gets the location button, desktop does not', () => {
|
||||
render(<MapView />)
|
||||
expect(screen.queryByRole('button', { name: 'Show my location' })).toBeNull()
|
||||
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
|
||||
geoMock.mode = 'show'
|
||||
render(<MapView />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Follow my location' }))
|
||||
expect(geoMock.cycleMode).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView bounds fitting', () => {
|
||||
it('FE-COMP-MAPVIEW-065: a day-detail fit nudges the map down once the animation ran (#1348)', async () => {
|
||||
const places = [
|
||||
buildMapPlace({ id: 1, lat: 48, lng: 2 }),
|
||||
buildMapPlace({ id: 2, lat: 48.2, lng: 2.2 }),
|
||||
]
|
||||
const { rerender } = render(<MapView places={places} dayPlaces={places} fitKey={1} hasDayDetail />)
|
||||
rerender(<MapView places={places} dayPlaces={places} fitKey={2} hasDayDetail />)
|
||||
|
||||
expect(mapMock.fitBounds).toHaveBeenCalled()
|
||||
await waitFor(() => expect(mapMock.panBy).toHaveBeenCalledWith([0, 150], { animate: true }), { timeout: 2000 })
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-066: a fitKey that never changed is not re-fitted', async () => {
|
||||
const L = await leafletMock()
|
||||
L.latLngBounds.mockClear()
|
||||
render(<MapView places={[buildMapPlace({ id: 1, lat: 48, lng: 2 })]} fitKey={-1} />)
|
||||
expect(L.latLngBounds).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-067: an invalid bounds object is ignored instead of throwing', async () => {
|
||||
const L = await leafletMock()
|
||||
L.latLngBounds.mockImplementationOnce(() => ({ isValid: () => false }))
|
||||
const places = [buildMapPlace({ id: 1, lat: 48, lng: 2 })]
|
||||
const { rerender } = render(<MapView places={places} fitKey={1} />)
|
||||
mapMock.fitBounds.mockClear()
|
||||
rerender(<MapView places={places} fitKey={2} />)
|
||||
expect(mapMock.fitBounds).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('MapView photo thumbnails', () => {
|
||||
const THUMB = 'data:image/jpeg;base64,THUMBDATA'
|
||||
|
||||
it('FE-COMP-MAPVIEW-068: a photo that arrives after mount is folded into the marker icon', async () => {
|
||||
render(<MapView places={[buildMapPlace({ id: 21, lat: 48, lng: 2, google_place_id: 'gp-21' })]} />)
|
||||
const deliver = thumbCallbacks.get('gp-21')
|
||||
expect(deliver).toBeTypeOf('function')
|
||||
|
||||
// Two deliveries in one frame collapse into a single re-render.
|
||||
act(() => { deliver!(THUMB); deliver!(THUMB) })
|
||||
await waitFor(() => expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toContain(THUMB))
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-069: re-delivering the same thumb does not change the icon', async () => {
|
||||
render(<MapView places={[buildMapPlace({ id: 22, lat: 48, lng: 2, google_place_id: 'gp-22' })]} />)
|
||||
const deliver = thumbCallbacks.get('gp-22')!
|
||||
act(() => { deliver(THUMB) })
|
||||
await waitFor(() => expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toContain(THUMB))
|
||||
|
||||
const before = iconHtmlOf(screen.getAllByTestId('marker')[0])
|
||||
act(() => { deliver(THUMB) })
|
||||
await waitFor(() => expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toBe(before))
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-075: an unchanged batch keeps the previous photo state object', () => {
|
||||
// Same case as above, but with the batching frame under the test's control so
|
||||
// the "nothing changed" path in the state updater really runs before teardown.
|
||||
const frames: FrameRequestCallback[] = []
|
||||
const flush = () => { frames.splice(0).forEach(cb => cb(0)) }
|
||||
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => frames.push(cb))
|
||||
vi.stubGlobal('cancelAnimationFrame', () => { frames.length = 0 })
|
||||
try {
|
||||
render(<MapView places={[buildMapPlace({ id: 24, lat: 48, lng: 2, google_place_id: 'gp-24' })]} />)
|
||||
const deliver = thumbCallbacks.get('gp-24')!
|
||||
|
||||
act(() => { deliver(THUMB) })
|
||||
act(flush)
|
||||
const withThumb = iconHtmlOf(screen.getAllByTestId('marker')[0])
|
||||
expect(withThumb).toContain(THUMB)
|
||||
|
||||
act(() => { deliver(THUMB) })
|
||||
act(flush)
|
||||
expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toBe(withThumb)
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-070: a place with a custom uploaded image is never auto-fetched', () => {
|
||||
render(<MapView places={[buildMapPlace({ id: 23, lat: 48, lng: 2, image_url: '/uploads/places/mine.jpg' })]} />)
|
||||
expect(thumbCallbacks.size).toBe(0)
|
||||
expect(vi.mocked(photoService.fetchPhoto)).not.toHaveBeenCalled()
|
||||
expect(iconHtmlOf(screen.getAllByTestId('marker')[0])).toContain('/uploads/places/mine.jpg')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPVIEW-071: photos are not fetched at all when the feature is off', () => {
|
||||
useAuthStore.setState({ placesPhotosEnabled: false })
|
||||
render(<MapView places={[buildMapPlace({ id: 24, lat: 48, lng: 2, google_place_id: 'gp-24' })]} />)
|
||||
expect(thumbCallbacks.size).toBe(0)
|
||||
expect(vi.mocked(photoService.fetchPhoto)).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,558 @@
|
||||
// FE-COMP-RESOVERLAY-001 to FE-COMP-RESOVERLAY-024
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import { act, fireEvent } from '@testing-library/react'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import type { Reservation, ReservationEndpoint } from '../../types'
|
||||
|
||||
// The Leaflet map jsdom cannot provide: panes are a plain map, and the
|
||||
// projection is a linear lat/lng → pixel scale so the tests can put endpoints a
|
||||
// chosen number of pixels apart and drive the declutter thresholds exactly.
|
||||
const leaflet = vi.hoisted(() => {
|
||||
const panes = new Map<string, HTMLElement>()
|
||||
const view = { zoom: 10, scale: 1000 }
|
||||
const point = (x: number, y: number) => ({
|
||||
x, y,
|
||||
distanceTo(other: { x: number; y: number }) { return Math.hypot(x - other.x, y - other.y) },
|
||||
})
|
||||
const events: Record<string, () => void> = {}
|
||||
const map = {
|
||||
getZoom: () => view.zoom,
|
||||
getPane: (name: string) => panes.get(name),
|
||||
createPane: (name: string) => {
|
||||
const el = document.createElement('div')
|
||||
panes.set(name, el)
|
||||
return el
|
||||
},
|
||||
latLngToContainerPoint: ([lat, lng]: [number, number]) => point(lng * view.scale, lat * view.scale),
|
||||
}
|
||||
return { panes, view, events, map }
|
||||
})
|
||||
|
||||
vi.mock('react-leaflet', () => ({
|
||||
Marker: ({ children, position, icon, eventHandlers, pane, zIndexOffset }: any) => (
|
||||
<div
|
||||
data-testid="endpoint-marker"
|
||||
data-lat={position[0]}
|
||||
data-lng={position[1]}
|
||||
data-pane={pane ?? ''}
|
||||
data-zindex={zIndexOffset}
|
||||
data-icon-html={icon?.options?.html ?? ''}
|
||||
onClick={() => eventHandlers?.click?.()}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
Polyline: ({ positions, pathOptions }: any) => (
|
||||
<div
|
||||
data-testid="polyline"
|
||||
data-points={JSON.stringify(positions)}
|
||||
data-path-options={JSON.stringify(pathOptions ?? null)}
|
||||
/>
|
||||
),
|
||||
Tooltip: ({ children }: any) => <div data-testid="marker-tooltip">{children}</div>,
|
||||
useMap: () => leaflet.map,
|
||||
useMapEvents: (handlers: Record<string, () => void>) => {
|
||||
Object.assign(leaflet.events, handlers)
|
||||
return leaflet.map
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('leaflet', () => {
|
||||
const divIcon = vi.fn((options: Record<string, unknown>) => ({ options }))
|
||||
const marker = vi.fn(() => ({
|
||||
addTo: vi.fn(), remove: vi.fn(), setLatLng: vi.fn(), getElement: () => null,
|
||||
}))
|
||||
const point = vi.fn((x: number, y: number) => ({ x, y }))
|
||||
return { default: { divIcon, marker, point }, divIcon, marker, point }
|
||||
})
|
||||
|
||||
import ReservationOverlay from './ReservationOverlay'
|
||||
|
||||
function endpoint(over: Partial<ReservationEndpoint> = {}): ReservationEndpoint {
|
||||
return {
|
||||
role: 'from', sequence: 0, name: 'A', code: null,
|
||||
lat: 48, lng: 16, timezone: null, local_time: null, local_date: null,
|
||||
...over,
|
||||
} as unknown as ReservationEndpoint
|
||||
}
|
||||
|
||||
// Endpoints 3500 px apart at the default scale — past every type's declutter and
|
||||
// label threshold, so a booking is fully drawn unless a test says otherwise.
|
||||
function booking(over: Partial<Reservation> = {}): Reservation {
|
||||
return {
|
||||
id: 1, type: 'flight', status: 'confirmed', title: null,
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
...over,
|
||||
} as unknown as Reservation
|
||||
}
|
||||
|
||||
const GEOMETRY = '__upzA_gayB_af@_pR_ry@~oR'
|
||||
|
||||
function transitBooking(legs: Record<string, unknown>[]): Reservation {
|
||||
return booking({
|
||||
id: 2,
|
||||
type: 'transit',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Stop A', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'Stop B', lat: 48.02, lng: 16 }),
|
||||
],
|
||||
metadata: { transit: { legs } },
|
||||
} as unknown as Partial<Reservation>)
|
||||
}
|
||||
|
||||
function renderOverlay(props: Partial<React.ComponentProps<typeof ReservationOverlay>> = {}) {
|
||||
return render(
|
||||
<ReservationOverlay
|
||||
reservations={[booking()]}
|
||||
showConnections
|
||||
showStats={false}
|
||||
{...props}
|
||||
/>,
|
||||
)
|
||||
}
|
||||
|
||||
const markers = () => screen.queryAllByTestId('endpoint-marker')
|
||||
const lines = () => screen.queryAllByTestId('polyline')
|
||||
const styleOf = (el: HTMLElement) => JSON.parse(el.getAttribute('data-path-options') || 'null')
|
||||
const labelOf = (el: HTMLElement) => {
|
||||
const html = el.getAttribute('data-icon-html') || ''
|
||||
return html.replace(/<[^>]*>/g, '').trim()
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
leaflet.panes.clear()
|
||||
leaflet.view.scale = 1000
|
||||
resetAllStores()
|
||||
})
|
||||
|
||||
describe('ReservationOverlay', () => {
|
||||
it('FE-COMP-RESOVERLAY-001: creates the endpoint pane above the overlay pane', () => {
|
||||
renderOverlay()
|
||||
const pane = leaflet.panes.get('reservation-endpoints')
|
||||
expect(pane).toBeDefined()
|
||||
expect(pane!.style.zIndex).toBe('650')
|
||||
expect(pane!.style.pointerEvents).toBe('auto')
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-002: renders nothing at all while connections are hidden', () => {
|
||||
renderOverlay({ showConnections: false })
|
||||
expect(lines()).toHaveLength(0)
|
||||
expect(markers()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-003: draws a marker per waypoint in the endpoint pane', () => {
|
||||
renderOverlay()
|
||||
expect(markers()).toHaveLength(2)
|
||||
expect(markers()[0].getAttribute('data-pane')).toBe('reservation-endpoints')
|
||||
expect(markers()[0].getAttribute('data-zindex')).toBe('1000')
|
||||
expect(markers().map(m => m.getAttribute('data-lat'))).toEqual(['48', '51.5'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-004: a flight is drawn as a geodesic arc, not a two-point line', () => {
|
||||
renderOverlay()
|
||||
const points = JSON.parse(lines()[0].getAttribute('data-points') || '[]')
|
||||
expect(points.length).toBeGreaterThan(2)
|
||||
expect(points[0]).toEqual([48, 16])
|
||||
expect(points[points.length - 1]).toEqual([51.5, 16])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-005: a train is drawn as the plain two-point line', () => {
|
||||
renderOverlay({ reservations: [booking({ type: 'train' })] })
|
||||
expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [51.5, 16]])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-006: a pending booking is dashed and dimmer than a confirmed one', () => {
|
||||
const { unmount } = renderOverlay({ reservations: [booking({ status: 'pending' })] })
|
||||
expect(styleOf(lines()[0])).toMatchObject({ opacity: 0.55, dashArray: '6, 6' })
|
||||
unmount()
|
||||
|
||||
renderOverlay({ reservations: [booking({ id: 9 })] })
|
||||
const confirmed = styleOf(lines()[0])
|
||||
expect(confirmed.opacity).toBe(0.75)
|
||||
expect(confirmed.dashArray).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-007: skips reservations that are not a transport type', () => {
|
||||
renderOverlay({ reservations: [booking({ type: 'hotel' as Reservation['type'] })] })
|
||||
expect(lines()).toHaveLength(0)
|
||||
expect(markers()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-008: skips a booking with fewer than two waypoints', () => {
|
||||
renderOverlay({ reservations: [booking({ endpoints: [endpoint({ role: 'from', sequence: 0 })] })] })
|
||||
expect(lines()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-009: orders waypoints by sequence and draws one leg per pair', () => {
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'to', sequence: 2, name: 'C', lat: 51.5, lng: 16 }),
|
||||
endpoint({ role: 'from', sequence: 0, name: 'A', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: 1, name: 'B', lat: 50, lng: 16 }),
|
||||
],
|
||||
})],
|
||||
})
|
||||
expect(lines()).toHaveLength(2)
|
||||
expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [50, 16]])
|
||||
expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]')).toEqual([[50, 16], [51.5, 16]])
|
||||
expect(markers()).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-010: hides a hop whose endpoints sit almost on top of each other', () => {
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, lat: 48.05, lng: 16 }), // 50 px, under the 200 px floor
|
||||
],
|
||||
})],
|
||||
})
|
||||
expect(lines()).toHaveLength(0)
|
||||
expect(markers()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-011: the same hop reappears once the map is zoomed in', () => {
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, lat: 48.05, lng: 16 }),
|
||||
],
|
||||
})],
|
||||
})
|
||||
expect(lines()).toHaveLength(0)
|
||||
|
||||
leaflet.view.scale = 20000 // 1000 px apart now
|
||||
leaflet.view.zoom = 14
|
||||
act(() => { leaflet.events.zoomend() })
|
||||
expect(lines()).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-012: each transport type gets its own declutter floor', () => {
|
||||
// 100 px apart: a flight survives (50 px floor), a cruise does not (150 px).
|
||||
const short = (type: string, id: number) => booking({
|
||||
id, type: type as Reservation['type'],
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, lat: 48.1, lng: 16 }),
|
||||
],
|
||||
})
|
||||
const { unmount } = renderOverlay({ reservations: [short('flight', 1)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
unmount()
|
||||
|
||||
renderOverlay({ reservations: [short('cruise', 2)] })
|
||||
expect(lines()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-013: clicking an endpoint reports its reservation id', () => {
|
||||
const onEndpointClick = vi.fn()
|
||||
renderOverlay({ reservations: [booking({ id: 42 })], onEndpointClick })
|
||||
fireEvent.click(markers()[1])
|
||||
expect(onEndpointClick).toHaveBeenCalledWith(42)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-014: an endpoint without a click handler stays inert', () => {
|
||||
renderOverlay({ onEndpointClick: undefined })
|
||||
expect(() => fireEvent.click(markers()[0])).not.toThrow()
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-015: the tooltip shows the stop name and the booking title', () => {
|
||||
renderOverlay({ reservations: [booking({ title: 'OS 456' })] })
|
||||
const tooltips = screen.getAllByTestId('marker-tooltip')
|
||||
expect(tooltips[0].textContent).toContain('Vienna')
|
||||
expect(tooltips[0].textContent).toContain('OS 456')
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-016: endpoint badges carry no label until the setting is on', () => {
|
||||
renderOverlay()
|
||||
expect(labelOf(markers()[0])).toBe('')
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-017: with the setting on the badge shows the endpoint code', () => {
|
||||
seedStore(useSettingsStore, { settings: { map_booking_labels: true } })
|
||||
renderOverlay()
|
||||
expect(markers().map(labelOf)).toEqual(['VIE', 'LHR'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-018: a code-less stop falls back to its name without the parenthetical', () => {
|
||||
seedStore(useSettingsStore, { settings: { map_booking_labels: true } })
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Wien Hbf (Bahnsteig 3)', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'München Hbf', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
})],
|
||||
})
|
||||
expect(markers().map(labelOf)).toEqual(['Wien Hbf', 'München Hbf'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-019: a short train hop draws its line but keeps its labels off', () => {
|
||||
seedStore(useSettingsStore, { settings: { map_booking_labels: true } })
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'Graz', code: 'GRZ', lat: 48.3, lng: 16 }),
|
||||
],
|
||||
})],
|
||||
})
|
||||
// 300 px: over the 200 px line floor, under the 400 px label floor.
|
||||
expect(lines()).toHaveLength(1)
|
||||
expect(markers().map(labelOf)).toEqual(['', ''])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationOverlay declutter floors and road routes', () => {
|
||||
// Same endpoints every time, only the north-south gap changes: at the mocked
|
||||
// scale one degree of latitude is 1000 px, so `dLat` *is* the pixel distance / 1000.
|
||||
const hop = (type: string, id: number, dLat: number) => booking({
|
||||
id, type: type as Reservation['type'],
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Start', code: 'AAA', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'End', code: 'BBB', lat: 48 + dLat, lng: 16 }),
|
||||
],
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-030: a renderer without pane support still draws the overlay', () => {
|
||||
const realGetPane = leaflet.map.getPane
|
||||
leaflet.map.getPane = undefined
|
||||
try {
|
||||
renderOverlay()
|
||||
expect(leaflet.panes.size).toBe(0)
|
||||
expect(markers()).toHaveLength(2)
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
} finally {
|
||||
leaflet.map.getPane = realGetPane
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-031: a car hop has its own 80 px line floor', () => {
|
||||
const { unmount } = renderOverlay({ reservations: [hop('car', 1, 0.1)] })
|
||||
expect(lines()).toHaveLength(1)
|
||||
unmount()
|
||||
|
||||
renderOverlay({ reservations: [hop('car', 2, 0.05)] })
|
||||
expect(lines()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-032: a car keeps its endpoint labels off below 150 px', () => {
|
||||
seedStore(useSettingsStore, { settings: { map_booking_labels: true } })
|
||||
const { unmount } = renderOverlay({ reservations: [hop('car', 1, 0.1)] })
|
||||
expect(markers().map(labelOf)).toEqual(['', ''])
|
||||
unmount()
|
||||
|
||||
renderOverlay({ reservations: [hop('car', 2, 0.2)] })
|
||||
expect(markers().map(labelOf)).toEqual(['AAA', 'BBB'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-033: a cruise draws from 150 px but only labels from 300 px', () => {
|
||||
seedStore(useSettingsStore, { settings: { map_booking_labels: true } })
|
||||
const { unmount } = renderOverlay({ reservations: [hop('cruise', 1, 0.2)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
expect(markers().map(labelOf)).toEqual(['', ''])
|
||||
unmount()
|
||||
|
||||
renderOverlay({ reservations: [hop('cruise', 2, 0.4)] })
|
||||
expect(markers().map(labelOf)).toEqual(['AAA', 'BBB'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-034: a supplied road route replaces the straight arc', () => {
|
||||
const road: [number, number][] = [[48, 16], [49, 16.4], [51.5, 16]]
|
||||
renderOverlay({
|
||||
reservations: [hop('car', 7, 3.5)],
|
||||
roadRoutes: new Map([[7, road]]),
|
||||
})
|
||||
expect(lines()).toHaveLength(1)
|
||||
expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual(road)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-035: a one-point road route falls back to the straight arc', () => {
|
||||
renderOverlay({
|
||||
reservations: [hop('car', 7, 3.5)],
|
||||
roadRoutes: new Map([[7, [[48, 16]] as [number, number][]]]),
|
||||
})
|
||||
expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [51.5, 16]])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-036: a booking without an endpoints array is skipped', () => {
|
||||
renderOverlay({ reservations: [booking({ endpoints: undefined })] })
|
||||
expect(lines()).toHaveLength(0)
|
||||
expect(markers()).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-037: waypoints without a sequence keep their array order', () => {
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: undefined, name: 'A', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: undefined, name: 'B', lat: 50, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: undefined, name: 'C', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
})],
|
||||
})
|
||||
expect(lines()).toHaveLength(2)
|
||||
expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toEqual([[48, 16], [50, 16]])
|
||||
expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]')).toEqual([[50, 16], [51.5, 16]])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-038: a leg whose stops share coordinates degrades to a straight segment', () => {
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: 1, name: 'Vienna Gate', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
})],
|
||||
})
|
||||
expect(lines()).toHaveLength(2)
|
||||
expect(JSON.parse(lines()[0].getAttribute('data-points') || '[]')).toHaveLength(2)
|
||||
expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]').length).toBeGreaterThan(2)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-039: a code-less stop between two coded ends falls back to its name', () => {
|
||||
seedStore(useSettingsStore, { settings: { map_booking_labels: true } })
|
||||
renderOverlay({
|
||||
reservations: [booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: 1, name: 'Zuerich HB (Gleis 5)', code: null, lat: 50, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
})],
|
||||
})
|
||||
expect(markers().map(labelOf)).toEqual(['VIE', 'Zuerich HB', 'LHR'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationOverlay transit journeys (#1570)', () => {
|
||||
it('FE-COMP-RESOVERLAY-020: draws the stored rail alignment with a white casing under it', () => {
|
||||
renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'BUS', line_color: '#7c3aed' }])] })
|
||||
expect(lines()).toHaveLength(2)
|
||||
expect(styleOf(lines()[0])).toMatchObject({ color: '#ffffff', weight: 6 })
|
||||
expect(styleOf(lines()[1])).toMatchObject({ color: '#7c3aed', weight: 3.5 })
|
||||
expect(JSON.parse(lines()[1].getAttribute('data-points') || '[]')).toEqual([[48, 2], [48.02, 2.01], [48.05, 2]])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-021: a walking leg is dotted and gets no casing', () => {
|
||||
renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'WALK' }])] })
|
||||
expect(lines()).toHaveLength(1)
|
||||
expect(styleOf(lines()[0])).toMatchObject({ color: '#64748b', dashArray: '1, 7' })
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-022: a leg without a line colour falls back to the transit blue', () => {
|
||||
renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'BUS' }])] })
|
||||
expect(styleOf(lines()[1])).toMatchObject({ color: '#3b82f6' })
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-023: real geometry survives the endpoint declutter even zoomed right out', () => {
|
||||
// The two stations project ~20 px apart — far under the 200 px floor.
|
||||
renderOverlay({ reservations: [transitBooking([{ geometry: GEOMETRY, mode: 'BUS' }])] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
expect(markers()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-024: a transit journey without stored geometry is decluttered like any hop', () => {
|
||||
renderOverlay({ reservations: [transitBooking([{ mode: 'BUS' }])] })
|
||||
expect(lines()).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
// computeDuration only feeds the stats badge, which this overlay no longer
|
||||
// renders — but it still runs on every update, and a non-finite date once threw
|
||||
// inside Intl.formatToParts and blanked the whole trip (#1620).
|
||||
describe('ReservationOverlay duration math', () => {
|
||||
const timed = (from: Partial<ReservationEndpoint>, to: Partial<ReservationEndpoint>, res: Partial<Reservation> = {}) =>
|
||||
booking({
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16, ...from }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: 16, ...to }),
|
||||
],
|
||||
...res,
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-025: renders a well-formed cross-timezone flight', () => {
|
||||
renderOverlay({ reservations: [timed(
|
||||
{ timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '09:20' },
|
||||
{ timezone: 'Europe/London', local_date: '2024-01-15', local_time: '11:05' },
|
||||
)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-026: renders a flight whose local arrival reads before its departure', () => {
|
||||
renderOverlay({ reservations: [timed(
|
||||
{ timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '22:30' },
|
||||
{ timezone: 'America/New_York', local_date: '2024-01-15', local_time: '02:10' },
|
||||
)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-027: renders a flight whose imported time is missing its minutes', () => {
|
||||
expect(() => renderOverlay({ reservations: [timed(
|
||||
{ timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '22' },
|
||||
{ timezone: 'Europe/London', local_date: '2024-01-16', local_time: '08' },
|
||||
)] })).not.toThrow()
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-028: a time-only endpoint borrows the date from the other side', () => {
|
||||
renderOverlay({ reservations: [timed(
|
||||
{ local_date: '2024-01-15', local_time: '09:20' }, {},
|
||||
{ reservation_end_time: '17:30' } as Partial<Reservation>,
|
||||
)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-029: two date-less times and an implausible gap both render', () => {
|
||||
const { unmount } = renderOverlay({ reservations: [timed({}, {}, {
|
||||
reservation_time: '09:20', reservation_end_time: '17:30',
|
||||
} as Partial<Reservation>)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
unmount()
|
||||
|
||||
renderOverlay({ reservations: [timed({}, {}, {
|
||||
id: 5, reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-19T17:30',
|
||||
} as Partial<Reservation>)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-040: a date-less departure borrows the date from the arrival', () => {
|
||||
renderOverlay({ reservations: [timed(
|
||||
{}, { local_date: '2024-01-16', local_time: '08:00' },
|
||||
{ reservation_time: '22:30' } as Partial<Reservation>,
|
||||
)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-041: a hop shorter than an hour renders', () => {
|
||||
renderOverlay({ reservations: [timed({}, {}, {
|
||||
reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-15T09:50',
|
||||
} as Partial<Reservation>)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESOVERLAY-042: a stored timestamp that carries no clock time renders', () => {
|
||||
renderOverlay({ reservations: [timed(
|
||||
{ timezone: 'Europe/Vienna' }, { timezone: 'Europe/London' },
|
||||
{ reservation_time: '2024-01-15T', reservation_end_time: '2024-01-15T18:00' } as Partial<Reservation>,
|
||||
)] })
|
||||
expect(lines().length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,25 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { http, HttpResponse } from 'msw'
|
||||
import { server } from '../../../tests/helpers/msw/server'
|
||||
import { pluginsApi, type PluginRouteResult } from '../../api/client'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import {
|
||||
calculateRoute,
|
||||
calculateRouteWithLegs,
|
||||
calculateSegments,
|
||||
optimizeRoute,
|
||||
generateGoogleMapsUrl,
|
||||
parsePluginProfile,
|
||||
withHotelBookends,
|
||||
} from './RouteCalculator'
|
||||
|
||||
const OSRM_BASE = 'https://router.project-osrm.org/route/v1'
|
||||
// calculateRouteWithLegs talks to the FOSSGIS per-profile hosts, not the car-only demo.
|
||||
const FOSSGIS = {
|
||||
driving: 'https://routing.openstreetmap.de/routed-car/route/v1/driving',
|
||||
walking: 'https://routing.openstreetmap.de/routed-foot/route/v1/foot',
|
||||
cycling: 'https://routing.openstreetmap.de/routed-bike/route/v1/bike',
|
||||
}
|
||||
|
||||
const buildOsrmRouteResponse = (distance = 5000, duration = 360) => ({
|
||||
code: 'Ok',
|
||||
@@ -285,3 +295,280 @@ describe('withHotelBookends', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
// ── parsePluginProfile ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('parsePluginProfile', () => {
|
||||
it('FE-COMP-ROUTECALCULATOR-026: splits plugin:<id>/<profile> into its two halves', () => {
|
||||
expect(parsePluginProfile('plugin:ev-router/fastest')).toEqual({ pluginId: 'ev-router', profileId: 'fastest' })
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-027: a profile id may itself contain slashes', () => {
|
||||
expect(parsePluginProfile('plugin:ev-router/eco/winter')).toEqual({ pluginId: 'ev-router', profileId: 'eco/winter' })
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-028: a built-in profile is not a plugin profile', () => {
|
||||
expect(parsePluginProfile('driving')).toBeNull()
|
||||
expect(parsePluginProfile('walking')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-029: rejects a malformed plugin key', () => {
|
||||
expect(parsePluginProfile('plugin:ev-router')).toBeNull() // no separator
|
||||
expect(parsePluginProfile('plugin:/fastest')).toBeNull() // empty plugin id
|
||||
expect(parsePluginProfile('plugin:ev-router/')).toBeNull() // empty profile id
|
||||
})
|
||||
})
|
||||
|
||||
// ── calculateRoute: remaining profiles ─────────────────────────────────────────
|
||||
|
||||
describe('calculateRoute profiles', () => {
|
||||
it('FE-COMP-ROUTECALCULATOR-030: cycling overrides the OSRM duration with a 15 km/h estimate', async () => {
|
||||
server.use(
|
||||
http.get(`${OSRM_BASE}/cycling/:coords`, () =>
|
||||
HttpResponse.json(buildOsrmRouteResponse(9000, 4242))
|
||||
)
|
||||
)
|
||||
const result = await calculateRoute([wp1, wp2], 'cycling')
|
||||
expect(result.duration).toBeCloseTo(9000 / (15000 / 3600))
|
||||
// The raw OSRM duration is still reported as the driving estimate.
|
||||
expect(result.drivingText).toBe('1 h 10 min')
|
||||
})
|
||||
})
|
||||
|
||||
// ── calculateSegments error paths ──────────────────────────────────────────────
|
||||
|
||||
describe('calculateSegments failures', () => {
|
||||
it('FE-COMP-ROUTECALCULATOR-031: throws when OSRM answers with an HTTP error', async () => {
|
||||
server.use(http.get(`${OSRM_BASE}/driving/:coords`, () => HttpResponse.json({}, { status: 502 })))
|
||||
await expect(calculateSegments([wp1, wp2])).rejects.toThrow('Route could not be calculated')
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-032: throws when OSRM reports no usable route', async () => {
|
||||
server.use(http.get(`${OSRM_BASE}/driving/:coords`, () => HttpResponse.json({ code: 'NoRoute', routes: [] })))
|
||||
await expect(calculateSegments([wp1, wp2])).rejects.toThrow('No route found')
|
||||
})
|
||||
})
|
||||
|
||||
// ── calculateRouteWithLegs ─────────────────────────────────────────────────────
|
||||
|
||||
// The module caches by the exact waypoint list, so every test that must reach the
|
||||
// network needs coordinates no earlier test has used.
|
||||
let coordSeed = 0
|
||||
function freshWaypoints(count = 2) {
|
||||
coordSeed += 1
|
||||
return Array.from({ length: count }, (_, i) => ({ lat: 10 + coordSeed + i / 100, lng: 20 + coordSeed + i / 100 }))
|
||||
}
|
||||
|
||||
const buildLegsResponse = (legCount = 1) => ({
|
||||
code: 'Ok',
|
||||
routes: [{
|
||||
geometry: { coordinates: [[2.35, 48.85], [2.36, 48.86], [2.37, 48.87]] },
|
||||
distance: 4200,
|
||||
duration: 600,
|
||||
legs: Array.from({ length: legCount }, () => ({ distance: 4200 / legCount, duration: 600 / legCount })),
|
||||
}],
|
||||
})
|
||||
|
||||
function pluginRouteResult(over: Partial<PluginRouteResult> = {}): PluginRouteResult {
|
||||
return {
|
||||
pluginId: 'ev-router',
|
||||
profile: 'fastest',
|
||||
coordinates: [[48.85, 2.35], [48.9, 2.4]],
|
||||
distance: 120000,
|
||||
duration: 5400,
|
||||
legs: [{ distance: 120000, duration: 5400 }],
|
||||
viaPoints: [],
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })
|
||||
})
|
||||
|
||||
describe('calculateRouteWithLegs', () => {
|
||||
it('FE-COMP-ROUTECALCULATOR-033: returns an empty route for fewer than 2 waypoints without calling OSRM', async () => {
|
||||
const result = await calculateRouteWithLegs([wp1])
|
||||
expect(result).toEqual({ coordinates: [], distance: 0, duration: 0, legs: [] })
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-034: returns road geometry as [lat,lng] plus per-leg metadata', async () => {
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))
|
||||
const [a, b] = freshWaypoints()
|
||||
const result = await calculateRouteWithLegs([a, b])
|
||||
|
||||
// OSRM ships [lng,lat]; Leaflet wants [lat,lng].
|
||||
expect(result.coordinates).toEqual([[48.85, 2.35], [48.86, 2.36], [48.87, 2.37]])
|
||||
expect(result.distance).toBe(4200)
|
||||
expect(result.legs).toHaveLength(1)
|
||||
expect(result.legs[0].from).toEqual([a.lat, a.lng])
|
||||
expect(result.legs[0].to).toEqual([b.lat, b.lng])
|
||||
expect(result.legs[0].mid).toEqual([(a.lat + b.lat) / 2, (a.lng + b.lng) / 2])
|
||||
expect(result.legs[0].distanceText).toBe('4.2 km')
|
||||
expect(result.legs[0].drivingText).toBe('10 min')
|
||||
expect(result.legs[0].walkingText).toBe('50 min')
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-035: a repeated call is served from the cache instead of the network', async () => {
|
||||
let hits = 0
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))
|
||||
const wps = freshWaypoints()
|
||||
const first = await calculateRouteWithLegs(wps)
|
||||
const second = await calculateRouteWithLegs(wps)
|
||||
|
||||
expect(hits).toBe(1)
|
||||
expect(second).toBe(first)
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-036: switching the distance unit re-fetches instead of reusing stale text (#1300)', async () => {
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse())))
|
||||
const wps = freshWaypoints()
|
||||
const metric = await calculateRouteWithLegs(wps)
|
||||
expect(metric.legs[0].distanceText).toBe('4.2 km')
|
||||
|
||||
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'imperial' } })
|
||||
const imperial = await calculateRouteWithLegs(wps)
|
||||
expect(imperial).not.toBe(metric)
|
||||
expect(imperial.legs[0].distanceText).toContain('mi')
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-037: walking and cycling go to their own FOSSGIS profile hosts', async () => {
|
||||
server.use(
|
||||
http.get(`${FOSSGIS.walking}/:coords`, () => HttpResponse.json(buildLegsResponse())),
|
||||
http.get(`${FOSSGIS.cycling}/:coords`, () => HttpResponse.json(buildLegsResponse())),
|
||||
)
|
||||
await expect(calculateRouteWithLegs(freshWaypoints(), { profile: 'walking' })).resolves.toMatchObject({ distance: 4200 })
|
||||
await expect(calculateRouteWithLegs(freshWaypoints(), { profile: 'cycling' })).resolves.toMatchObject({ distance: 4200 })
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-038: an unknown profile falls back to the car host', async () => {
|
||||
let hits = 0
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))
|
||||
await calculateRouteWithLegs(freshWaypoints(), { profile: 'hovercraft' })
|
||||
expect(hits).toBe(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-039: builds one leg per waypoint pair', async () => {
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json(buildLegsResponse(2))))
|
||||
const wps = freshWaypoints(3)
|
||||
const result = await calculateRouteWithLegs(wps)
|
||||
expect(result.legs).toHaveLength(2)
|
||||
expect(result.legs[1].from).toEqual([wps[1].lat, wps[1].lng])
|
||||
expect(result.legs[1].to).toEqual([wps[2].lat, wps[2].lng])
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-040: throws on an OSRM HTTP error so the caller can fall back to a straight line', async () => {
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({}, { status: 503 })))
|
||||
await expect(calculateRouteWithLegs(freshWaypoints())).rejects.toThrow('Route could not be calculated')
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-041: throws when OSRM reports no route', async () => {
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({ code: 'NoRoute', routes: [] })))
|
||||
await expect(calculateRouteWithLegs(freshWaypoints())).rejects.toThrow('No route found')
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-042: a route without legs still returns its geometry', async () => {
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({
|
||||
code: 'Ok',
|
||||
routes: [{ geometry: { coordinates: [[2.35, 48.85]] }, distance: 10, duration: 5 }],
|
||||
})))
|
||||
const result = await calculateRouteWithLegs(freshWaypoints())
|
||||
expect(result.legs).toEqual([])
|
||||
expect(result.coordinates).toEqual([[48.85, 2.35]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateRouteWithLegs plugin profiles', () => {
|
||||
it('FE-COMP-ROUTECALCULATOR-043: refuses a plugin route without a trip context', async () => {
|
||||
const spy = vi.spyOn(pluginsApi, 'pluginRoute')
|
||||
await expect(
|
||||
calculateRouteWithLegs(freshWaypoints(), { profile: 'plugin:ev-router/fastest' })
|
||||
).rejects.toThrow('Plugin routing needs a trip context')
|
||||
expect(spy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-044: forwards the trip/day context and the bare coordinates to the plugin', async () => {
|
||||
const spy = vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })
|
||||
const wps = freshWaypoints()
|
||||
await calculateRouteWithLegs(wps, { profile: 'plugin:ev-router/fastest', tripId: 7, dayId: 3 })
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(
|
||||
'ev-router',
|
||||
'fastest',
|
||||
{ tripId: 7, dayId: 3, waypoints: wps.map(p => ({ lat: p.lat, lng: p.lng })) },
|
||||
{ signal: undefined },
|
||||
)
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-045: maps the plugin answer onto the normal route shape', async () => {
|
||||
vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({
|
||||
route: pluginRouteResult({
|
||||
legs: [{ distance: 120000, duration: 5400, note: '25 min charge' }],
|
||||
viaPoints: [{ lat: 48.7, lng: 2.3, label: 'Supercharger', tone: 'success', dwellSeconds: 1500 }],
|
||||
}),
|
||||
})
|
||||
const wps = freshWaypoints()
|
||||
const result = await calculateRouteWithLegs(wps, { profile: 'plugin:ev-router/fastest', tripId: 7 })
|
||||
|
||||
expect(result.coordinates).toEqual([[48.85, 2.35], [48.9, 2.4]])
|
||||
expect(result.legs[0].noteText).toBe('25 min charge')
|
||||
expect(result.legs[0].drivingText).toBe('1 h 30 min')
|
||||
expect(result.legs[0].distanceText).toBe('120 km')
|
||||
expect(result.legs[0].from).toEqual([wps[0].lat, wps[0].lng])
|
||||
expect(result.vias).toHaveLength(1)
|
||||
expect(result.vias?.[0].label).toBe('Supercharger')
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-046: a leg without a note carries no noteText, and no vias means no vias key', async () => {
|
||||
vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })
|
||||
const result = await calculateRouteWithLegs(freshWaypoints(), { profile: 'plugin:ev-router/fastest', tripId: 7 })
|
||||
expect(result.legs[0].noteText).toBeUndefined()
|
||||
expect('vias' in result).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-047: a refusing plugin throws like an OSRM outage', async () => {
|
||||
vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: null })
|
||||
await expect(
|
||||
calculateRouteWithLegs(freshWaypoints(), { profile: 'plugin:ev-router/fastest', tripId: 7 })
|
||||
).rejects.toThrow('No route found')
|
||||
})
|
||||
|
||||
it('FE-COMP-ROUTECALCULATOR-048: the same coordinates on a different day are routed again, not served from cache', async () => {
|
||||
const spy = vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })
|
||||
const wps = freshWaypoints()
|
||||
const opts = { profile: 'plugin:ev-router/fastest', tripId: 7 }
|
||||
await calculateRouteWithLegs(wps, { ...opts, dayId: 1 })
|
||||
await calculateRouteWithLegs(wps, { ...opts, dayId: 1 })
|
||||
expect(spy).toHaveBeenCalledTimes(1)
|
||||
|
||||
// A plugin may hand back different charging stops for another day, so the
|
||||
// cache key is scoped to trip + day.
|
||||
await calculateRouteWithLegs(wps, { ...opts, dayId: 2 })
|
||||
expect(spy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
// Runs last on purpose: it fills the module-level route cache to its cap, which
|
||||
// would evict the entries the tests above rely on.
|
||||
describe('calculateRouteWithLegs cache eviction', () => {
|
||||
it('FE-COMP-ROUTECALCULATOR-049: the route cache is capped and drops its oldest entry', async () => {
|
||||
const spy = vi.spyOn(pluginsApi, 'pluginRoute').mockResolvedValue({ route: pluginRouteResult() })
|
||||
const opts = { profile: 'plugin:ev-router/fastest', tripId: 99 }
|
||||
const oldest = freshWaypoints()
|
||||
await calculateRouteWithLegs(oldest, opts)
|
||||
|
||||
// ROUTE_CACHE_MAX is 200 — push past it so the first entry falls out again.
|
||||
for (let i = 0; i < 201; i++) await calculateRouteWithLegs(freshWaypoints(), opts)
|
||||
|
||||
spy.mockClear()
|
||||
await calculateRouteWithLegs(oldest, opts)
|
||||
expect(spy).toHaveBeenCalledTimes(1)
|
||||
|
||||
// The OSRM path writes into (and trims) the very same cache.
|
||||
let hits = 0
|
||||
server.use(http.get(`${FOSSGIS.driving}/:coords`, () => { hits++; return HttpResponse.json(buildLegsResponse()) }))
|
||||
await calculateRouteWithLegs(freshWaypoints())
|
||||
expect(hits).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
// FE-COMP-LOCMARKERGL-001 to FE-COMP-LOCMARKERGL-016
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { attachLocationMarker } from './locationMarkerMapbox'
|
||||
import type { GeoPosition } from '../../hooks/useGeolocation'
|
||||
|
||||
const SOURCE_ID = 'trek-location-accuracy'
|
||||
|
||||
type FeatureCollection = {
|
||||
type: 'FeatureCollection'
|
||||
features: { geometry: { type: string; coordinates: number[][][] } }[]
|
||||
}
|
||||
|
||||
// Minimal mapbox-gl stand-in: sources/layers live in plain maps so the tests can
|
||||
// assert what the handle added and removed, and `loaded` is switchable to drive
|
||||
// the "map not ready yet" branch.
|
||||
function fakeMap({ loaded = true }: { loaded?: boolean } = {}) {
|
||||
const sources = new Map<string, { setData: ReturnType<typeof vi.fn> }>()
|
||||
const layers = new Map<string, unknown>()
|
||||
const once = vi.fn()
|
||||
return {
|
||||
_sources: sources,
|
||||
_layers: layers,
|
||||
once,
|
||||
loaded: () => loaded,
|
||||
getSource: (id: string) => sources.get(id),
|
||||
addSource: vi.fn((id: string) => { sources.set(id, { setData: vi.fn() }) }),
|
||||
addLayer: vi.fn((layer: { id: string }) => { layers.set(layer.id, layer) }),
|
||||
getLayer: (id: string) => layers.get(id),
|
||||
removeLayer: vi.fn((id: string) => { layers.delete(id) }),
|
||||
removeSource: vi.fn((id: string) => { sources.delete(id) }),
|
||||
// Fires the handler the marker registered for the given event.
|
||||
fire: (event: string) => {
|
||||
const call = once.mock.calls.find(c => c[0] === event)
|
||||
;(call?.[1] as (() => void) | undefined)?.()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type FakeMarker = {
|
||||
setLngLat: ReturnType<typeof vi.fn>
|
||||
addTo: ReturnType<typeof vi.fn>
|
||||
remove: ReturnType<typeof vi.fn>
|
||||
getElement: () => HTMLElement
|
||||
_el: HTMLElement
|
||||
}
|
||||
|
||||
let markers: FakeMarker[] = []
|
||||
|
||||
// A marker that mirrors mapbox's DOM contract: addTo appends the element (so
|
||||
// `getElement().parentElement` becomes truthy), remove detaches it again.
|
||||
const FakeMarkerCtor = vi.fn(function (options?: { element?: HTMLElement }) {
|
||||
const el = options?.element ?? document.createElement('div')
|
||||
const marker: FakeMarker = {
|
||||
_el: el,
|
||||
setLngLat: vi.fn(() => marker),
|
||||
addTo: vi.fn(() => { document.body.appendChild(el); return marker }),
|
||||
remove: vi.fn(() => { el.remove() }),
|
||||
getElement: () => el,
|
||||
}
|
||||
markers.push(marker)
|
||||
return marker
|
||||
}) as unknown as new (options?: { element?: HTMLElement; anchor?: string }) => unknown
|
||||
|
||||
function position(over: Partial<GeoPosition> = {}): GeoPosition {
|
||||
return { lat: 48.2, lng: 16.37, accuracy: 20, heading: null, speed: null, timestamp: 1 , ...over } as GeoPosition
|
||||
}
|
||||
|
||||
function lastData(map: ReturnType<typeof fakeMap>): FeatureCollection | undefined {
|
||||
const src = map._sources.get(SOURCE_ID)
|
||||
const calls = src?.setData.mock.calls ?? []
|
||||
return calls[calls.length - 1]?.[0] as FeatureCollection | undefined
|
||||
}
|
||||
|
||||
function attach(map: ReturnType<typeof fakeMap>) {
|
||||
return attachLocationMarker(map as never, FakeMarkerCtor as never)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
markers = []
|
||||
vi.clearAllMocks()
|
||||
document.getElementById('trek-location-style')?.remove()
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
describe('attachLocationMarker', () => {
|
||||
it('FE-COMP-LOCMARKERGL-001: injects the pulse keyframes exactly once per document', () => {
|
||||
attach(fakeMap())
|
||||
attach(fakeMap())
|
||||
const styles = document.querySelectorAll('#trek-location-style')
|
||||
expect(styles).toHaveLength(1)
|
||||
expect(styles[0].textContent).toContain('@keyframes trek-location-pulse')
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-002: builds a marker element with a pulse, a heading cone and a dot', () => {
|
||||
attach(fakeMap())
|
||||
const root = markers[0]._el
|
||||
expect(root.children).toHaveLength(3)
|
||||
// The cone starts hidden — there is no heading until the first fix.
|
||||
expect((root.children[1] as HTMLElement).style.display).toBe('none')
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-003: adds the accuracy source and fill layer when the map is already loaded', () => {
|
||||
const map = fakeMap({ loaded: true })
|
||||
attach(map)
|
||||
expect(map.addSource).toHaveBeenCalledWith(SOURCE_ID, expect.objectContaining({ type: 'geojson' }))
|
||||
expect(map.addLayer).toHaveBeenCalledWith(expect.objectContaining({ id: SOURCE_ID, type: 'fill' }))
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-004: defers the layer to the load event when the map is not ready', () => {
|
||||
const map = fakeMap({ loaded: false })
|
||||
attach(map)
|
||||
expect(map.addSource).not.toHaveBeenCalled()
|
||||
expect(map.once).toHaveBeenCalledWith('load', expect.any(Function))
|
||||
|
||||
map.fire('load')
|
||||
expect(map.addSource).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-005: does not re-add the layer when the source already exists', () => {
|
||||
const map = fakeMap({ loaded: true })
|
||||
attach(map)
|
||||
map.addSource.mockClear()
|
||||
map.addLayer.mockClear()
|
||||
// A second marker on the same map (e.g. a remount) must reuse the source.
|
||||
attach(map)
|
||||
expect(map.addSource).not.toHaveBeenCalled()
|
||||
expect(map.addLayer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-006: swallows an addSource failure instead of breaking the map', () => {
|
||||
const map = fakeMap({ loaded: true })
|
||||
map.addSource.mockImplementation(() => { throw new Error('style not loaded') })
|
||||
expect(() => attach(map)).not.toThrow()
|
||||
expect(map.addLayer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-007: the first update positions the marker and adds it to the map', () => {
|
||||
const map = fakeMap()
|
||||
attach(map).update(position({ lat: 10, lng: 20 }))
|
||||
expect(markers[0].setLngLat).toHaveBeenCalledWith([20, 10])
|
||||
expect(markers[0].addTo).toHaveBeenCalledWith(map)
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-008: a follow-up update moves the marker without re-adding it', () => {
|
||||
const handle = attach(fakeMap())
|
||||
handle.update(position())
|
||||
handle.update(position({ lat: 11, lng: 21 }))
|
||||
expect(markers[0].addTo).toHaveBeenCalledTimes(1)
|
||||
expect(markers[0].setLngLat).toHaveBeenLastCalledWith([21, 11])
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-009: a heading shows the cone and rotates it', () => {
|
||||
const handle = attach(fakeMap())
|
||||
handle.update(position({ heading: 135 }))
|
||||
const cone = markers[0]._el.children[1] as HTMLElement
|
||||
expect(cone.style.display).toBe('block')
|
||||
expect(cone.style.transform).toContain('rotate(135deg)')
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-010: a null or NaN heading hides the cone again', () => {
|
||||
const handle = attach(fakeMap())
|
||||
const cone = markers[0]._el.children[1] as HTMLElement
|
||||
handle.update(position({ heading: 90 }))
|
||||
expect(cone.style.display).toBe('block')
|
||||
|
||||
handle.update(position({ heading: null }))
|
||||
expect(cone.style.display).toBe('none')
|
||||
|
||||
handle.update(position({ heading: 90 }))
|
||||
handle.update(position({ heading: NaN }))
|
||||
expect(cone.style.display).toBe('none')
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-011: an accuracy radius becomes a 48-segment geodesic ring', () => {
|
||||
const map = fakeMap()
|
||||
attach(map).update(position({ lat: 48, lng: 16, accuracy: 100 }))
|
||||
const data = lastData(map)!
|
||||
expect(data.features).toHaveLength(1)
|
||||
const ring = data.features[0].geometry.coordinates[0]
|
||||
// 48 segments produces 49 points, with the ring closed back on itself.
|
||||
expect(ring).toHaveLength(49)
|
||||
expect(ring[0][0]).toBeCloseTo(ring[48][0], 9)
|
||||
expect(ring[0][1]).toBeCloseTo(ring[48][1], 9)
|
||||
// 100 m at this latitude is well under a hundredth of a degree from the fix.
|
||||
ring.forEach(([lng, lat]) => {
|
||||
expect(Math.abs(lat - 48)).toBeLessThan(0.01)
|
||||
expect(Math.abs(lng - 16)).toBeLessThan(0.01)
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-012: a sub-metre or missing accuracy clears the ring', () => {
|
||||
const map = fakeMap()
|
||||
const handle = attach(map)
|
||||
handle.update(position({ accuracy: 0.5 }))
|
||||
expect(lastData(map)!.features).toHaveLength(0)
|
||||
|
||||
handle.update(position({ accuracy: 0 }))
|
||||
expect(lastData(map)!.features).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-013: update(null) removes the marker and empties the accuracy ring', () => {
|
||||
const map = fakeMap()
|
||||
const handle = attach(map)
|
||||
handle.update(position({ accuracy: 80 }))
|
||||
expect(lastData(map)!.features).toHaveLength(1)
|
||||
|
||||
handle.update(null)
|
||||
expect(markers[0].remove).toHaveBeenCalled()
|
||||
expect(lastData(map)!.features).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-014: an update before the source exists does not throw', () => {
|
||||
const map = fakeMap({ loaded: false })
|
||||
const handle = attach(map)
|
||||
expect(() => handle.update(position({ accuracy: 50 }))).not.toThrow()
|
||||
expect(() => handle.update(null)).not.toThrow()
|
||||
expect(markers[0].setLngLat).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-015: destroy removes the marker, the layer and the source', () => {
|
||||
const map = fakeMap()
|
||||
const handle = attach(map)
|
||||
handle.update(position())
|
||||
handle.destroy()
|
||||
expect(markers[0].remove).toHaveBeenCalled()
|
||||
expect(map.removeLayer).toHaveBeenCalledWith(SOURCE_ID)
|
||||
expect(map.removeSource).toHaveBeenCalledWith(SOURCE_ID)
|
||||
})
|
||||
|
||||
it('FE-COMP-LOCMARKERGL-016: destroy survives a torn-down map and a throwing marker', () => {
|
||||
const map = fakeMap()
|
||||
const handle = attach(map)
|
||||
markers[0].remove.mockImplementation(() => { throw new Error('marker gone') })
|
||||
map.removeLayer.mockImplementation(() => { throw new Error('style gone') })
|
||||
expect(() => handle.destroy()).not.toThrow()
|
||||
// The source removal is in the same try block, so it never ran.
|
||||
expect(map.removeSource).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
// FE-COMP-MAPBOXSETUP-001 to FE-COMP-MAPBOXSETUP-014
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import type mapboxgl from 'mapbox-gl'
|
||||
import {
|
||||
isStandardFamily,
|
||||
wantsTerrain,
|
||||
supportsCustom3d,
|
||||
addCustom3dBuildings,
|
||||
addTerrainAndSky,
|
||||
} from './mapboxSetup'
|
||||
|
||||
interface FakeMapOptions {
|
||||
layers?: string[]
|
||||
sources?: string[]
|
||||
styleLayers?: Array<{ id: string; type: string }>
|
||||
noStyle?: boolean
|
||||
addSourceThrows?: boolean
|
||||
addLayerThrows?: boolean
|
||||
setTerrainThrows?: boolean
|
||||
}
|
||||
|
||||
function fakeMap(opts: FakeMapOptions = {}) {
|
||||
const layers = new Set(opts.layers ?? [])
|
||||
const sources = new Set(opts.sources ?? [])
|
||||
return {
|
||||
getLayer: vi.fn((id: string) => (layers.has(id) ? { id } : undefined)),
|
||||
getSource: vi.fn((id: string) => (sources.has(id) ? { id } : undefined)),
|
||||
addSource: vi.fn((id: string) => {
|
||||
if (opts.addSourceThrows) throw new Error('source rejected')
|
||||
sources.add(id)
|
||||
}),
|
||||
addLayer: vi.fn((spec: { id: string }) => {
|
||||
if (opts.addLayerThrows) throw new Error('source-layer unavailable')
|
||||
layers.add(spec.id)
|
||||
}),
|
||||
getStyle: vi.fn(() => (opts.noStyle ? undefined : { layers: opts.styleLayers ?? [] })),
|
||||
setTerrain: vi.fn(() => {
|
||||
if (opts.setTerrainThrows) throw new Error('style has no terrain')
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
type FakeMap = ReturnType<typeof fakeMap>
|
||||
const asMap = (m: FakeMap) => m as unknown as mapboxgl.Map
|
||||
|
||||
describe('mapboxSetup', () => {
|
||||
it('FE-COMP-MAPBOXSETUP-001: recognises the two Standard styles as the standard family', () => {
|
||||
expect(isStandardFamily('mapbox://styles/mapbox/standard')).toBe(true)
|
||||
expect(isStandardFamily('mapbox://styles/mapbox/standard-satellite')).toBe(true)
|
||||
expect(isStandardFamily('mapbox://styles/mapbox/streets-v12')).toBe(false)
|
||||
expect(isStandardFamily('https://tiles.openfreemap.org/styles/liberty')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-002: wants terrain only for satellite and outdoors styles', () => {
|
||||
expect(wantsTerrain('mapbox://styles/mapbox/satellite-v9')).toBe(true)
|
||||
expect(wantsTerrain('mapbox://styles/mapbox/satellite-streets-v12')).toBe(true)
|
||||
expect(wantsTerrain('mapbox://styles/mapbox/outdoors-v12')).toBe(true)
|
||||
// Flat vector styles must stay flat — DEM would drift the route lines off the markers.
|
||||
expect(wantsTerrain('mapbox://styles/mapbox/streets-v12')).toBe(false)
|
||||
expect(wantsTerrain('mapbox://styles/mapbox/standard')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-003: custom 3D is offered for everything outside the standard family', () => {
|
||||
expect(supportsCustom3d('mapbox://styles/mapbox/streets-v12')).toBe(true)
|
||||
expect(supportsCustom3d('mapbox://styles/mapbox/satellite-v9')).toBe(true)
|
||||
expect(supportsCustom3d('mapbox://styles/mapbox/standard')).toBe(false)
|
||||
expect(supportsCustom3d('mapbox://styles/mapbox/standard-satellite')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-004: addCustom3dBuildings bails out when the layer already exists', () => {
|
||||
const map = fakeMap({ layers: ['trek-3d-buildings'] })
|
||||
addCustom3dBuildings(asMap(map), false)
|
||||
expect(map.addLayer).not.toHaveBeenCalled()
|
||||
expect(map.addSource).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-005: uses the style composite source and inserts below the first symbol layer', () => {
|
||||
const map = fakeMap({
|
||||
sources: ['composite'],
|
||||
styleLayers: [
|
||||
{ id: 'water', type: 'fill' },
|
||||
{ id: 'place-labels', type: 'symbol' },
|
||||
{ id: 'road-labels', type: 'symbol' },
|
||||
],
|
||||
})
|
||||
addCustom3dBuildings(asMap(map), false)
|
||||
|
||||
expect(map.addSource).not.toHaveBeenCalled()
|
||||
const [spec, beforeId] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>, string]
|
||||
expect(spec.id).toBe('trek-3d-buildings')
|
||||
expect(spec.source).toBe('composite')
|
||||
expect(spec.type).toBe('fill-extrusion')
|
||||
// Extrusions must sit under the first label layer so text stays readable.
|
||||
expect(beforeId).toBe('place-labels')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-006: attaches the streets tileset when the style has no composite source', () => {
|
||||
const map = fakeMap({ styleLayers: [] })
|
||||
addCustom3dBuildings(asMap(map), false)
|
||||
|
||||
expect(map.addSource).toHaveBeenCalledWith('mapbox-streets-v8', {
|
||||
type: 'vector',
|
||||
url: 'mapbox://mapbox.mapbox-streets-v8',
|
||||
})
|
||||
const [spec, beforeId] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>, string | undefined]
|
||||
expect(spec.source).toBe('mapbox-streets-v8')
|
||||
// No symbol layer in the style: nothing to insert before.
|
||||
expect(beforeId).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-007: reuses an already attached streets tileset', () => {
|
||||
const map = fakeMap({ sources: ['mapbox-streets-v8'] })
|
||||
addCustom3dBuildings(asMap(map), false)
|
||||
|
||||
expect(map.addSource).not.toHaveBeenCalled()
|
||||
const [spec] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>]
|
||||
expect(spec.source).toBe('mapbox-streets-v8')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-008: gives up quietly when the fallback source cannot be added', () => {
|
||||
const map = fakeMap({ addSourceThrows: true })
|
||||
expect(() => addCustom3dBuildings(asMap(map), false)).not.toThrow()
|
||||
expect(map.addLayer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-009: swallows a rejected extrusion layer', () => {
|
||||
const map = fakeMap({ sources: ['composite'], addLayerThrows: true })
|
||||
expect(() => addCustom3dBuildings(asMap(map), false)).not.toThrow()
|
||||
expect(map.addLayer).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-010: picks the dark building colour in dark mode', () => {
|
||||
const light = fakeMap({ sources: ['composite'] })
|
||||
addCustom3dBuildings(asMap(light), false)
|
||||
const dark = fakeMap({ sources: ['composite'] })
|
||||
addCustom3dBuildings(asMap(dark), true)
|
||||
|
||||
const paintOf = (m: FakeMap) => (m.addLayer.mock.calls[0][0] as unknown as { paint: Record<string, unknown> }).paint
|
||||
expect(paintOf(light)['fill-extrusion-color']).toBe('#cfd2d6')
|
||||
expect(paintOf(dark)['fill-extrusion-color']).toBe('#3b3b3f')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-011: survives a style that reports no layers at all', () => {
|
||||
const map = fakeMap({ sources: ['composite'], noStyle: true })
|
||||
addCustom3dBuildings(asMap(map), false)
|
||||
const [, beforeId] = map.addLayer.mock.calls[0] as unknown as [unknown, string | undefined]
|
||||
expect(beforeId).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-012: addTerrainAndSky adds the DEM source, the terrain and the sky layer', () => {
|
||||
const map = fakeMap()
|
||||
addTerrainAndSky(asMap(map))
|
||||
|
||||
expect(map.addSource).toHaveBeenCalledWith('mapbox-dem', {
|
||||
type: 'raster-dem',
|
||||
url: 'mapbox://mapbox.mapbox-terrain-dem-v1',
|
||||
tileSize: 512,
|
||||
maxzoom: 14,
|
||||
})
|
||||
expect(map.setTerrain).toHaveBeenCalledWith({ source: 'mapbox-dem', exaggeration: 1.2 })
|
||||
const [spec] = map.addLayer.mock.calls[0] as unknown as [Record<string, unknown>]
|
||||
expect(spec.id).toBe('sky')
|
||||
expect(spec.type).toBe('sky')
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-013: does not re-add DEM or sky when they are already there', () => {
|
||||
const map = fakeMap({ sources: ['mapbox-dem'], layers: ['sky'] })
|
||||
addTerrainAndSky(asMap(map))
|
||||
|
||||
expect(map.addSource).not.toHaveBeenCalled()
|
||||
expect(map.addLayer).not.toHaveBeenCalled()
|
||||
// Terrain itself is re-applied — it is what the style rebuild dropped.
|
||||
expect(map.setTerrain).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-MAPBOXSETUP-014: swallows a style that does not support terrain', () => {
|
||||
const map = fakeMap({ setTerrainThrows: true })
|
||||
expect(() => addTerrainAndSky(asMap(map))).not.toThrow()
|
||||
expect(map.addLayer).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,132 @@
|
||||
// FE-COMP-PLACEPOPUP-001 to FE-COMP-PLACEPOPUP-014
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildPlacePopupHtml, buildPoiPopupHtml } from './placePopup'
|
||||
import { buildPlace } from '../../../tests/helpers/factories'
|
||||
import type { Poi } from './poiCategories'
|
||||
import type { Place } from '../../types'
|
||||
|
||||
type PopupPlace = Place & {
|
||||
category_color?: string | null
|
||||
category_icon?: string | null
|
||||
category_name?: string | null
|
||||
}
|
||||
|
||||
function popupPlace(overrides: Partial<PopupPlace> = {}): PopupPlace {
|
||||
return {
|
||||
...buildPlace(),
|
||||
category_color: null,
|
||||
category_icon: null,
|
||||
category_name: null,
|
||||
...overrides,
|
||||
} as PopupPlace
|
||||
}
|
||||
|
||||
function poi(overrides: Partial<Poi> = {}): Poi {
|
||||
return {
|
||||
osm_id: 'node/1',
|
||||
name: 'Café Central',
|
||||
lat: 48.21,
|
||||
lng: 16.36,
|
||||
category: 'cafe',
|
||||
poi_type: 'cafe',
|
||||
address: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
opening_hours: null,
|
||||
cuisine: null,
|
||||
source: 'openstreetmap',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildPlacePopupHtml', () => {
|
||||
it('FE-COMP-PLACEPOPUP-001: renders the name and nothing else for a bare place', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace({ name: 'Louvre', address: null }), null)
|
||||
expect(html).toContain('Louvre')
|
||||
expect(html).not.toContain('<img')
|
||||
expect(html).not.toContain('<svg')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-002: escapes HTML metacharacters in the name', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace({ name: 'Bar & "Grill" <b>x</b>' }), null)
|
||||
expect(html).toContain('Bar & "Grill" <b>x</b>')
|
||||
expect(html).not.toContain('<b>x</b>')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-003: embeds a data: thumbnail as an img', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace(), 'data:image/jpeg;base64,AAAA')
|
||||
expect(html).toContain('<img src="data:image/jpeg;base64,AAAA"')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-004: embeds a photo-proxy URL as an img', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace(), '/api/maps/place-photo/abc123')
|
||||
expect(html).toContain('<img src="/api/maps/place-photo/abc123"')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-005: ignores a foreign photo URL — it is a fetch seed, not a src', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace(), 'https://lh3.googleusercontent.com/p/AF1')
|
||||
expect(html).not.toContain('<img')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-006: renders the category row with an inline icon svg', () => {
|
||||
const html = buildPlacePopupHtml(
|
||||
popupPlace({ category_name: 'Museum', category_icon: 'Landmark', category_color: '#6366F1' }),
|
||||
null,
|
||||
)
|
||||
expect(html).toContain('Museum')
|
||||
expect(html).toContain('<svg')
|
||||
expect(html).toContain('#6366F1')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-007: an unknown icon name falls back to the MapPin glyph', () => {
|
||||
const known = buildPlacePopupHtml(popupPlace({ category_name: 'X', category_icon: 'MapPin' }), null)
|
||||
const unknown = buildPlacePopupHtml(popupPlace({ category_name: 'X', category_icon: 'NoSuchIcon' }), null)
|
||||
const svgOf = (s: string) => s.slice(s.indexOf('<svg'), s.indexOf('</svg>'))
|
||||
expect(svgOf(unknown)).toBe(svgOf(known))
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-008: a category without an icon draws no category row', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace({ category_name: 'Museum', category_icon: null }), null)
|
||||
expect(html).not.toContain('Museum')
|
||||
expect(html).not.toContain('<svg')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-009: an icon without a category name draws no category row', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace({ category_name: null, category_icon: 'Landmark' }), null)
|
||||
expect(html).not.toContain('<svg')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-010: renders and escapes the address', () => {
|
||||
const html = buildPlacePopupHtml(popupPlace({ address: 'Rue <A> & B' }), null)
|
||||
expect(html).toContain('Rue <A> & B')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-011: a category icon with no colour falls back to grey', () => {
|
||||
const html = buildPlacePopupHtml(
|
||||
popupPlace({ category_name: 'Museum', category_icon: 'Landmark', category_color: null }),
|
||||
null,
|
||||
)
|
||||
expect(html).toContain('#6b7280')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildPoiPopupHtml', () => {
|
||||
it('FE-COMP-PLACEPOPUP-012: renders the POI name with its category-coloured icon', () => {
|
||||
const html = buildPoiPopupHtml(poi({ name: 'Café Central', category: 'cafe' }))
|
||||
expect(html).toContain('Café Central')
|
||||
expect(html).toContain('<svg')
|
||||
// cafe → #B45309 in POI_CATEGORIES
|
||||
expect(html).toContain('#B45309')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-013: an unknown category renders no icon and the grey fallback', () => {
|
||||
const html = buildPoiPopupHtml(poi({ category: 'not-a-category', name: 'Somewhere' }))
|
||||
expect(html).not.toContain('<svg')
|
||||
expect(html).toContain('Somewhere')
|
||||
})
|
||||
|
||||
it('FE-COMP-PLACEPOPUP-014: escapes the POI address and omits it when absent', () => {
|
||||
expect(buildPoiPopupHtml(poi({ address: null }))).not.toContain('margin-top:3px')
|
||||
expect(buildPoiPopupHtml(poi({ address: 'Herrengasse 14 & 16' }))).toContain('Herrengasse 14 & 16')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { ReservationMapboxOverlay } from './reservationsMapbox'
|
||||
import type { Reservation } from '../../types'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
ReservationMapboxOverlay,
|
||||
RESERVATION_SOURCE_ID,
|
||||
RESERVATION_LINE_LAYER_ID,
|
||||
type ReservationOverlayOptions,
|
||||
} from './reservationsMapbox'
|
||||
import type { Reservation, ReservationEndpoint } from '../../types'
|
||||
|
||||
// A minimal mapbox-gl stand-in: a persistent source that records the last
|
||||
// setData, and project() spreading points far enough apart to pass the
|
||||
@@ -134,3 +139,577 @@ describe('ReservationMapboxOverlay transit routes (#1570)', () => {
|
||||
expect(data.features).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
// ── FE-COMP-RESGL-001 to FE-COMP-RESGL-023 ────────────────────────────────────
|
||||
// The fake above always hands back a source, which makes the constructor skip
|
||||
// setupLayer. This one starts empty like a real freshly-styled map, records its
|
||||
// event handlers so the tests can fire them, and lets a test swap the projection
|
||||
// mid-flight to simulate a zoom.
|
||||
|
||||
type Handler = () => void
|
||||
type Projection = (c: [number, number]) => { x: number; y: number }
|
||||
|
||||
const spread: Projection = ([lng, lat]) => ({ x: lng * 1000, y: lat * 1000 })
|
||||
const collapsed: Projection = () => ({ x: 0, y: 0 })
|
||||
|
||||
function freshMap(projection: Projection = spread) {
|
||||
const sources = new Map<string, { setData: ReturnType<typeof vi.fn> }>()
|
||||
const layers = new Map<string, unknown>()
|
||||
const handlers: Record<string, Handler[]> = {}
|
||||
return {
|
||||
projection,
|
||||
_sources: sources,
|
||||
_layers: layers,
|
||||
getSource: (id: string) => sources.get(id),
|
||||
addSource: vi.fn((id: string) => { sources.set(id, { setData: vi.fn() }) }),
|
||||
addLayer: vi.fn((layer: { id: string }) => { layers.set(layer.id, layer) }),
|
||||
getLayer: (id: string) => layers.get(id),
|
||||
removeLayer: vi.fn((id: string) => { layers.delete(id) }),
|
||||
removeSource: vi.fn((id: string) => { sources.delete(id) }),
|
||||
on: vi.fn(function (this: void, event: string, fn: Handler) { (handlers[event] ||= []).push(fn) }),
|
||||
off: vi.fn((event: string, fn: Handler) => { handlers[event] = (handlers[event] || []).filter(h => h !== fn) }),
|
||||
getZoom: () => 12,
|
||||
project(this: { projection: Projection }, c: [number, number]) { return this.projection(c) },
|
||||
fire: (event: string) => { (handlers[event] || []).forEach(h => h()) },
|
||||
listeners: (event: string) => (handlers[event] || []).length,
|
||||
}
|
||||
}
|
||||
|
||||
type MarkerRecord = { el: HTMLElement; remove: ReturnType<typeof vi.fn>; lngLat: [number, number] | null }
|
||||
let glMarkers: MarkerRecord[] = []
|
||||
|
||||
// Unlike FakeMarker above this keeps the element it was handed, so the tests can
|
||||
// read the rendered badge and dispatch real clicks on it.
|
||||
const TrackingMarker = vi.fn(function (options?: { element?: HTMLElement }) {
|
||||
const record: MarkerRecord = {
|
||||
el: options?.element ?? document.createElement('div'),
|
||||
remove: vi.fn(),
|
||||
lngLat: null,
|
||||
}
|
||||
glMarkers.push(record)
|
||||
const marker = {
|
||||
setLngLat: (lngLat: [number, number]) => { record.lngLat = lngLat; return marker },
|
||||
addTo: () => marker,
|
||||
remove: record.remove,
|
||||
getElement: () => record.el,
|
||||
}
|
||||
return marker
|
||||
}) as unknown as new (options?: { element?: HTMLElement; anchor?: string }) => unknown
|
||||
|
||||
function endpoint(over: Partial<ReservationEndpoint> = {}): ReservationEndpoint {
|
||||
return {
|
||||
role: 'from', sequence: 0, name: 'A', code: null,
|
||||
lat: 48, lng: 2, timezone: null, local_time: null, local_date: null,
|
||||
...over,
|
||||
} as unknown as ReservationEndpoint
|
||||
}
|
||||
|
||||
function booking(over: Partial<Reservation> = {}): Reservation {
|
||||
return {
|
||||
id: 100, type: 'flight', status: 'confirmed',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: -0.5 }),
|
||||
],
|
||||
...over,
|
||||
} as unknown as Reservation
|
||||
}
|
||||
|
||||
const labelled = { showConnections: true, showStats: false, showEndpointLabels: true }
|
||||
|
||||
function features(map: ReturnType<typeof freshMap>) {
|
||||
const src = map._sources.get(RESERVATION_SOURCE_ID)
|
||||
const calls = src?.setData.mock.calls ?? []
|
||||
const data = calls[calls.length - 1]?.[0] as {
|
||||
features: { properties: Record<string, unknown>; geometry: { coordinates: [number, number][] } }[]
|
||||
} | undefined
|
||||
return data?.features ?? []
|
||||
}
|
||||
|
||||
function attach(map: ReturnType<typeof freshMap>, options: ReservationOverlayOptions = opts) {
|
||||
return new ReservationMapboxOverlay(map as never, options, TrackingMarker as never)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
glMarkers = []
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('ReservationMapboxOverlay lifecycle', () => {
|
||||
it('FE-COMP-RESGL-001: sets up the geojson source and both line layers on a fresh map', () => {
|
||||
const map = freshMap()
|
||||
attach(map)
|
||||
expect(map.addSource).toHaveBeenCalledWith(RESERVATION_SOURCE_ID, expect.objectContaining({ type: 'geojson' }))
|
||||
expect(map._layers.has(RESERVATION_LINE_LAYER_ID)).toBe(true)
|
||||
expect(map._layers.has(`${RESERVATION_LINE_LAYER_ID}-transit-casing`)).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-002: a second overlay on the same map reuses the existing source', () => {
|
||||
const map = freshMap()
|
||||
attach(map)
|
||||
map.addSource.mockClear()
|
||||
map.addLayer.mockClear()
|
||||
attach(map)
|
||||
expect(map.addSource).not.toHaveBeenCalled()
|
||||
expect(map.addLayer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-003: destroy unhooks every listener and removes the markers, layer and source', () => {
|
||||
const map = freshMap()
|
||||
const overlay = attach(map, { ...opts, onEndpointClick: vi.fn() })
|
||||
overlay.update([booking()], opts)
|
||||
expect(glMarkers).toHaveLength(2)
|
||||
|
||||
overlay.destroy()
|
||||
expect(glMarkers.every(m => m.remove.mock.calls.length > 0)).toBe(true)
|
||||
expect(map.listeners('zoomend')).toBe(0)
|
||||
expect(map.listeners('moveend')).toBe(0)
|
||||
expect(map.listeners('render')).toBe(0)
|
||||
expect(map.removeLayer).toHaveBeenCalledWith(RESERVATION_LINE_LAYER_ID)
|
||||
expect(map.removeSource).toHaveBeenCalledWith(RESERVATION_SOURCE_ID)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-004: destroy survives a map whose style is already gone', () => {
|
||||
const map = freshMap()
|
||||
const overlay = attach(map)
|
||||
map.removeLayer.mockImplementation(() => { throw new Error('style gone') })
|
||||
expect(() => overlay.destroy()).not.toThrow()
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-005: a camera move redraws — a hop that was decluttered appears once zoomed in', () => {
|
||||
const map = freshMap(collapsed)
|
||||
const overlay = attach(map)
|
||||
overlay.update([booking({ type: 'train' })], opts)
|
||||
expect(features(map)).toHaveLength(0)
|
||||
|
||||
map.projection = spread
|
||||
map.fire('zoomend')
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-006: the redraw and rotation handlers are inert once the overlay is destroyed', () => {
|
||||
const map = freshMap()
|
||||
const overlay = attach(map)
|
||||
const handlerFor = (event: string) =>
|
||||
map.on.mock.calls.find(c => c[0] === event)?.[1] as Handler
|
||||
const rerender = handlerFor('moveend')
|
||||
const rotate = handlerFor('render')
|
||||
|
||||
overlay.update([booking()], opts)
|
||||
const drawsBefore = map._sources.get(RESERVATION_SOURCE_ID)!.setData.mock.calls.length
|
||||
overlay.destroy()
|
||||
|
||||
rerender()
|
||||
rotate()
|
||||
expect(map._sources.get(RESERVATION_SOURCE_ID)).toBeUndefined()
|
||||
expect(drawsBefore).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-007: an update after the style dropped the source draws nothing', () => {
|
||||
const map = freshMap()
|
||||
const overlay = attach(map)
|
||||
map._sources.clear()
|
||||
overlay.update([booking()], opts)
|
||||
expect(glMarkers).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-008: a projection failure keeps the booking rather than hiding it', () => {
|
||||
const map = freshMap(() => { throw new Error('not projectable') })
|
||||
const overlay = attach(map)
|
||||
overlay.update([booking()], labelled)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
// The label threshold cannot be measured either, so no labels are drawn.
|
||||
expect(glMarkers[0].el.textContent).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationMapboxOverlay item filtering', () => {
|
||||
it('FE-COMP-RESGL-009: ignores reservations that are not transport', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking({ type: 'hotel' as Reservation['type'] })], opts)
|
||||
expect(features(map)).toHaveLength(0)
|
||||
expect(glMarkers).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-010: ignores a booking with fewer than two waypoints', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking({ endpoints: [endpoint({ role: 'from', sequence: 0 })] })], opts)
|
||||
expect(features(map)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-011: ignores endpoints that are neither from, to nor stop', () => {
|
||||
const map = freshMap()
|
||||
const res = booking({
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'via' as ReservationEndpoint['role'], sequence: 1, lat: 49, lng: 17 }),
|
||||
],
|
||||
})
|
||||
attach(map).update([res], opts)
|
||||
expect(features(map)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-012: orders waypoints by sequence and draws one arc per leg', () => {
|
||||
const map = freshMap()
|
||||
const res = booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'to', sequence: 2, name: 'C', lat: 51, lng: 16 }),
|
||||
endpoint({ role: 'from', sequence: 0, name: 'A', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: 1, name: 'B', lat: 49.5, lng: 16 }),
|
||||
],
|
||||
})
|
||||
attach(map).update([res], opts)
|
||||
const drawn = features(map)
|
||||
expect(drawn).toHaveLength(2)
|
||||
// GeoJSON is [lng, lat]; legs run A→B and B→C.
|
||||
expect(drawn[0].geometry.coordinates).toEqual([[16, 48], [16, 49.5]])
|
||||
expect(drawn[1].geometry.coordinates).toEqual([[16, 49.5], [16, 51]])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-013: a booking without a status is drawn as pending', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking({ status: undefined })], opts)
|
||||
expect(features(map)[0].properties.status).toBe('pending')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationMapboxOverlay endpoint markers', () => {
|
||||
it('FE-COMP-RESGL-014: places one marker per waypoint, titled with the stop name', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking()], opts)
|
||||
expect(glMarkers).toHaveLength(2)
|
||||
expect(glMarkers.map(m => m.lngLat)).toEqual([[16, 48], [-0.5, 51.5]])
|
||||
expect(glMarkers.map(m => m.el.title)).toEqual(['Vienna', 'London'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-015: no label is rendered while endpoint labels are off', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking()], opts)
|
||||
expect(glMarkers[0].el.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-016: labels show the endpoint code when there is one', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking()], labelled)
|
||||
expect(glMarkers.map(m => m.el.textContent)).toEqual(['VIE', 'LHR'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-017: a code-less stop falls back to its name with the parenthetical stripped', () => {
|
||||
const map = freshMap()
|
||||
const res = booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Wien Hbf (Bahnsteig 3)', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'München Hbf', lat: 49, lng: 16 }),
|
||||
],
|
||||
})
|
||||
attach(map).update([res], labelled)
|
||||
expect(glMarkers.map(m => m.el.textContent)).toEqual(['Wien Hbf', 'München Hbf'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-018: a short hop draws its line but not its labels', () => {
|
||||
const map = freshMap()
|
||||
// 300 px apart: past the 200 px line threshold, under the 400 px label one.
|
||||
const res = booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'Graz', code: 'GRZ', lat: 48.3, lng: 16 }),
|
||||
],
|
||||
})
|
||||
attach(map).update([res], labelled)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
expect(glMarkers.map(m => m.el.textContent)).toEqual(['', ''])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-019: a redraw replaces the previous markers instead of stacking them', () => {
|
||||
const map = freshMap()
|
||||
const overlay = attach(map)
|
||||
overlay.update([booking()], opts)
|
||||
const first = [...glMarkers]
|
||||
|
||||
overlay.update([booking()], opts)
|
||||
expect(first.every(m => m.remove.mock.calls.length > 0)).toBe(true)
|
||||
expect(glMarkers).toHaveLength(4)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-020: hiding connections drops the markers and the lines', () => {
|
||||
const map = freshMap()
|
||||
const overlay = attach(map)
|
||||
overlay.update([booking()], opts)
|
||||
const shown = [...glMarkers]
|
||||
|
||||
overlay.update([booking()], { ...opts, showConnections: false })
|
||||
expect(shown.every(m => m.remove.mock.calls.length > 0)).toBe(true)
|
||||
expect(features(map)).toHaveLength(0)
|
||||
expect(glMarkers).toHaveLength(2) // the removed ones; none were added
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-021: clicking an endpoint reports its reservation and does not reach the map', () => {
|
||||
const onEndpointClick = vi.fn()
|
||||
const clickable = { ...opts, onEndpointClick }
|
||||
const map = freshMap()
|
||||
attach(map, clickable).update([booking({ id: 77 })], clickable)
|
||||
|
||||
const wrapper = document.createElement('div')
|
||||
const onMapClick = vi.fn()
|
||||
wrapper.addEventListener('click', onMapClick)
|
||||
wrapper.appendChild(glMarkers[0].el)
|
||||
glMarkers[0].el.dispatchEvent(new MouseEvent('click', { bubbles: true }))
|
||||
|
||||
expect(onEndpointClick).toHaveBeenCalledWith(77)
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-022: without a click handler the marker stays inert', () => {
|
||||
const map = freshMap()
|
||||
attach(map, { ...opts, onEndpointClick: undefined }).update([booking()], opts)
|
||||
expect(() => glMarkers[0].el.dispatchEvent(new MouseEvent('click', { bubbles: true }))).not.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
// computeDuration feeds the stats badge, which the GL overlay no longer draws —
|
||||
// but it still runs on every update, and a throw in there blanked whole trips
|
||||
// once (#1620). These pin down that every time shape stays survivable and the
|
||||
// connection keeps being drawn.
|
||||
describe('ReservationMapboxOverlay duration math', () => {
|
||||
function timed(from: Partial<ReservationEndpoint>, to: Partial<ReservationEndpoint>, res: Partial<Reservation> = {}) {
|
||||
return booking({
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16, ...from }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'London', code: 'LHR', lat: 51.5, lng: -0.5, ...to }),
|
||||
],
|
||||
...res,
|
||||
})
|
||||
}
|
||||
|
||||
it('FE-COMP-RESGL-023: a well-formed cross-timezone flight renders', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed(
|
||||
{ timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '09:20' },
|
||||
{ timezone: 'Europe/London', local_date: '2024-01-15', local_time: '11:05' },
|
||||
)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-024: an overnight flight whose arrival reads earlier than departure renders', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed(
|
||||
{ timezone: 'Europe/Vienna', local_date: '2024-01-15', local_time: '22:30' },
|
||||
{ timezone: 'America/New_York', local_date: '2024-01-15', local_time: '02:10' },
|
||||
)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-025: a time-only endpoint borrows the date from the other side', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed(
|
||||
{ local_date: '2024-01-15', local_time: '09:20' },
|
||||
{},
|
||||
{ reservation_end_time: '17:30' } as Partial<Reservation>,
|
||||
)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
|
||||
const other = freshMap()
|
||||
attach(other).update([timed(
|
||||
{},
|
||||
{ local_date: '2024-01-15', local_time: '17:30' },
|
||||
{ reservation_time: '09:20' } as Partial<Reservation>,
|
||||
)], opts)
|
||||
expect(features(other)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-026: two date-less times render without a duration', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed({}, {}, {
|
||||
reservation_time: '09:20', reservation_end_time: '17:30',
|
||||
} as Partial<Reservation>)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-027: a booking without time zones uses the plain reservation times', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed({}, {}, {
|
||||
reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-15T17:30',
|
||||
} as Partial<Reservation>)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-028: an implausibly long gap is rendered without a duration', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed({}, {}, {
|
||||
reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-19T17:30',
|
||||
} as Partial<Reservation>)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-029: a booking with no times at all still draws its connection', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed({}, {})], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-030: a hop shorter than an hour renders', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed({}, {}, {
|
||||
reservation_time: '2024-01-15T09:20', reservation_end_time: '2024-01-15T09:50',
|
||||
} as Partial<Reservation>)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-031: a stored timestamp that carries no clock time renders', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([timed(
|
||||
{ timezone: 'Europe/Vienna' },
|
||||
{ timezone: 'Europe/London' },
|
||||
{ reservation_time: '2024-01-15T', reservation_end_time: '2024-01-15T18:00' } as Partial<Reservation>,
|
||||
)], opts)
|
||||
expect(features(map)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationMapboxOverlay declutter floors', () => {
|
||||
// At the fake projection one degree of latitude is 1000 px, so `dLat` is the
|
||||
// on-screen gap between the two endpoints divided by 1000.
|
||||
const hop = (id: number, type: string, dLat: number) => booking({
|
||||
id, type: type as Reservation['type'],
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Genoa', code: 'GOA', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'Palma', code: 'PMI', lat: 48 + dLat, lng: 16 }),
|
||||
],
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-032: a cruise needs 150 px before it is drawn', () => {
|
||||
const near = freshMap()
|
||||
attach(near, labelled).update([hop(1, 'cruise', 0.1)], labelled)
|
||||
expect(features(near)).toHaveLength(0)
|
||||
|
||||
const far = freshMap()
|
||||
attach(far, labelled).update([hop(2, 'cruise', 0.2)], labelled)
|
||||
expect(features(far)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-033: a cruise keeps its endpoint labels off below 300 px', () => {
|
||||
const map = freshMap()
|
||||
attach(map, labelled).update([hop(1, 'cruise', 0.2)], labelled)
|
||||
expect(glMarkers.map(m => m.el.textContent)).toEqual(['', ''])
|
||||
|
||||
glMarkers = []
|
||||
const wide = freshMap()
|
||||
attach(wide, labelled).update([hop(2, 'cruise', 0.4)], labelled)
|
||||
expect(glMarkers.map(m => m.el.textContent)).toEqual(['GOA', 'PMI'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationMapboxOverlay waypoint edge cases', () => {
|
||||
it('FE-COMP-RESGL-034: a booking without an endpoints array is skipped', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking({ endpoints: undefined })], opts)
|
||||
expect(features(map)).toHaveLength(0)
|
||||
expect(glMarkers).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-035: waypoints without a sequence keep their array order', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: undefined, name: 'A', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: undefined, name: 'B', lat: 49.5, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: undefined, name: 'C', lat: 51, lng: 16 }),
|
||||
],
|
||||
})], opts)
|
||||
const drawn = features(map)
|
||||
expect(drawn).toHaveLength(2)
|
||||
expect(drawn[0].geometry.coordinates).toEqual([[16, 48], [16, 49.5]])
|
||||
expect(drawn[1].geometry.coordinates).toEqual([[16, 49.5], [16, 51]])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-036: a leg whose stops share coordinates degrades to a straight segment', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking({
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Vienna', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: 1, name: 'Vienna Gate', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
})], opts)
|
||||
const drawn = features(map)
|
||||
expect(drawn).toHaveLength(2)
|
||||
expect(drawn[0].geometry.coordinates).toHaveLength(2)
|
||||
expect(drawn[1].geometry.coordinates.length).toBeGreaterThan(2)
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-037: a code-less stop between two coded ends falls back to its name', () => {
|
||||
const map = freshMap()
|
||||
attach(map, labelled).update([booking({
|
||||
type: 'train',
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Wien', code: 'VIE', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'stop', sequence: 1, name: 'Zuerich HB (Gleis 5)', code: null, lat: 50, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 2, name: 'London', code: 'LHR', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
})], labelled)
|
||||
expect(glMarkers.map(m => m.el.textContent)).toEqual(['VIE', 'Zuerich HB', 'LHR'])
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-038: an endpoint without a name gets an empty marker title', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([booking({
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: '', lat: 48, lng: 16 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'London', lat: 51.5, lng: 16 }),
|
||||
],
|
||||
})], opts)
|
||||
expect(glMarkers.map(m => m.el.title)).toEqual(['', 'London'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationMapboxOverlay transit styling', () => {
|
||||
const GEOMETRY = '__upzA_gayB_af@_pR_ry@~oR'
|
||||
|
||||
const transit = (legs: Record<string, unknown>[], over: Partial<Reservation> = {}) => booking({
|
||||
id: 200,
|
||||
type: 'transit' as Reservation['type'],
|
||||
endpoints: [
|
||||
endpoint({ role: 'from', sequence: 0, name: 'Stop A', lat: 48, lng: 2 }),
|
||||
endpoint({ role: 'to', sequence: 1, name: 'Stop B', lat: 48.05, lng: 2 }),
|
||||
],
|
||||
metadata: { transit: { legs } },
|
||||
...over,
|
||||
} as unknown as Partial<Reservation>)
|
||||
|
||||
it('FE-COMP-RESGL-039: a walking leg is grey and flagged as a walk', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([transit([{ geometry: GEOMETRY, mode: 'WALK' }])], opts)
|
||||
expect(features(map)[0].properties).toMatchObject({ transitPath: true, walk: true, color: '#64748b' })
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-040: a leg without a line colour falls back to the transit violet', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([transit([{ geometry: GEOMETRY, mode: 'BUS' }])], opts)
|
||||
expect(features(map)[0].properties).toMatchObject({ walk: false, color: '#7c3aed' })
|
||||
})
|
||||
|
||||
it('FE-COMP-RESGL-041: a transit journey without a status is drawn as pending', () => {
|
||||
const map = freshMap()
|
||||
attach(map).update([transit([{ geometry: GEOMETRY, mode: 'BUS' }], { status: undefined })], opts)
|
||||
expect(features(map)[0].properties.status).toBe('pending')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReservationMapboxOverlay frame handler', () => {
|
||||
it('FE-COMP-RESGL-042: a paint frame rotates only — it does not redraw the overlay', () => {
|
||||
const map = freshMap()
|
||||
const overlay = attach(map)
|
||||
overlay.update([booking()], opts)
|
||||
const drawsBefore = map._sources.get(RESERVATION_SOURCE_ID)!.setData.mock.calls.length
|
||||
|
||||
map.fire('render')
|
||||
|
||||
expect(map._sources.get(RESERVATION_SOURCE_ID)!.setData.mock.calls).toHaveLength(drawsBefore)
|
||||
expect(glMarkers).toHaveLength(2)
|
||||
expect(glMarkers.every(m => m.remove.mock.calls.length === 0)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// FE-COMP-POIEXPLORE-001 to FE-COMP-POIEXPLORE-016
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { TranslationProvider } from '../../i18n'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { usePoiExplore, type Bbox } from './usePoiExplore'
|
||||
import type { Poi } from './poiCategories'
|
||||
|
||||
type PoiResponse = Awaited<ReturnType<typeof mapsApi.pois>>
|
||||
|
||||
const BBOX: Bbox = { south: 48.1, west: 16.3, north: 48.3, east: 16.4 }
|
||||
|
||||
function poi(over: Partial<Poi> = {}): Poi {
|
||||
return {
|
||||
osm_id: 'node/1',
|
||||
name: 'Café Central',
|
||||
lat: 48.21,
|
||||
lng: 16.36,
|
||||
category: 'cafe',
|
||||
poi_type: 'cafe',
|
||||
address: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
opening_hours: null,
|
||||
cuisine: null,
|
||||
source: 'openstreetmap',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function response(pois: Poi[]): PoiResponse {
|
||||
return { pois, source: 'openstreetmap', truncated: false }
|
||||
}
|
||||
|
||||
// Hand-controlled promise so a test can hold a request "in flight" and decide
|
||||
// exactly when — and in which order — it settles.
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason?: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<TranslationProvider>{children}</TranslationProvider>
|
||||
)
|
||||
|
||||
function setup() {
|
||||
return renderHook(() => usePoiExplore(), { wrapper })
|
||||
}
|
||||
|
||||
const spyOnPois = () => vi.spyOn(mapsApi, 'pois')
|
||||
let pois: ReturnType<typeof spyOnPois>
|
||||
|
||||
beforeEach(() => {
|
||||
pois = spyOnPois().mockResolvedValue(response([poi()]))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('usePoiExplore', () => {
|
||||
it('FE-COMP-POIEXPLORE-001: starts with nothing selected, loaded or failed', () => {
|
||||
const { result } = setup()
|
||||
expect(result.current.active.size).toBe(0)
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(result.current.loadingKeys.size).toBe(0)
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
expect(result.current.moved).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-002: panning with nothing active does not offer "search this area"', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
expect(result.current.moved).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-003: toggling before the map reported a viewport selects but does not fetch', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(result.current.active.has('cafe')).toBe(true)
|
||||
expect(pois).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-004: toggling fetches the category for the current viewport', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(pois).toHaveBeenCalledWith('cafe', BBOX, 'en-US', expect.any(AbortSignal))
|
||||
expect(result.current.pois[0].osm_id).toBe('node/1')
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-005: the spinner is on while the request is in flight and off when it lands', async () => {
|
||||
const d = deferred<PoiResponse>()
|
||||
pois.mockReturnValue(d.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(true)
|
||||
|
||||
await act(async () => { d.resolve(response([poi()])) })
|
||||
await waitFor(() => expect(result.current.loadingKeys.has('cafe')).toBe(false))
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-006: toggling the active category turns it off and drops its markers', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(result.current.active.size).toBe(0)
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(pois).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-007: the pill is single-select — a second category replaces the first', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/2', category: 'bar', name: 'Loos Bar' })]))
|
||||
act(() => { result.current.toggle('bar') })
|
||||
// The previous category's markers vanish immediately, before the new results land.
|
||||
expect(result.current.active).toEqual(new Set(['bar']))
|
||||
expect(result.current.pois).toEqual([])
|
||||
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.pois[0].osm_id).toBe('node/2')
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-008: panning with a category active marks the results stale', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.moved).toBe(false)
|
||||
|
||||
act(() => { result.current.onViewportChange({ ...BBOX, south: 48.0 }) })
|
||||
expect(result.current.moved).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-009: searchArea refetches the active category for the new viewport', async () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
|
||||
const moved: Bbox = { south: 40, west: 10, north: 41, east: 11 }
|
||||
act(() => { result.current.onViewportChange(moved) })
|
||||
act(() => { result.current.searchArea() })
|
||||
|
||||
expect(result.current.moved).toBe(false)
|
||||
await waitFor(() => expect(pois).toHaveBeenCalledTimes(2))
|
||||
expect(pois).toHaveBeenLastCalledWith('cafe', moved, 'en-US', expect.any(AbortSignal))
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-010: searchArea without a viewport is a no-op', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.searchArea() })
|
||||
expect(pois).not.toHaveBeenCalled()
|
||||
expect(result.current.moved).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-011: searchArea with nothing active fetches nothing', () => {
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.searchArea() })
|
||||
expect(pois).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-012: a failed fetch surfaces a retryable error instead of a silent empty', async () => {
|
||||
pois.mockRejectedValue(new Error('all Overpass mirrors down'))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))
|
||||
expect(result.current.pois).toEqual([])
|
||||
expect(result.current.loadingKeys.has('cafe')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-013: a retry that succeeds clears the error flag', async () => {
|
||||
pois.mockRejectedValueOnce(new Error('timeout'))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))
|
||||
|
||||
act(() => { result.current.searchArea() })
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.errorKeys.has('cafe')).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-014: switching category clears a previous error flag', async () => {
|
||||
pois.mockRejectedValueOnce(new Error('timeout'))
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
await waitFor(() => expect(result.current.errorKeys.has('cafe')).toBe(true))
|
||||
|
||||
act(() => { result.current.toggle('bar') })
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-015: results that land after the category was switched off are dropped', async () => {
|
||||
const d = deferred<PoiResponse>()
|
||||
pois.mockReturnValue(d.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
expect(result.current.active.size).toBe(0)
|
||||
|
||||
await act(async () => { d.resolve(response([poi()])) })
|
||||
expect(result.current.pois).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-COMP-POIEXPLORE-016: a superseded request is not reported as a failure', async () => {
|
||||
const first = deferred<PoiResponse>()
|
||||
pois.mockReturnValueOnce(first.promise)
|
||||
const { result } = setup()
|
||||
act(() => { result.current.onViewportChange(BBOX) })
|
||||
act(() => { result.current.toggle('cafe') })
|
||||
|
||||
pois.mockResolvedValue(response([poi({ osm_id: 'node/9', category: 'bar' })]))
|
||||
act(() => { result.current.toggle('bar') })
|
||||
|
||||
// The abandoned cafe request rejects with axios' cancellation error.
|
||||
await act(async () => { first.reject(Object.assign(new Error('canceled'), { name: 'CanceledError' })) })
|
||||
|
||||
await waitFor(() => expect(result.current.pois).toHaveLength(1))
|
||||
expect(result.current.errorKeys.size).toBe(0)
|
||||
expect(result.current.pois[0].osm_id).toBe('node/9')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user