File size: 10,870 Bytes
4a382c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
/**
* Tests for sendMLRequest (helpers.ts lines 43β73).
*
* sendMLRequest calls getGeoJSONRequest which calls fetch() internally.
* We mock fetch globally (matching the pattern in helpers.test.ts) so we
* control what getGeoJSONRequest returns without partially mocking the module.
*
* Leaflet's geoJSON() and FeatureGroup are used on the success path.
* We mock leaflet (same style as PagePredictionMap.test.ts) so those
* constructors don't require a real DOM map.
*
* IMPORTANT: vi.mock is hoisted above imports, so the mock factory cannot
* close over module-level variables that haven't been initialised yet.
* We therefore define the mocks inside the factory using local variables,
* and expose them via the module re-export so individual tests can import
* the mocked functions and spy/assert on them after hoisting completes.
*/
vi.mock('leaflet', async () => {
const actual = await vi.importActual('leaflet')
return {
...actual,
/**
* geoJSON (aliased as LeafletGeoJSON in helpers.ts) is called as a
* plain function: `const featureNew = LeafletGeoJSON(data)`.
* It must return something that can be passed to map.addLayer()
* and collected into a FeatureGroup array.
*/
geoJSON: vi.fn(() => ({ _mock: 'geoJsonLayer' })),
/**
* FeatureGroup is used as `new FeatureGroup([...])` so its mock must
* be a real constructor (class). We use a class so vitest doesn't warn
* about non-constructor vi.fn() usage.
*/
FeatureGroup: vi.fn(function(this: any, _layers: any[]) {
this._mock = 'featureGroupInstance'
}),
icon: vi.fn(() => ({})),
}
})
vi.mock('leaflet-providers', () => ({}))
vi.mock('@geoman-io/leaflet-geoman-free', () => ({}))
// Imports must come after vi.mock declarations (hoisting order is fine here).
import { sendMLRequest } from '@/components/helpers'
import {
mapNavigationLocked,
layerControlGroupLayersRef,
waitingString,
OpenStreetMap,
} from '@/components/constants'
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Helpers
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Minimal mock Leaflet map satisfying the sendMLRequest surface.
* getBounds() shape matches what getExtentCurrentViewMapBBox accesses.
*/
const makeMockMap = (opts?: { dragEnabled?: boolean; editEnabled?: boolean }) => ({
pm: {
globalDragModeEnabled: vi.fn(() => opts?.dragEnabled ?? false),
globalEditModeEnabled: vi.fn(() => opts?.editEnabled ?? false),
disableGlobalDragMode: vi.fn(),
disableGlobalEditMode: vi.fn(),
},
getZoom: vi.fn(() => 10),
getBounds: vi.fn(() => ({
getNorthEast: () => ({ lat: 45, lng: 10 }),
getSouthWest: () => ({ lat: 44, lng: 9 }),
})),
addLayer: vi.fn(),
})
const samplePrompts = [
{ id: 1, type: 'point' as const, data: { lat: 45, lng: 10 }, label: 1 },
]
/** Minimal valid GeoJSON response shaped as getGeoJSONRequest expects */
const validParsedOutput = {
duration_run: 0.5,
output: {
geojson: '{"type":"FeatureCollection","features":[]}',
n_predictions: 1,
n_shapes_geojson: 1,
},
}
const make200Response = (parsedOutput: object) => ({
status: 200,
json: () => Promise.resolve({ body: JSON.stringify(parsedOutput) }),
})
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// T12: disables drag/edit modes and locks navigation
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
describe('T12: sendMLRequest disables drag/edit modes and locks navigation', () => {
beforeEach(() => {
mapNavigationLocked.value = false
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.restoreAllMocks()
})
it('disables drag mode when globalDragModeEnabled is true', async () => {
const mockMap = makeMockMap({ dragEnabled: true, editEnabled: true })
vi.spyOn(global, 'fetch').mockRejectedValue(new Error('network error'))
await sendMLRequest(mockMap as any, samplePrompts)
expect(mockMap.pm.disableGlobalDragMode).toHaveBeenCalledTimes(1)
})
it('disables edit mode when globalEditModeEnabled is true', async () => {
const mockMap = makeMockMap({ dragEnabled: true, editEnabled: true })
vi.spyOn(global, 'fetch').mockRejectedValue(new Error('network error'))
await sendMLRequest(mockMap as any, samplePrompts)
expect(mockMap.pm.disableGlobalEditMode).toHaveBeenCalledTimes(1)
})
it('sets mapNavigationLocked to true', async () => {
const mockMap = makeMockMap({ dragEnabled: true, editEnabled: true })
vi.spyOn(global, 'fetch').mockRejectedValue(new Error('network error'))
await sendMLRequest(mockMap as any, samplePrompts)
expect(mapNavigationLocked.value).toBe(true)
})
})
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// T13: builds correct request body
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
describe('T13: sendMLRequest builds correct request body', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('sends fetch with bbox, prompt, zoom, and source_type', async () => {
const mockMap = makeMockMap()
const fetchSpy = vi.spyOn(global, 'fetch').mockResolvedValue(make200Response(validParsedOutput) as any)
await sendMLRequest(mockMap as any, samplePrompts, OpenStreetMap)
expect(fetchSpy).toHaveBeenCalledOnce()
const [url, init] = fetchSpy.mock.calls[0]
expect(url).toBe('/infer_samgis')
const body = JSON.parse(init!.body as string)
expect(body.bbox).toEqual({
ne: { lat: 45, lng: 10 },
sw: { lat: 44, lng: 9 },
})
expect(body.prompt).toEqual(samplePrompts)
expect(body.zoom).toBe(10)
expect(body.source_type).toBe(OpenStreetMap)
})
})
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// T14: success β adds GeoJSON layer to map and calls addOverlay
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
describe('T14: sendMLRequest success adds GeoJSON layer to map', () => {
const mockAddOverlay = vi.fn()
beforeEach(() => {
mockAddOverlay.mockReset()
layerControlGroupLayersRef.value = { addOverlay: mockAddOverlay } as any
})
afterEach(() => {
vi.restoreAllMocks()
})
it('calls leafletMap.addLayer with the geoJSON layer', async () => {
const mockMap = makeMockMap()
vi.spyOn(global, 'fetch').mockResolvedValue(make200Response(validParsedOutput) as any)
await sendMLRequest(mockMap as any, samplePrompts)
// geoJSON mock returns { _mock: 'geoJsonLayer' } β addLayer should receive it
expect(mockMap.addLayer).toHaveBeenCalledTimes(1)
const layerArg = mockMap.addLayer.mock.calls[0][0]
expect(layerArg).toHaveProperty('_mock', 'geoJsonLayer')
})
it('calls layerControlGroupLayersRef.addOverlay with a FeatureGroup', async () => {
const mockMap = makeMockMap()
vi.spyOn(global, 'fetch').mockResolvedValue(make200Response(validParsedOutput) as any)
await sendMLRequest(mockMap as any, samplePrompts)
expect(mockAddOverlay).toHaveBeenCalledOnce()
// Second arg is the locale timestamp string
expect(typeof mockAddOverlay.mock.calls[0][1]).toBe('string')
// First arg is a FeatureGroup instance constructed by the mock
const overlayArg = mockAddOverlay.mock.calls[0][0]
expect(overlayArg).toHaveProperty('_mock', 'featureGroupInstance')
})
})
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// T15: error β logs and does not throw
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
describe('T15: sendMLRequest error logs and does not throw', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('does not throw when fetch rejects', async () => {
const mockMap = makeMockMap()
vi.spyOn(global, 'fetch').mockRejectedValue(new Error('network failure'))
vi.spyOn(console, 'error').mockImplementation(() => {})
await expect(sendMLRequest(mockMap as any, samplePrompts)).resolves.not.toThrow()
})
it('calls console.error at least once on fetch failure', async () => {
const mockMap = makeMockMap()
vi.spyOn(global, 'fetch').mockRejectedValue(new Error('network failure'))
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await sendMLRequest(mockMap as any, samplePrompts)
expect(errorSpy).toHaveBeenCalled()
})
})
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// T16: skips disable when drag/edit not enabled
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
describe('T16: sendMLRequest skips disable when drag/edit not enabled', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('does NOT call disableGlobalDragMode when drag mode is off', async () => {
const mockMap = makeMockMap({ dragEnabled: false, editEnabled: false })
vi.spyOn(global, 'fetch').mockResolvedValue(make200Response(validParsedOutput) as any)
await sendMLRequest(mockMap as any, samplePrompts)
expect(mockMap.pm.disableGlobalDragMode).not.toHaveBeenCalled()
})
it('does NOT call disableGlobalEditMode when edit mode is off', async () => {
const mockMap = makeMockMap({ dragEnabled: false, editEnabled: false })
vi.spyOn(global, 'fetch').mockResolvedValue(make200Response(validParsedOutput) as any)
await sendMLRequest(mockMap as any, samplePrompts)
expect(mockMap.pm.disableGlobalEditMode).not.toHaveBeenCalled()
})
})
|