Interactive interface for browsing global, full-resolution satellite imagery
Added a handful of missing tests
Jason Hurleyd0a960b0d580
diff --git a/web/js/map/model.test.js b/web/js/map/model.test.jsindex f155f3da7..7c5fd22ca 100644--- a/web/js/map/model.test.js+++ b/web/js/map/model.test.js@@ -1,507 +1,256 @@-import {- CRS_WGS_84,- CRS_WGS_84_QUERY_EXTENT,- mapIsExtentValid,- mapParser,- mapIsPolygonValid,- mapAdjustAntiMeridian,- mapDistance2D,- mapDistanceX,- mapInterpolate2D,- mapToPolys,- setVisibility,- setOpacity,- getLayerByName,-} from './map';--// ─── Mock OlGeomPolygon so it never touches real OL geometry ─────────────────-jest.mock('ol/geom/Polygon', () =>- jest.fn().mockImplementation((coords) => ({ coords, type: 'Polygon' })),-);--// =============================================================================-// Constants-// =============================================================================--describe('CRS_WGS_84', () => {- test('is EPSG:4326', () => {- expect(CRS_WGS_84).toBe('EPSG:4326');- });-});--describe('CRS_WGS_84_QUERY_EXTENT', () => {- test('is the correct bounding box', () => {- expect(CRS_WGS_84_QUERY_EXTENT).toEqual([-180, -60, 180, 60]);- });-});--// =============================================================================-// mapIsExtentValid-// =============================================================================--describe('mapIsExtentValid', () => {- test('returns false when extent is undefined', () => {- expect(mapIsExtentValid(undefined)).toBe(false);- });-- test('returns true for a valid numeric array extent', () => {- expect(mapIsExtentValid([-180, -90, 180, 90])).toBe(true);- });-- test('returns true for an all-zero extent', () => {- expect(mapIsExtentValid([0, 0, 0, 0])).toBe(true);- });-- test('returns false when one value in the array is NaN', () => {- expect(mapIsExtentValid([-180, NaN, 180, 90])).toBe(false);- });-- test('returns false when a non-numeric string is in the array (parses as NaN)', () => {- expect(mapIsExtentValid([-180, -90, 'x', 90])).toBe(false);- });-- test('returns true for an extent object that has a toArray() method returning valid values', () => {- const extentObj = { toArray: () => [-180, -90, 180, 90] };- expect(mapIsExtentValid(extentObj)).toBe(true);- });-- test('returns false for an extent object whose toArray() returns a NaN value', () => {- const extentObj = { toArray: () => [-180, NaN, 180, 90] };- expect(mapIsExtentValid(extentObj)).toBe(false);- });+import mapModel from './model';++const mockProj4Defs = jest.fn();+jest.mock('proj4', () => ({+ __esModule: true,+ default: {+ defs: (...args) => mockProj4Defs(...args),+ },+}));++const mockRegister = jest.fn();+jest.mock('ol/proj/proj4', () => ({+ register: (...args) => mockRegister(...args),+}));++const mockSetExtent = jest.fn();+const mockOlProjGet = jest.fn(() => ({ setExtent: mockSetExtent }));+jest.mock('ol/proj', () => ({+ get: (...args) => mockOlProjGet(...args),+}));++const mockIntersects = jest.fn();+jest.mock('ol/extent', () => ({+ intersects: (...args) => mockIntersects(...args),+}));++const geographicDef = {+ id: 'geographic',+ crs: 'EPSG:4326',+ proj4: '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',+ maxExtent: [-180, -90, 180, 90],+};++const arcticDef = {+ id: 'arctic',+ crs: 'EPSG:3413',+ proj4: '+proj=stere +lat_0=90 +lat_ts=70',+ maxExtent: [-4194304, -4194304, 4194304, 4194304],+};++const buildConfig = (projections) => ({ projections });++const buildModels = (selectedId = 'geographic') => ({+ proj: { selected: { id: selectedId } },});-// =============================================================================-// mapParser-// =============================================================================--describe('mapParser', () => {- describe('permalink 1.1 — map key', () => {- test('moves map value to v, parses into numeric array, no errors', () => {- const errors = [];- const state = { map: '0,1,2,3' };- mapParser(state, errors);- expect(state.v).toEqual([0, 1, 2, 3]);- expect(state.map).toBeUndefined();- expect(errors).toHaveLength(0);- });-- test('pushes an error and deletes v when map value contains a non-numeric token', () => {- const errors = [];- const state = { map: '0,1,x,3' };- mapParser(state, errors);- expect(state.v).toBeUndefined();- expect(errors).toHaveLength(1);- expect(errors[0].message).toMatch(/Invalid extent/);- });- });-- describe('permalink 1.2 — v key', () => {- test('parses valid v string into numeric array, no errors', () => {- const errors = [];- const state = { v: '0,1,2,3' };- mapParser(state, errors);- expect(state.v).toEqual([0, 1, 2, 3]);- expect(errors).toHaveLength(0);- });-- test('pushes an error and deletes v when v value contains a non-numeric token', () => {- const errors = [];- const state = { v: 'a,b,c,d' };- mapParser(state, errors);- expect(state.v).toBeUndefined();- expect(errors).toHaveLength(1);- expect(errors[0].message).toMatch(/Invalid extent/);- });-- test('parses negative coordinates correctly', () => {- const errors = [];- const state = { v: '-180,-90,180,90' };- mapParser(state, errors);- expect(state.v).toEqual([-180, -90, 180, 90]);- expect(errors).toHaveLength(0);- });- });-- describe('no map or v key present', () => {- test('does nothing when state has neither map nor v', () => {- const errors = [];- const state = {};- mapParser(state, errors);- expect(state.v).toBeUndefined();- expect(errors).toHaveLength(0);- });- });-});--// =============================================================================-// mapIsPolygonValid-// =============================================================================--describe('mapIsPolygonValid', () => {- // Helper to build a mock OL polygon whose outer ring has the given coordinates- const buildPolygon = (coords) => ({- getLinearRing: () => ({- getCoordinates: () => coords,- }),- });-- test('returns true when no consecutive points exceed maxDistance', () => {- const polygon = buildPolygon([[0, 0], [5, 0], [5, 5], [0, 5], [0, 0]]);- expect(mapIsPolygonValid(polygon, 10)).toBe(true);- });-- test('returns false when a consecutive x-distance exceeds maxDistance', () => {- // jump of 15 in x between first and second point- const polygon = buildPolygon([[0, 0], [15, 0], [15, 5], [0, 5], [0, 0]]);- expect(mapIsPolygonValid(polygon, 10)).toBe(false);- });-- test('returns true for a single-segment polygon within maxDistance', () => {- const polygon = buildPolygon([[0, 0], [10, 0]]);- expect(mapIsPolygonValid(polygon, 10)).toBe(true);- });-- test('returns false when the distance exactly exceeds maxDistance', () => {- // Math.abs(11 - 0) = 11 > 10- const polygon = buildPolygon([[0, 0], [11, 0], [11, 5]]);- expect(mapIsPolygonValid(polygon, 10)).toBe(false);- });-- test('handles negative x-direction crossing (abs value compared)', () => {- // jump from 10 to -5 → abs diff = 15 > 10- const polygon = buildPolygon([[10, 0], [-5, 0], [-5, 5]]);- expect(mapIsPolygonValid(polygon, 10)).toBe(false);- });-- test('returns true for an empty coordinate list', () => {- const polygon = buildPolygon([]);- expect(mapIsPolygonValid(polygon, 10)).toBe(true);- });-});--// =============================================================================-// mapAdjustAntiMeridian-// =============================================================================--describe('mapAdjustAntiMeridian', () => {- // mapAdjustAntiMeridian takes an OL polygon and an adjustSign value.- // It reads outer ring coords, adjusts them, and returns a new OlGeomPolygon.- const buildPolygon = (coords) => ({- getLinearRing: () => ({- getCoordinates: () => coords.map((c) => [...c]), // return copies- }),- });-- test('returns an OlGeomPolygon object', () => {- const polygon = buildPolygon([[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]);- const result = mapAdjustAntiMeridian(polygon, 0);- expect(result).toBeDefined();- });-- test('does not shift coordinates when adjustSign is 0', () => {- const OlGeomPolygon = require('ol/geom/Polygon');- OlGeomPolygon.mockClear();- const coords = [[-10, 0], [10, 0], [10, 10], [-10, 10], [-10, 0]];- const polygon = buildPolygon(coords);- mapAdjustAntiMeridian(polygon, 0);- const passedCoords = OlGeomPolygon.mock.calls[0][0][0];- expect(passedCoords).toEqual([[-10, 0], [10, 0], [10, 10], [-10, 10], [-10, 0]]);- });-- test('adds 360 to negative x-coordinates when adjustSign is positive (+1)', () => {- const OlGeomPolygon = require('ol/geom/Polygon');- OlGeomPolygon.mockClear();- const coords = [[-10, 0], [10, 0], [10, 10], [-10, 10], [-10, 0]];- const polygon = buildPolygon(coords);- mapAdjustAntiMeridian(polygon, 1);- const passedCoords = OlGeomPolygon.mock.calls[0][0][0];- // -10 → 350, 10 stays 10- expect(passedCoords[0][0]).toBe(350);- expect(passedCoords[1][0]).toBe(10);- expect(passedCoords[3][0]).toBe(350);- });-- test('leaves positive x-coordinates unchanged when adjustSign is positive', () => {- const OlGeomPolygon = require('ol/geom/Polygon');- OlGeomPolygon.mockClear();- const coords = [[10, 0], [20, 0], [20, 5], [10, 5], [10, 0]];- const polygon = buildPolygon(coords);- mapAdjustAntiMeridian(polygon, 1);- const passedCoords = OlGeomPolygon.mock.calls[0][0][0];- expect(passedCoords[0][0]).toBe(10);- expect(passedCoords[1][0]).toBe(20);- });-- test('subtracts 360 from positive x-coordinates when adjustSign is negative (-1)', () => {- const OlGeomPolygon = require('ol/geom/Polygon');- OlGeomPolygon.mockClear();- const coords = [[10, 0], [170, 0], [170, 10], [10, 10], [10, 0]];- const polygon = buildPolygon(coords);- mapAdjustAntiMeridian(polygon, -1);- const passedCoords = OlGeomPolygon.mock.calls[0][0][0];- // 10 → -350, 170 → -190- expect(passedCoords[0][0]).toBe(10 - 360);- expect(passedCoords[1][0]).toBe(170 - 360);- });-- test('leaves negative x-coordinates unchanged when adjustSign is negative', () => {- const OlGeomPolygon = require('ol/geom/Polygon');- OlGeomPolygon.mockClear();- const coords = [[-10, 0], [-20, 0], [-20, 5], [-10, 5], [-10, 0]];- const polygon = buildPolygon(coords);- mapAdjustAntiMeridian(polygon, -1);- const passedCoords = OlGeomPolygon.mock.calls[0][0][0];- expect(passedCoords[0][0]).toBe(-10);- expect(passedCoords[1][0]).toBe(-20);- });+beforeEach(() => {+ jest.clearAllMocks();+ mockIntersects.mockReturnValue(true);});-// =============================================================================-// mapDistance2D-// =============================================================================--describe('mapDistance2D', () => {- test('returns 0 for identical points', () => {- expect(mapDistance2D([0, 0], [0, 0])).toBe(0);- });-- test('returns 5 for a 3-4-5 right triangle', () => {- expect(mapDistance2D([0, 0], [3, 4])).toBe(5);+describe('mapModel construction (init)', () => {+ test('exposes default state', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ expect(self.extent).toBeNull();+ expect(self.selectedMap).toBeNull();+ expect(self.ui).toBeNull();+ expect(self.rotation).toBe(0);});- test('works correctly with negative coordinates', () => {- expect(mapDistance2D([-3, -4], [0, 0])).toBe(5);+ test('does nothing when config has no projections', () => {+ mapModel(buildModels(), {});+ expect(mockProj4Defs).not.toHaveBeenCalled();+ expect(mockRegister).not.toHaveBeenCalled();});- test('returns the horizontal distance when y values are equal', () => {- expect(mapDistance2D([0, 0], [10, 0])).toBe(10);+ test('registers projections that have both crs and proj4', () => {+ mapModel(buildModels(), buildConfig({ geographic: geographicDef, arctic: arcticDef }));+ expect(mockProj4Defs).toHaveBeenCalledTimes(2);+ expect(mockProj4Defs).toHaveBeenCalledWith(geographicDef.crs, geographicDef.proj4);+ expect(mockProj4Defs).toHaveBeenCalledWith(arcticDef.crs, arcticDef.proj4);});- test('returns the vertical distance when x values are equal', () => {- expect(mapDistance2D([0, 0], [0, 7])).toBe(7);- });-- test('is symmetric (order of points does not matter)', () => {- expect(mapDistance2D([1, 2], [4, 6])).toBeCloseTo(mapDistance2D([4, 6], [1, 2]));+ test('skips projections missing crs or proj4', () => {+ const partial = { crs: 'EPSG:4326' };+ mapModel(buildModels(), buildConfig({ partial }));+ expect(mockProj4Defs).not.toHaveBeenCalled();});});-// =============================================================================-// mapDistanceX-// =============================================================================--describe('mapDistanceX', () => {- test('returns 0 when both values are equal', () => {- expect(mapDistanceX(5, 5)).toBe(0);- });-- test('returns positive distance when p2 > p1', () => {- expect(mapDistanceX(3, 10)).toBe(7);- });-- test('returns positive distance when p1 > p2 (absolute value)', () => {- expect(mapDistanceX(10, 3)).toBe(7);+describe('self.register', () => {+ test('registers a valid definition and sets the extent', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ self.register(geographicDef);+ expect(mockProj4Defs).toHaveBeenCalledWith(geographicDef.crs, geographicDef.proj4);+ expect(mockRegister).toHaveBeenCalled();+ expect(mockOlProjGet).toHaveBeenCalledWith(geographicDef.crs);+ expect(mockSetExtent).toHaveBeenCalledWith(geographicDef.maxExtent);});- test('handles negative values', () => {- expect(mapDistanceX(-5, 5)).toBe(10);+ test('does nothing for a definition without proj4', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ self.register({ crs: 'EPSG:4326' });+ expect(mockProj4Defs).not.toHaveBeenCalled();});- test('handles both negative values', () => {- expect(mapDistanceX(-10, -3)).toBe(7);+ test('does nothing for an undefined definition', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ self.register(undefined);+ expect(mockProj4Defs).not.toHaveBeenCalled();});});-// =============================================================================-// mapInterpolate2D-// =============================================================================--describe('mapInterpolate2D', () => {- test('returns p1 exactly when amount is 0', () => {- expect(mapInterpolate2D([0, 0], [10, 10], 0)).toEqual([0, 0]);- });-- test('returns p2 exactly when amount is 1', () => {- expect(mapInterpolate2D([0, 0], [10, 10], 1)).toEqual([10, 10]);- });-- test('returns the midpoint when amount is 0.5', () => {- expect(mapInterpolate2D([0, 0], [10, 10], 0.5)).toEqual([5, 5]);- });-- test('interpolates correctly with a non-zero starting point', () => {- expect(mapInterpolate2D([2, 4], [6, 8], 0.5)).toEqual([4, 6]);- });-- test('handles negative coordinates', () => {- expect(mapInterpolate2D([-10, -10], [10, 10], 0.5)).toEqual([0, 0]);- });-- test('handles amount greater than 1 (extrapolation)', () => {- expect(mapInterpolate2D([0, 0], [10, 10], 2)).toEqual([20, 20]);+describe('self.update', () => {+ test('stores the extent', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ const extent = [-10, -10, 10, 10];+ self.update(extent);+ expect(self.extent).toBe(extent);});});-// =============================================================================-// mapToPolys-// =============================================================================--describe('mapToPolys', () => {- test('returns getPolygons() result when the geometry has a getPolygons method', () => {- const polys = [{ type: 'Polygon' }, { type: 'Polygon' }];- const geom = { getPolygons: () => polys };- expect(mapToPolys(geom)).toBe(polys);- });-- test('wraps the geometry in an array when it does not have a getPolygons method', () => {- const geom = { type: 'Polygon' };- expect(mapToPolys(geom)).toEqual([geom]);+describe('self.updateMap', () => {+ test('stores the map and ui references', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ const map = {};+ const ui = {};+ self.updateMap(map, ui);+ expect(self.selectedMap).toBe(map);+ expect(self.ui).toBe(ui);});});-// =============================================================================-// setVisibility-// =============================================================================--describe('setVisibility', () => {- describe('control layer (isControl = true)', () => {- test('calls setVisibility(true) when visible is true', () => {- const layer = { isControl: true, setVisibility: jest.fn() };- setVisibility(layer, true, 0.8);- expect(layer.setVisibility).toHaveBeenCalledWith(true);- });-- test('calls setVisibility(false) when visible is false', () => {- const layer = { isControl: true, setVisibility: jest.fn() };- setVisibility(layer, false, 0.8);- expect(layer.setVisibility).toHaveBeenCalledWith(false);- });+describe('self.getZoom', () => {+ test('returns null when no map is selected', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ expect(self.getZoom()).toBeNull();});- describe('non-control layer (isControl = false / undefined)', () => {- const buildLayer = (isCurrentlyVisible = true) => ({- isControl: false,- div: { style: { opacity: null } },- getVisibility: jest.fn().mockReturnValue(isCurrentlyVisible),- setVisibility: jest.fn(),- });-- test('sets div opacity to the given opacity when visible is true', () => {- const layer = buildLayer(true);- setVisibility(layer, true, 0.6);- expect(layer.div.style.opacity).toBe(0.6);- });-- test('sets div opacity to 0 when visible is false', () => {- const layer = buildLayer(true);- setVisibility(layer, false, 0.6);- expect(layer.div.style.opacity).toBe(0);- });-- test('calls setVisibility(true) when visible=true, opacity > 0 and layer is currently not visible', () => {- const layer = buildLayer(false); // currently invisible- setVisibility(layer, true, 0.5);- expect(layer.setVisibility).toHaveBeenCalledWith(true);- });-- test('does not call setVisibility when layer is already visible', () => {- const layer = buildLayer(true); // already visible- setVisibility(layer, true, 0.9);- expect(layer.setVisibility).not.toHaveBeenCalled();- });-- test('does not call setVisibility when visible is true but opacity is 0', () => {- const layer = buildLayer(false);- setVisibility(layer, true, 0);- expect(layer.setVisibility).not.toHaveBeenCalled();- });-- test('does not call setVisibility when visible is false', () => {- const layer = buildLayer(false);- setVisibility(layer, false, 0.8);- expect(layer.setVisibility).not.toHaveBeenCalled();- });+ test('returns the zoom from the selected map view', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ const map = { getView: () => ({ getZoom: () => 5 }) };+ self.updateMap(map, {});+ expect(self.getZoom()).toBe(5);});});-// =============================================================================-// setOpacity-// =============================================================================--describe('setOpacity', () => {- test('always calls layer.setOpacity with the given value', () => {- const layer = { setOpacity: jest.fn(), transitionEffect: 'resize', originalTransitionEffect: undefined };- setOpacity(layer, 0.5);- expect(layer.setOpacity).toHaveBeenCalledWith(0.5);- });-- describe('when opacity is exactly 1', () => {- test('restores transitionEffect to originalTransitionEffect', () => {- const layer = { setOpacity: jest.fn(), transitionEffect: 'none', originalTransitionEffect: 'resize' };- setOpacity(layer, 1);- expect(layer.transitionEffect).toBe('resize');- });-- test('defaults transitionEffect to "resize" when originalTransitionEffect is not set', () => {- const layer = { setOpacity: jest.fn(), transitionEffect: 'none', originalTransitionEffect: undefined };- setOpacity(layer, 1);- expect(layer.transitionEffect).toBe('resize');- });- });-- describe('when opacity is not 1', () => {- test('saves current transitionEffect to originalTransitionEffect', () => {- const layer = { setOpacity: jest.fn(), transitionEffect: 'resize', originalTransitionEffect: undefined };- setOpacity(layer, 0.5);- expect(layer.originalTransitionEffect).toBe('resize');- });-- test('sets transitionEffect to "none"', () => {- const layer = { setOpacity: jest.fn(), transitionEffect: 'resize', originalTransitionEffect: undefined };- setOpacity(layer, 0.5);- expect(layer.transitionEffect).toBe('none');- });-- test('also sets transitionEffect to "none" for opacity of 0', () => {- const layer = { setOpacity: jest.fn(), transitionEffect: 'resize', originalTransitionEffect: undefined };- setOpacity(layer, 0);- expect(layer.transitionEffect).toBe('none');- });+describe('self.load', () => {+ test('sets extent when within range', () => {+ const config = buildConfig({ geographic: geographicDef });+ const self = mapModel(buildModels(), config);+ const errors = [];+ const state = { v: [-10, -10, 10, 10], p: 'geographic' };+ mockIntersects.mockReturnValue(true);+ self.load(state, errors);+ expect(self.extent).toEqual(state.v);+ expect(errors).toHaveLength(0);+ expect(self.loaded).toBe(true);+ });++ test('defaults the projection to geographic when state.p is absent', () => {+ const config = buildConfig({ geographic: geographicDef });+ const self = mapModel(buildModels(), config);+ const state = { v: [-10, -10, 10, 10] };+ self.load(state, []);+ expect(self.extent).toEqual(state.v);+ });++ test('overrides geographic maxExtent and sets wrapExtent', () => {+ const geoDef = { ...geographicDef };+ const config = buildConfig({ geographic: geoDef });+ const self = mapModel(buildModels(), config);+ self.load({ v: [-10, -10, 10, 10], p: 'geographic' }, []);+ expect(geoDef.wrapExtent).toEqual([-250, -90, 250, 90]);+ });++ test('falls back to maxExtent and pushes an error when out of range', () => {+ const config = buildConfig({ arctic: arcticDef });+ const self = mapModel(buildModels(), config);+ const errors = [];+ mockIntersects.mockReturnValue(false);+ self.load({ v: [9e9, 9e9, 1e10, 1e10], p: 'arctic' }, errors);+ expect(self.extent).toEqual(arcticDef.maxExtent);+ expect(self.extent).not.toBe(arcticDef.maxExtent);+ expect(errors).toEqual([{ message: 'Extent outside of range' }]);+ });++ test('pushes an error when the projection does not exist', () => {+ const config = buildConfig({ geographic: geographicDef });+ const self = mapModel(buildModels(), config);+ const errors = [];+ self.load({ v: [-10, -10, 10, 10], p: 'does-not-exist' }, errors);+ expect(errors).toEqual([{ message: 'Projection does not exist' }]);+ });++ test('ignores extent logic when state.v is absent', () => {+ const config = buildConfig({ geographic: geographicDef });+ const self = mapModel(buildModels(), config);+ const errors = [];+ self.load({ p: 'geographic' }, errors);+ expect(self.extent).toBeNull();+ expect(errors).toHaveLength(0);+ });++ test('converts rotation to radians for polar projections', () => {+ const config = buildConfig({ arctic: arcticDef });+ const self = mapModel(buildModels(), config);+ self.load({ p: 'arctic', r: 90 }, []);+ expect(self.rotation).toBeCloseTo(Math.PI / 2);+ });++ test('handles antarctic rotation', () => {+ const config = buildConfig({ arctic: arcticDef });+ const self = mapModel(buildModels(), config);+ self.load({ p: 'antarctic', r: 180 }, []);+ expect(self.rotation).toBeCloseTo(Math.PI);+ });++ test('leaves rotation untouched when r is NaN', () => {+ const config = buildConfig({ arctic: arcticDef });+ const self = mapModel(buildModels(), config);+ self.load({ p: 'arctic', r: NaN }, []);+ expect(self.rotation).toBe(0);+ });++ test('returns self', () => {+ const config = buildConfig({ geographic: geographicDef });+ const self = mapModel(buildModels(), config);+ expect(self.load({}, [])).toBe(self);});});-// =============================================================================-// getLayerByName-// =============================================================================--describe('getLayerByName', () => {- const buildMap = (layers) => ({- getLayers: () => ({ getArray: () => layers }),- });-- test('returns the matching layer when found by wvname', () => {- const layerA = { wvname: 'layer-a' };- const layerB = { wvname: 'layer-b' };- const map = buildMap([layerA, layerB]);- expect(getLayerByName(map, 'layer-b')).toBe(layerB);- });-- test('returns undefined when no layer matches the given name', () => {- const layerA = { wvname: 'layer-a' };- const map = buildMap([layerA]);- expect(getLayerByName(map, 'nonexistent')).toBeUndefined();- });-- test('returns undefined when the layers array is empty', () => {- const map = buildMap([]);- expect(getLayerByName(map, 'any-layer')).toBeUndefined();- });-- test('returns the first matching layer when multiple layers share the same wvname', () => {- const layerA1 = { wvname: 'layer-a', index: 1 };- const layerA2 = { wvname: 'layer-a', index: 2 };- const map = buildMap([layerA1, layerA2]);- expect(getLayerByName(map, 'layer-a')).toBe(layerA1);+describe('self.save', () => {+ test('saves a clone of the extent', () => {+ const self = mapModel(buildModels(), buildConfig({}));+ self.extent = [-10, -10, 10, 10];+ const stateObj = {};+ self.save(stateObj);+ expect(stateObj.v).toEqual(self.extent);+ expect(stateObj.v).not.toBe(self.extent);+ });++ test('saves rotation in degrees for non-geographic projections', () => {+ const self = mapModel(buildModels('arctic'), buildConfig({}));+ self.rotation = Math.PI / 2;+ const stateObj = {};+ self.save(stateObj);+ expect(Number(stateObj.r)).toBeCloseTo(90);+ });++ test('does not save rotation when it is zero', () => {+ const self = mapModel(buildModels('arctic'), buildConfig({}));+ self.rotation = 0;+ const stateObj = {};+ self.save(stateObj);+ expect(stateObj.r).toBeUndefined();+ });++ test('does not save rotation for the geographic projection', () => {+ const self = mapModel(buildModels('geographic'), buildConfig({}));+ self.rotation = Math.PI / 2;+ const stateObj = {};+ self.save(stateObj);+ expect(stateObj.r).toBeUndefined();});});diff --git a/web/js/mapUI/combineUI.test.js b/web/js/mapUI/combineUI.test.jsindex c9d6864e2..c4bd009a0 100644--- a/web/js/mapUI/combineUI.test.js+++ b/web/js/mapUI/combineUI.test.js@@ -1,3 +1,156 @@-test('combineUI mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, act } from '@testing-library/react';+import configureMockStore from 'redux-mock-store';+import {+ MAP_MOUSE_OUT,+ MAP_MOVE_END,+ MAP_MOUSE_MOVE,+ MAP_SINGLE_CLICK,+ MAP_CONTEXT_MENU,+ REDUX_ACTION_DISPATCHED,+} from '../util/constants';+import util from '../util/util';+let mockMapProps;++jest.mock('cachai', () => jest.fn().mockImplementation(() => ({ clear: jest.fn() })));+jest.mock('p-queue', () => jest.fn().mockImplementation(() => ({ add: jest.fn() })));+jest.mock('../map/runningdata', () => jest.fn().mockImplementation(() => ({})));+jest.mock('../map/compare/compare', () => jest.fn(() => ({ compare: true })));+jest.mock('../map/layerbuilder', () => jest.fn(() => ({+ createLayer: jest.fn(),+ layerKey: jest.fn(),+})));++jest.mock('../util/util', () => ({+ __esModule: true,+ default: {+ events: { trigger: jest.fn(), on: jest.fn(), off: jest.fn() },+ warn: jest.fn(),+ },+}));++jest.mock('./mapUI', () => (props) => { mockMapProps = props; return null; });++const CombineUI = require('./combineUI').default;++const mockStore = configureMockStore();++const buildStore = (state = { lastAction: { type: 'SOME_ACTION' } }) => mockStore(state);++const buildProps = (overrides = {}) => ({+ models: { map: {} },+ config: { projections: {} },+ store: buildStore(),+ ...overrides,+});++const renderComponent = (props) => render(<CombineUI {...props} />);++beforeEach(() => {+ jest.clearAllMocks();+ mockMapProps = undefined;+});++describe('CombineUI', () => {+ it('renders MapUI with the expected props', () => {+ const props = buildProps();+ renderComponent(props);+ expect(mockMapProps).toBeDefined();+ expect(mockMapProps.models).toBe(props.models);+ expect(mockMapProps.config).toBe(props.config);+ expect(mockMapProps.ui).toBeDefined();+ expect(typeof mockMapProps.setUI).toBe('function');+ expect(mockMapProps.layerQueue).toBeDefined();+ expect(mockMapProps.layerCreationQueue).toBeDefined();+ expect(mockMapProps.compareMapUi).toBeDefined();+ });++ it('seeds the ui state with the expected default shape', () => {+ renderComponent(buildProps());+ const { ui } = mockMapProps;+ expect(ui.mapIsbeingDragged).toBe(false);+ expect(ui.mapIsbeingZoomed).toBe(false);+ expect(ui.proj).toEqual({});+ expect(ui.selected).toBeNull();+ expect(ui.markers).toEqual([]);+ expect(ui.processingPromise).toBeNull();+ expect(typeof ui.createLayer).toBe('function');+ expect(typeof ui.layerKey).toBe('function');+ });++ it('subscribes to the store and triggers REDUX_ACTION_DISPATCHED when notified', () => {+ const props = buildProps();+ renderComponent(props);++ act(() => { props.store.dispatch({ type: 'ANY' }); });+ expect(util.events.trigger).toHaveBeenCalledWith(+ REDUX_ACTION_DISPATCHED,+ { type: 'SOME_ACTION' },+ );+ });++ it('blurs focused inputs when a non-input element is clicked', () => {+ renderComponent(buildProps());++ const input = document.createElement('input');+ document.body.appendChild(input);+ const blurSpy = jest.spyOn(input, 'blur');++ const div = document.createElement('div');+ document.body.appendChild(div);+ div.dispatchEvent(new MouseEvent('click', { bubbles: true }));++ expect(blurSpy).toHaveBeenCalled();++ document.body.removeChild(input);+ document.body.removeChild(div);+ });++ it('registers OL map mouse handlers once maps exist in ui.proj', () => {+ jest.useFakeTimers();+ try {+ renderComponent(buildProps());+ const { setUI } = mockMapProps;++ const element = document.createElement('div');+ const elementAddSpy = jest.spyOn(element, 'addEventListener');+ const map = {+ getTargetElement: () => element,+ getView: () => ({+ getProjection: () => ({ getCode: () => 'EPSG:4326' }),+ }),+ on: jest.fn(),+ };++ act(() => {+ setUI((prev) => ({ ...prev, proj: { geographic: map } }));+ });++ act(() => { jest.runOnlyPendingTimers(); });++ expect(elementAddSpy).toHaveBeenCalledWith('mouseleave', expect.any(Function));+ const onEvents = map.on.mock.calls.map((c) => c[0]);+ expect(onEvents).toEqual(+ expect.arrayContaining(['moveend', 'pointermove', 'singleclick', 'contextmenu']),+ );++ const mouseleaveHandler = elementAddSpy.mock.calls.find((c) => c[0] === 'mouseleave')[1];+ mouseleaveHandler({ type: 'mouseleave' });+ expect(util.events.trigger).toHaveBeenCalledWith(MAP_MOUSE_OUT, { type: 'mouseleave' });++ const handlerFor = (name) => map.on.mock.calls.find((c) => c[0] === name)[1];+ handlerFor('moveend')({ e: 1 });+ handlerFor('pointermove')({ e: 2 });+ handlerFor('singleclick')({ e: 3 });+ handlerFor('contextmenu')({ e: 4 });++ expect(util.events.trigger).toHaveBeenCalledWith(MAP_MOVE_END, { e: 1 }, map, 'EPSG:4326');+ expect(util.events.trigger).toHaveBeenCalledWith(MAP_MOUSE_MOVE, { e: 2 }, map, 'EPSG:4326');+ expect(util.events.trigger).toHaveBeenCalledWith(MAP_SINGLE_CLICK, { e: 3 }, map, 'EPSG:4326');+ expect(util.events.trigger).toHaveBeenCalledWith(MAP_CONTEXT_MENU, { e: 4 }, map, 'EPSG:4326');+ } finally {+ jest.useRealTimers();+ }+ });});diff --git a/web/js/mapUI/components/dev-test-mode/utils/image-api-request-experimental.test.js b/web/js/mapUI/components/dev-test-mode/utils/image-api-request-experimental.test.jsindex fd3fdc8ea..a84a01cd2 100644--- a/web/js/mapUI/components/dev-test-mode/utils/image-api-request-experimental.test.js+++ b/web/js/mapUI/components/dev-test-mode/utils/image-api-request-experimental.test.js@@ -1,3 +1,182 @@-test('image-api-request-experimental mapUI test', () => {+import axios from 'axios';+import fetchWMSImage from './image-api-request-experimental';+jest.mock('axios');+jest.mock('file-saver', () => ({ saveAs: jest.fn() }));++const mockObjectUrl = 'blob:mock-object-url';+const mockLayer = 'MODIS_Terra_CorrectedReflectance_TrueColor';+const mockDate = '2024-06-15';+const mockExtent = [-100, 30, -80, 50];+const mockResponseData = new ArrayBuffer(8);+const mockContentType = 'image/png';+const fullExtentBBox = '-20037508.34,-20048966.1,20037508.34,20048966.1';++function buildAxiosResponse(overrides = {}) {+ return {+ data: mockResponseData,+ headers: { 'content-type': mockContentType },+ ...overrides,+ };+}++describe('fetchWMSImage (experimental)', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'error').mockImplementation(() => {});+ global.URL.createObjectURL = jest.fn(() => mockObjectUrl);+ global.URL.revokeObjectURL = jest.fn();+ axios.get.mockResolvedValue(buildAxiosResponse());+ });++ afterEach(() => {+ console.error.mockRestore();+ });++ describe('return value', () => {+ it('returns a blob object URL on success', async () => {+ const result = await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(result).toBe(mockObjectUrl);+ });++ it('returns the result of URL.createObjectURL', async () => {+ global.URL.createObjectURL.mockReturnValue('blob:custom-url');+ const result = await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(result).toBe('blob:custom-url');+ });++ it('returns null when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('Network error'));+ const result = await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(result).toBeNull();+ });+ });++ describe('axios.get call', () => {+ it('calls axios.get with the correct base URL', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(axios.get).toHaveBeenCalledWith(+ 'https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi',+ expect.anything(),+ );+ });++ it('calls axios.get with responseType "arraybuffer"', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(axios.get).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ responseType: 'arraybuffer' }),+ );+ });++ it('calls axios.get exactly once', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(axios.get).toHaveBeenCalledTimes(1);+ });+ });++ describe('WMS params', () => {+ async function getParams() {+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ return axios.get.mock.calls[0][1].params;+ }++ it('sets version to "1.3.0"', async () => {+ expect((await getParams()).version).toBe('1.3.0');+ });++ it('sets service to "WMS"', async () => {+ expect((await getParams()).service).toBe('WMS');+ });++ it('sets request to "GetMap"', async () => {+ expect((await getParams()).request).toBe('GetMap');+ });++ it('sets format to "image/png"', async () => {+ expect((await getParams()).format).toBe('image/png');+ });++ it('sets STYLE to "default"', async () => {+ expect((await getParams()).STYLE).toBe('default');+ });++ it('sets CRS to "EPSG:3857"', async () => {+ expect((await getParams()).CRS).toBe('EPSG:3857');+ });++ it('sets HEIGHT to "256"', async () => {+ expect((await getParams()).HEIGHT).toBe('256');+ });++ it('sets WIDTH to "256"', async () => {+ expect((await getParams()).WIDTH).toBe('256');+ });++ it('sets TIME to the provided date', async () => {+ expect((await getParams()).TIME).toBe(mockDate);+ });++ it('sets layers to the provided layer', async () => {+ expect((await getParams()).layers).toBe(mockLayer);+ });++ it('builds the bbox string from the extent as "x1,y1,x2,y2"', async () => {+ await fetchWMSImage(mockLayer, mockDate, [1, 2, 3, 4]);+ const params = axios.get.mock.calls[0][1].params;+ expect(params.bbox).toBe('1,2,3,4');+ });++ it('sets bbox from the provided extent values', async () => {+ expect((await getParams()).bbox).toBe('-100,30,-80,50');+ });++ it('falls back to the full extent bbox when no extent is provided', async () => {+ await fetchWMSImage(mockLayer, mockDate);+ const params = axios.get.mock.calls[0][1].params;+ expect(params.bbox).toBe(fullExtentBBox);+ });++ it('falls back to the full extent bbox when extent is undefined', async () => {+ await fetchWMSImage(mockLayer, mockDate, undefined);+ const params = axios.get.mock.calls[0][1].params;+ expect(params.bbox).toBe(fullExtentBBox);+ });+ });++ describe('Blob and URL.createObjectURL', () => {+ it('calls URL.createObjectURL with a Blob', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(URL.createObjectURL).toHaveBeenCalledTimes(1);+ const arg = URL.createObjectURL.mock.calls[0][0];+ expect(arg).toBeInstanceOf(Blob);+ });++ it('creates the Blob with the content-type from response headers', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ const blob = URL.createObjectURL.mock.calls[0][0];+ expect(blob.type).toBe(mockContentType);+ });+ });++ describe('error handling', () => {+ it('calls console.error when axios throws', async () => {+ const mockError = new Error('Network error');+ axios.get.mockRejectedValue(mockError);+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(console.error).toHaveBeenCalledWith(mockError);+ });++ it('calls console.error exactly once when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('fail'));+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(console.error).toHaveBeenCalledTimes(1);+ });++ it('does NOT call URL.createObjectURL when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('fail'));+ await fetchWMSImage(mockLayer, mockDate, mockExtent);+ expect(URL.createObjectURL).not.toHaveBeenCalled();+ });+ });});diff --git a/web/js/mapUI/mapUI.test.js b/web/js/mapUI/mapUI.test.jsindex 3f2db4948..f780825e0 100644--- a/web/js/mapUI/mapUI.test.js+++ b/web/js/mapUI/mapUI.test.js@@ -1,3 +1,439 @@-test('mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, act } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import { getActiveLayers, isRenderable, getGranuleLayer } from '../modules/layers/selectors';+import { getSelectedDate } from '../modules/date/selectors';+import { getNextDateTime } from '../modules/date/util';+import { promiseImageryForTime } from '../modules/map/util';+import { updateVectorSelection } from '../modules/vector-styles/util';+import util from '../util/util';+import { REDUX_ACTION_DISPATCHED } from '../util/constants';+import { CHANGE_PROJECTION } from '../modules/projection/constants';+import { CLEAR_ROTATE, REFRESH_ROTATE } from '../modules/map/constants';+import * as vectorStyleConstants from '../modules/vector-styles/constants';+import * as dateConstants from '../modules/date/constants';+import * as layerConstants from '../modules/layers/constants';+let mockCaptured = {};++jest.mock('./components/layers/addLayer', () => (props) => { mockCaptured.AddLayer = props; return null; });+jest.mock('./components/layers/removeLayer', () => (props) => { mockCaptured.RemoveLayer = props; return null; });+jest.mock('./components/create-map/createMap', () => (props) => { mockCaptured.CreateMap = props; return null; });+jest.mock('./components/granule-hover/granuleHover', () => (props) => { mockCaptured.GranuleHover = props; return null; });+jest.mock('./components/markers/markers', () => (props) => { mockCaptured.Markers = props; return null; });+jest.mock('./components/update-date/updateDate', () => (props) => { mockCaptured.UpdateDate = props; return null; });+jest.mock('./components/update-opacity/updateOpacity', () => (props) => { mockCaptured.UpdateOpacity = props; return null; });+jest.mock('./components/update-projection/updateProjection', () => (props) => { mockCaptured.UpdateProjection = props; return null; });+jest.mock('./components/mouse-move-events/mouseMoveEvents', () => (props) => { mockCaptured.MouseMoveEvents = props; return null; });+jest.mock('./components/buffer-quick-animate/bufferQuickAnimate', () => (props) => { mockCaptured.BufferQuickAnimate = props; return null; });+jest.mock('./components/kiosk/kiosk-animations/kiosk-animations', () => (props) => { mockCaptured.KioskAnimations = props; return null; });+jest.mock('./components/kiosk/tile-measurement/tile-measurement', () => (props) => { mockCaptured.TileMeasurement = props; return null; });+jest.mock('./components/kiosk/travel-mode/travelMode', () => (props) => { mockCaptured.TravelMode = props; return null; });+jest.mock('./components/eic/eic', () => (props) => { mockCaptured.EIC = props; return null; });+jest.mock('./components/update-collections/updateCollections', () => (props) => { mockCaptured.UpdateCollections = props; return null; });+jest.mock('./components/dev-test-mode/dev-test-button', () => (props) => { mockCaptured.DevTestButton = props; return null; });++jest.mock('../modules/layers/selectors', () => ({+ getActiveLayers: jest.fn(() => []),+ isRenderable: jest.fn(() => true),+ getGranuleLayer: jest.fn(() => undefined),+}));+jest.mock('../modules/date/selectors', () => ({ getSelectedDate: jest.fn(() => new Date('2023-01-01')) }));+jest.mock('../modules/date/util', () => ({ getNextDateTime: jest.fn(() => new Date('2023-01-02')) }));+jest.mock('../modules/map/util', () => ({ promiseImageryForTime: jest.fn(() => Promise.resolve()) }));+jest.mock('../modules/vector-styles/util', () => ({ updateVectorSelection: jest.fn() }));+jest.mock('../modules/map/actions', () => ({ updateMapExtent: jest.fn(() => ({ type: 'UPDATE_MAP_EXTENT' })) }));+jest.mock('../modules/date/actions', () => ({+ clearPreload: jest.fn(() => ({ type: 'CLEAR_PRELOAD' })),+ setPreload: jest.fn(() => ({ type: 'SET_PRELOAD' })),+}));++jest.mock('../util/util', () => ({+ __esModule: true,+ default: {+ events: { on: jest.fn(), off: jest.fn(), trigger: jest.fn() },+ warn: jest.fn(),+ },+}));++const ConnectedMapUI = require('./mapUI').default;++const mockStore = configureMockStore();++const collection = (arr) => ({+ forEach: (fn) => arr.forEach(fn),+ getArray: () => arr,+});++const makeMap = (layers = [], isRendered = true) => {+ const view = { calculateExtent: jest.fn(() => [0, 0, 10, 10]), animate: jest.fn() };+ return {+ getView: () => view,+ getLayers: () => collection(layers),+ isRendered: () => isRendered,+ };+};++const buildState = (overrides = {}) => {+ const { date: dateOverrides, ui: uiOverrides, ...rest } = overrides;+ return {+ compare: { active: false, activeString: 'active' },+ config: {},+ date: {+ arrowDown: undefined,+ lastArrowDirection: undefined,+ lastPreloadDate: null,+ preloaded: false,+ selected: new Date('2023-01-01'),+ selectedB: new Date('2023-01-02'),+ ...dateOverrides,+ },+ embed: {},+ layers: {},+ map: {},+ palettes: {},+ proj: { id: 'geographic' },+ vectorStyles: {},+ ui: {+ eic: '', travelMode: '', displayStaticMap: false, ...uiOverrides,+ },+ ...rest,+ };+};++const buildOwnProps = (over = {}) => {+ const selected = over.selected || makeMap();+ const props = {+ compareMapUi: {},+ config: {},+ layerCreationQueue: { add: jest.fn() },+ layerQueue: { add: jest.fn() },+ models: {},+ setUI: jest.fn(),+ ui: { selected, selectedVectors: {}, dislayStaticMap: false },+ ...over,+ };+ delete props.selected;+ return props;+};++const renderComponent = (ownProps = {}, state) => {+ const store = mockStore(state || buildState());+ const props = buildOwnProps(ownProps);+ const result = render(+ <Provider store={store}>+ <ConnectedMapUI {...props} />+ </Provider>,+ );+ return { store, props, ...result };+};++const getSubscriber = () => {+ const call = util.events.on.mock.calls.find((c) => c[0] === REDUX_ACTION_DISPATCHED);+ return call && call[1];+};++const child = (key) => mockCaptured[key];++beforeEach(() => {+ jest.clearAllMocks();+ mockCaptured = {};+ getActiveLayers.mockReturnValue([]);+ isRenderable.mockReturnValue(true);+ getGranuleLayer.mockReturnValue(undefined);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));+ getNextDateTime.mockReturnValue(new Date('2023-01-02'));+ promiseImageryForTime.mockResolvedValue();+});++describe('MapUI rendering', () => {+ it('mounts without errors and renders child components', () => {+ renderComponent();+ expect(child('CreateMap')).toBeDefined();+ expect(child('UpdateProjection')).toBeDefined();+ expect(child('Markers')).toBeDefined();+ });++ it('derives state props from the store (mapStateToProps)', () => {+ renderComponent();+ expect(child('UpdateProjection').ui).toBeDefined();+ expect(child('CreateMap').config).toBeDefined();+ });++ it('renders EIC / kiosk children when EIC mode is active', () => {+ const state = buildState({+ ui: { eic: 'on', travelMode: 'on', displayStaticMap: false },+ });+ renderComponent({}, state);+ expect(child('EIC')).toBeDefined();+ expect(child('KioskAnimations')).toBeDefined();+ expect(child('TileMeasurement')).toBeDefined();+ expect(child('TravelMode')).toBeDefined();+ });++ it('runs mapStateToProps for varied store state without throwing', () => {+ const state = buildState({+ ui: { eic: 'on', travelMode: 'on', displayStaticMap: true },+ compare: { active: true, activeString: 'activeB' },+ date: {+ arrowDown: 'left',+ lastArrowDirection: 'left',+ lastPreloadDate: new Date('2023-01-01'),+ preloaded: true,+ },+ });+ expect(() => renderComponent({}, state)).not.toThrow();+ });++ it('registers and removes the REDUX_ACTION_DISPATCHED listener', () => {+ const { unmount } = renderComponent();+ expect(util.events.on).toHaveBeenCalledWith(REDUX_ACTION_DISPATCHED, expect.any(Function));+ unmount();+ expect(util.events.off).toHaveBeenCalledWith(REDUX_ACTION_DISPATCHED, expect.any(Function));+ });++ it('dispatches updateMapExtent + clearPreload through mapDispatchToProps', () => {+ const { store } = renderComponent();+ act(() => { child('CreateMap').updateExtent(); });+ expect(store.getActions()).toContainEqual({ type: 'UPDATE_MAP_EXTENT' });+ expect(store.getActions()).toContainEqual({ type: 'CLEAR_PRELOAD' });+ });+});++describe('subscribeToStore', () => {+ it('handles CHANGE_PROJECTION and a variety of action types without throwing', () => {+ renderComponent();+ const subscriber = getSubscriber();+ [+ CHANGE_PROJECTION,+ layerConstants.ADD_LAYER,+ layerConstants.REMOVE_LAYER,+ dateConstants.SELECT_DATE,+ layerConstants.UPDATE_OPACITY,+ 'UNKNOWN_ACTION_TYPE',+ ].forEach((type) => {+ act(() => { subscriber({ type }); });+ });+ expect(getSubscriber()).toBeDefined();+ });++ it('animates the view back to 0 on CLEAR_ROTATE', () => {+ const selected = makeMap();+ renderComponent({ ui: { selected, selectedVectors: {} } });+ act(() => { getSubscriber()({ type: CLEAR_ROTATE }); });+ expect(selected.getView().animate).toHaveBeenCalledWith({ duration: 500, rotation: 0 });+ });++ it('animates to the requested rotation on REFRESH_ROTATE', () => {+ const selected = makeMap();+ renderComponent({ ui: { selected, selectedVectors: {} } });+ act(() => { getSubscriber()({ type: REFRESH_ROTATE, rotation: 1.2 }); });+ expect(selected.getView().animate).toHaveBeenCalledWith({ rotation: 1.2, duration: 500 });+ });++ it('runs updateVectorSelections on SET_SELECTED_VECTORS', () => {+ const { props } = renderComponent();+ act(() => {+ getSubscriber()({+ type: vectorStyleConstants.SET_SELECTED_VECTORS,+ payload: { layerA: true },+ });+ });+ expect(updateVectorSelection).toHaveBeenCalled();+ expect(props.ui.selectedVectors).toEqual({ layerA: true });+ });++ it('preloads tiles on CHANGE_INTERVAL', () => {+ const { props } = renderComponent();+ act(() => { getSubscriber()({ type: dateConstants.CHANGE_INTERVAL }); });+ expect(props.layerQueue.add).toHaveBeenCalled();+ });++ it('handles ARROW_DOWN', () => {+ renderComponent();+ expect(() => act(() => { getSubscriber()({ type: dateConstants.ARROW_DOWN }); })).not.toThrow();+ });+});++describe('updateExtent', () => {+ it('updates the map extent and clears preload when the map is rendered', () => {+ const selected = makeMap([], true);+ const { store } = renderComponent({ ui: { selected, selectedVectors: {} } });+ act(() => { child('CreateMap').updateExtent(); });+ expect(store.getActions()).toContainEqual({ type: 'UPDATE_MAP_EXTENT' });+ expect(store.getActions()).toContainEqual({ type: 'CLEAR_PRELOAD' });+ });++ it('does not clear preload when the map is not rendered', () => {+ const selected = makeMap([], false);+ const { store } = renderComponent({ ui: { selected, selectedVectors: {} } });+ act(() => { child('CreateMap').updateExtent(); });+ expect(store.getActions()).toContainEqual({ type: 'UPDATE_MAP_EXTENT' });+ expect(store.getActions()).not.toContainEqual({ type: 'CLEAR_PRELOAD' });+ });+});++describe('updateLayerVisibilities', () => {+ it('returns early when no map is selected', () => {+ renderComponent({ ui: { selected: null, selectedVectors: {} } });+ expect(() => act(() => { child('RemoveLayer').updateLayerVisibilities(); })).not.toThrow();+ });++ it('sets visibility for a plain (non-compare, non-granule) layer', () => {+ const layer = {+ wv: { id: 'l1', group: 'active' },+ get: (k) => ({ date: undefined, granuleGroup: undefined, group: undefined }[k]),+ setVisible: jest.fn(),+ getLayers: () => collection([]),+ };+ const selected = makeMap([layer]);+ renderComponent({ ui: { selected, selectedVectors: {} } });+ act(() => { child('RemoveLayer').updateLayerVisibilities(); });+ expect(layer.setVisible).toHaveBeenCalledWith(true);+ });++ it('handles compare-group layers with granule subgroups', () => {+ isRenderable.mockReturnValue(false);+ const granuleTile = {+ wv: { id: 'g-tile', group: 'active' },+ get: () => undefined,+ setVisible: jest.fn(),+ getLayers: () => collection([]),+ };+ const granuleSubLayer = {+ wv: { id: 'g-sub', group: 'active' },+ get: (k) => (k === 'granuleGroup' ? true : undefined),+ setVisible: jest.fn(),+ getLayers: () => collection([granuleTile]),+ };+ const noWvSubLayer = {+ wv: null,+ get: () => undefined,+ setVisible: jest.fn(),+ getLayers: () => collection([]),+ };+ const groupLayer = {+ wv: null,+ get: (k) => (k === 'group' ? 'active' : undefined),+ setVisible: jest.fn(),+ getLayers: () => collection([noWvSubLayer, granuleSubLayer]),+ };+ const selected = makeMap([groupLayer]);+ renderComponent({ ui: { selected, selectedVectors: {} } });+ act(() => { child('RemoveLayer').updateLayerVisibilities(); });+ expect(groupLayer.setVisible).toHaveBeenCalledWith(true);+ expect(granuleSubLayer.setVisible).toHaveBeenCalledWith(true);+ expect(granuleTile.setVisible).toHaveBeenCalled();+ });+});++describe('findLayer', () => {+ it('finds a top-level layer by wv id', () => {+ const layer = { wv: { id: 'l1' }, get: () => undefined };+ const selected = { ...makeMap(), getLayers: () => collection([layer]) };+ renderComponent({ ui: { selected, selectedVectors: {} } });+ const found = child('RemoveLayer').findLayer({ id: 'l1' }, 'active');+ expect(found).toBe(layer);+ });++ it('descends into a compare group to find the layer', () => {+ const innerLayer = { wv: { id: 'l2' }, get: () => undefined };+ const groupLayer = {+ wv: null,+ get: (k) => (k === 'group' ? 'active' : undefined),+ getLayers: () => collection([innerLayer]),+ };+ const selected = { ...makeMap(), getLayers: () => collection([groupLayer]) };+ renderComponent({ ui: { selected, selectedVectors: {} } });+ const found = child('RemoveLayer').findLayer({ id: 'l2' }, 'active');+ expect(found).toBe(innerLayer);+ });+});++describe('getGranuleOptions', () => {+ it('returns an empty object for non-granule layers', () => {+ renderComponent();+ const result = child('UpdateProjection').getGranuleOptions({}, { id: 'l1', type: 'wmts' }, 'active');+ expect(result).toEqual({});+ });++ it('returns granule state when available', () => {+ getGranuleLayer.mockReturnValue({ dates: ['2023-01-01'], count: 20, geometry: { g: 1 } });+ renderComponent();+ const result = child('UpdateProjection').getGranuleOptions(+ {},+ { id: 'gran', count: 10, type: 'granule' },+ 'active',+ );+ expect(result).toEqual({+ granuleDates: ['2023-01-01'],+ granuleCount: 20,+ geometry: { g: 1 },+ });+ });++ it('falls back to the def count and resets dates when reset matches', () => {+ getGranuleLayer.mockReturnValue({ dates: ['2023-01-01'], count: undefined, geometry: undefined });+ renderComponent();+ const result = child('UpdateProjection').getGranuleOptions(+ {},+ { id: 'gran', count: 10, type: 'granule' },+ 'active',+ { reset: 'gran' },+ );+ expect(result.granuleDates).toBe(false);+ expect(result.granuleCount).toBe(10);+ });++ it('returns undefined granule fields when there is no granule state', () => {+ getGranuleLayer.mockReturnValue(undefined);+ renderComponent();+ const result = child('UpdateProjection').getGranuleOptions(+ {},+ { id: 'gran', count: 7, type: 'granule' },+ 'active',+ );+ expect(result.granuleCount).toBe(7);+ expect(result.granuleDates).toBeUndefined();+ });+});++describe('preloadNextTiles', () => {+ it('does nothing when the static map is displayed', async () => {+ const { props } = renderComponent({+ ui: { selected: makeMap(), selectedVectors: {}, dislayStaticMap: true },+ });+ await act(async () => { await child('AddLayer').preloadNextTiles(); });+ expect(props.layerQueue.add).not.toHaveBeenCalled();+ });++ it('queues imagery for the next and previous dates', async () => {+ const { props } = renderComponent();+ await act(async () => { await child('AddLayer').preloadNextTiles(); });+ expect(props.layerQueue.add).toHaveBeenCalled();+ });++ it('dispatches setPreload and queues one date when preloaded with an arrow direction', async () => {+ const state = buildState({ date: { preloaded: true, lastArrowDirection: 'right' } });+ const { props, store } = renderComponent({}, state);+ await act(async () => { await child('AddLayer').preloadNextTiles(); });+ expect(store.getActions()).toContainEqual({ type: 'SET_PRELOAD' });+ expect(props.layerQueue.add).toHaveBeenCalledTimes(1);+ });+});++describe('preloadForCompareMode', () => {+ it('preloads only the active side when compare is inactive', async () => {+ const { props } = renderComponent();+ await act(async () => { await child('CreateMap').preloadForCompareMode(); });+ expect(props.layerQueue.add).toHaveBeenCalled();+ });++ it('preloads both sides when compare is active', async () => {+ const state = buildState({ compare: { active: true, activeString: 'active' } });+ const { props } = renderComponent({}, state);+ await act(async () => { await child('CreateMap').preloadForCompareMode(); });+ expect(props.layerQueue.add).toHaveBeenCalled();+ });});