Interactive interface for browsing global, full-resolution satellite imagery
Added unit tests for map/ and mapUI/ directories
Jason Hurleye625fcb58f6d
diff --git a/web/js/map/compare/compare.test.js b/web/js/map/compare/compare.test.jsindex f550ba606..b13b1683e 100644--- a/web/js/map/compare/compare.test.js+++ b/web/js/map/compare/compare.test.js@@ -1,3 +1,145 @@-test('compare map test', () => {+import mapCompare from './compare'; // Update with the actual path+import Swipe from './swipe';+import Opacity from './opacity';+import util from '../../util/util';+import { setValue } from '../../modules/compare/actions';+import { COMPARE_MOVE_START, COMPARE_MOVE_END } from '../../util/constants';+jest.mock('./swipe');+jest.mock('./opacity');+jest.mock('../../modules/compare/actions', () => ({+ setValue: jest.fn(),+}));+jest.mock('../../util/util', () => {+ const listeners = {};+ return {+ events: {+ on: jest.fn((event, callback) => {+ listeners[event] = callback;+ }),+ trigger: (event, payload) => {+ if (listeners[event]) listeners[event](payload);+ },+ },+ browser: {+ mobileAndTabletDevice: false,+ },+ };+});++describe('mapCompare', () => {+ let store;+ let mapMock;++ beforeEach(() => {+ jest.clearAllMocks();++ store = {+ dispatch: jest.fn(),+ getState: jest.fn(() => ({+ proj: { selected: 'EPSG:3857' },+ compare: { value: 75 },+ })),+ };++ mapMock = {};++ Swipe.mockImplementation(() => ({+ update: jest.fn(),+ destroy: jest.fn(),+ getSwipeOffset: jest.fn(() => 100),+ }));++ Opacity.mockImplementation(() => ({+ update: jest.fn(),+ destroy: jest.fn(),+ }));+ });++ it('initializes and sets up event listeners correctly', () => {+ const instance = mapCompare(store);++ expect(util.events.on).toHaveBeenCalledWith(COMPARE_MOVE_START, expect.any(Function));+ expect(util.events.on).toHaveBeenCalledWith(COMPARE_MOVE_END, expect.any(Function));++ // Trigger START+ util.events.trigger(COMPARE_MOVE_START);+ expect(instance.dragging).toBe(true);++ // Trigger END+ util.events.trigger(COMPARE_MOVE_END, 40);+ expect(instance.dragging).toBe(false);+ expect(instance.value).toBe(40);+ expect(setValue).toHaveBeenCalledWith(40);+ expect(store.dispatch).toHaveBeenCalled();+ });++ it('creates a new comparison instance', () => {+ const instance = mapCompare(store);+ instance.create(mapMock, 'swipe');++ expect(Swipe).toHaveBeenCalled();+ expect(instance.active).toBe(true);+ expect(instance.value).toBe(75);+ });++ it('updates an existing comparison instance if mode and state are the same', () => {+ const instance = mapCompare(store);+ instance.create(mapMock, 'swipe');++ const mockSwipeInstance = Swipe.mock.results[0].value;++ // Call create again with same mode and state+ instance.create(mapMock, 'swipe');+ expect(mockSwipeInstance.update).toHaveBeenCalledWith(store);+ });++ it('destroys old instance and creates new one if mode changes', () => {+ const instance = mapCompare(store);+ instance.create(mapMock, 'swipe');++ const mockSwipeInstance = Swipe.mock.results[0].value;++ instance.create(mapMock, 'opacity');+ expect(mockSwipeInstance.destroy).toHaveBeenCalled();+ expect(Opacity).toHaveBeenCalled();+ });++ it('calls update on comparison if it exists', () => {+ const instance = mapCompare(store);+ instance.create(mapMock, 'swipe');++ const mockSwipeInstance = Swipe.mock.results[0].value;+ const groupMock = {};+ instance.update(groupMock);++ expect(mockSwipeInstance.update).toHaveBeenCalledWith(store, groupMock);+ });++ it('returns offset only for swipe mode', () => {+ const instance = mapCompare(store);++ expect(instance.getOffset()).toBeNull(); // No comparison yet++ instance.create(mapMock, 'opacity');+ expect(instance.getOffset()).toBeNull(); // Wrong mode++ instance.create(mapMock, 'swipe');+ expect(instance.getOffset()).toBe(100); // Swipe mode+ });++ it('destroys the comparison properly', () => {+ const instance = mapCompare(store);+ instance.create(mapMock, 'swipe');++ const mockSwipeInstance = Swipe.mock.results[0].value;++ instance.destroy();++ expect(mockSwipeInstance.destroy).toHaveBeenCalled();+ expect(instance.value).toBe(50);+ expect(setValue).toHaveBeenCalledWith(50);+ expect(store.dispatch).toHaveBeenCalled();+ expect(instance.active).toBe(false);+ });});diff --git a/web/js/map/compare/opacity.test.js b/web/js/map/compare/opacity.test.jsindex 04732518d..c4c029bb0 100644--- a/web/js/map/compare/opacity.test.js+++ b/web/js/map/compare/opacity.test.js@@ -1,3 +1,151 @@-test('opacity map test', () => {+import { createRoot } from 'react-dom/client';+import Opacity from './opacity'; // Adjust the import path if necessary+import { getCompareDates } from '../../modules/compare/selectors';+import util from '../../util/util';+import { COMPARE_MOVE_END } from '../../util/constants';+jest.mock('react-dom/client', () => ({+ createRoot: jest.fn(),+}));++jest.mock('../../components/compare/opacity-slider', () => () => <div data-testid="opacity-slider" />);++jest.mock('../../modules/compare/selectors', () => ({+ getCompareDates: jest.fn(),+}));++jest.mock('../../util/util', () => ({+ events: {+ trigger: jest.fn(),+ },+}));++describe('Opacity Compare Class', () => {+ let mockMap;+ let mockStore;+ let mockFirstLayer;+ let mockSecondLayer;+ let mockRoot;++ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();++ // Setup DOM+ document.body.innerHTML = '<div id="wv-map"></div>';++ // Mock createRoot returns+ mockRoot = {+ render: jest.fn(),+ unmount: jest.fn(),+ };+ createRoot.mockReturnValue(mockRoot);++ // Mock Layers+ mockFirstLayer = { setOpacity: jest.fn() };+ mockSecondLayer = { setOpacity: jest.fn() };++ // Mock Map+ mockMap = {+ getLayers: jest.fn(() => ({+ getArray: jest.fn(() => [mockFirstLayer, mockSecondLayer]),+ })),+ };++ // Mock Store+ mockStore = {+ getState: jest.fn(() => ({})),+ };++ // Mock Selectors+ getCompareDates.mockReturnValue({ dateA: '2023-01-01', dateB: '2023-01-02' });+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('initializes correctly and sets initial layer opacities', () => {+ const opacityInstance = new Opacity(mockMap, mockStore, {}, 75);++ expect(createRoot).toHaveBeenCalledWith(opacityInstance.sliderCase);+ expect(getCompareDates).toHaveBeenCalled();+ expect(opacityInstance.dateA).toBe('2023-01-01');+ expect(opacityInstance.dateB).toBe('2023-01-02');++ // oninput is called during create+ expect(mockFirstLayer.setOpacity).toHaveBeenCalledWith(0.25); // 1 - 0.75+ expect(mockSecondLayer.setOpacity).toHaveBeenCalledWith(0.75);+ expect(util.events.trigger).toHaveBeenCalledWith(COMPARE_MOVE_END, 75);+ });++ it('uses default value if valueOverride is not provided', () => {+ // eslint-disable-next-line no-unused-vars+ const opacityInstance = new Opacity(mockMap, mockStore, {});++ expect(mockFirstLayer.setOpacity).toHaveBeenCalledWith(0.25);+ expect(mockSecondLayer.setOpacity).toHaveBeenCalledWith(0.75);+ });++ it('updates dates and re-renders on update()', () => {+ const opacityInstance = new Opacity(mockMap, mockStore, {}, 50);++ getCompareDates.mockReturnValue({ dateA: '2023-02-01', dateB: '2023-02-02' });+ opacityInstance.update(mockStore);++ expect(opacityInstance.dateA).toBe('2023-02-01');+ expect(opacityInstance.dateB).toBe('2023-02-02');+ expect(mockRoot.render).toHaveBeenCalledTimes(2); // 1 for create, 1 for update+ });++ it('renders slider into the DOM map container', () => {+ const opacityInstance = new Opacity(mockMap, mockStore, {}, 50);+ const mapCase = document.getElementById('wv-map');++ expect(mapCase.contains(opacityInstance.sliderCase)).toBe(true);+ expect(mockRoot.render).toHaveBeenCalled();+ });++ it('adjusts opacities and triggers event on oninput()', () => {+ const opacityInstance = new Opacity(mockMap, mockStore, {}, 50);++ opacityInstance.oninput(30);++ expect(mockFirstLayer.setOpacity).toHaveBeenCalledWith(0.7); // 1 - 0.3+ expect(mockSecondLayer.setOpacity).toHaveBeenCalledWith(0.3);+ expect(util.events.trigger).toHaveBeenCalledWith(COMPARE_MOVE_END, 30);+ });++ it('destroys correctly and unmounts react root asynchronously', () => {+ const opacityInstance = new Opacity(mockMap, mockStore, {}, 50);+ const mapCase = document.getElementById('wv-map');++ expect(mapCase.contains(opacityInstance.sliderCase)).toBe(true);++ opacityInstance.destroy();++ // Immediate state changes+ expect(opacityInstance.isDestroyed).toBe(true);+ expect(opacityInstance.root).toBeNull();++ // Render should abort if destroyed+ opacityInstance.renderSlider([mockFirstLayer, mockSecondLayer]);+ expect(mockRoot.render).toHaveBeenCalledTimes(1); // Only the initial render from constructor++ // DOM and unmount handled in setTimeout+ jest.runAllTimers();++ expect(mockRoot.unmount).toHaveBeenCalled();+ expect(mapCase.contains(opacityInstance.sliderCase)).toBe(false);+ });++ it('prevents multiple destruction calls', () => {+ const opacityInstance = new Opacity(mockMap, mockStore, {}, 50);++ opacityInstance.destroy();+ opacityInstance.destroy(); // Second call++ jest.runAllTimers();+ expect(mockRoot.unmount).toHaveBeenCalledTimes(1);+ });});diff --git a/web/js/map/compare/spy.test.js b/web/js/map/compare/spy.test.jsindex add3e252c..e7592fa63 100644--- a/web/js/map/compare/spy.test.js+++ b/web/js/map/compare/spy.test.js@@ -1,3 +1,481 @@-test('spy map test', () => {+/* eslint-disable no-new */+import Spy from './spy';+import { getCompareDates } from '../../modules/compare/selectors';+jest.mock('ol/render', () => ({+ getRenderPixel: jest.fn((event, pixel) => pixel),+}));++jest.mock('../../modules/compare/selectors', () => ({+ getCompareDates: jest.fn(),+}));++// ─── Helpers ────────────────────────────────────────────────────────────────++const makeLayer = () => ({+ on: jest.fn(),+ un: jest.fn(),+ get: jest.fn(() => null),+});++const makeLayerGroup = (layers) => ({+ on: jest.fn(),+ un: jest.fn(),+ get: jest.fn((key) => (key === 'layers' ? { getArray: () => layers } : null)),+});++const makeMap = (layer0, layer1) => ({+ on: jest.fn(),+ un: jest.fn(),+ render: jest.fn(),+ getEventPixel: jest.fn(() => [50, 50]),+ getLayers: jest.fn(() => ({+ getArray: jest.fn(() => [layer0, layer1]),+ })),+});++const makeStore = (overrides = {}) => {+ const state = {+ compare: {+ isCompareA: true,+ ...overrides.compare,+ },+ ...overrides,+ };+ return { getState: jest.fn(() => state) };+};++// ─── Setup ──────────────────────────────────────────────────────────────────++beforeEach(() => {+ document.body.innerHTML = '<div id="wv-map"></div>';+ getCompareDates.mockReturnValue({ dateA: '2020-01-01', dateB: '2020-06-01' });+});++afterEach(() => {+ jest.clearAllMocks();+});++// ─── Constructor ────────────────────────────────────────────────────────────++describe('Spy constructor', () => {+ test('sets mapCase to the wv-map element', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ const instance = new Spy(map, store);++ expect(instance.mapCase).toBe(document.getElementById('wv-map'));+ });++ test('sets this.map to the provided olMap', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ const instance = new Spy(map, store);++ expect(instance.map).toBe(map);+ });++ test('sets isBInside from state.compare.isCompareA', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore({ compare: { isCompareA: false } });++ const instance = new Spy(map, store);++ expect(instance.isBInside).toBe(false);+ });++ test('calls create() during construction', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ const createSpy = jest.spyOn(Spy.prototype, 'create');+ new Spy(map, store);++ expect(createSpy).toHaveBeenCalledWith(store);+ createSpy.mockRestore();+ });+});++// ─── addSpy ─────────────────────────────────────────────────────────────────++describe('addSpy', () => {+ test('appends a label span to the mapCase', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ new Spy(map, store);++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label).not.toBeNull();+ });++ test('label is initially hidden', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ new Spy(map, store);++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.style.display).toBe('none');+ });++ test('registers mousemove listener on mapCase', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const addEventSpy = jest.spyOn(HTMLElement.prototype, 'addEventListener');++ new Spy(map, store);++ const mousemoveCalls = addEventSpy.mock.calls.filter(([event]) => event === 'mousemove');+ expect(mousemoveCalls.length).toBeGreaterThan(0);+ addEventSpy.mockRestore();+ });++ test('registers mouseleave listener on mapCase', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const addEventSpy = jest.spyOn(HTMLElement.prototype, 'addEventListener');++ new Spy(map, store);++ const mouseleaveCalls = addEventSpy.mock.calls.filter(([event]) => event === 'mouseleave');+ expect(mouseleaveCalls.length).toBeGreaterThan(0);+ addEventSpy.mockRestore();+ });++ test('registers mouseenter listener on mapCase', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const addEventSpy = jest.spyOn(HTMLElement.prototype, 'addEventListener');++ new Spy(map, store);++ const mouseenterCalls = addEventSpy.mock.calls.filter(([event]) => event === 'mouseenter');+ expect(mouseenterCalls.length).toBeGreaterThan(0);+ addEventSpy.mockRestore();+ });++ test('registers pointerdrag listener on map', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ new Spy(map, store);++ expect(map.on).toHaveBeenCalledWith('pointerdrag', expect.any(Function));+ });++ test('label innerHTML reflects isCompareA=true (shows B)', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore({ compare: { isCompareA: true } });++ new Spy(map, store);++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.innerHTML).toContain('B');+ });++ test('label innerHTML reflects isCompareA=false (shows A)', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore({ compare: { isCompareA: false } });++ new Spy(map, store);++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.innerHTML).toContain('A');+ });+});++// ─── updateSpy ──────────────────────────────────────────────────────────────++describe('updateSpy', () => {+ test('updates label position and calls map.render when pixel is provided', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ map.render.mockClear();+ instance.updateSpy({ pixel: [100, 200] });++ expect(map.render).toHaveBeenCalled();+ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.style.top).not.toBe('');+ expect(label.style.left).not.toBe('');+ });++ test('falls back to map.getEventPixel when pixel is not provided', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ map.render.mockClear();+ instance.updateSpy({});++ expect(map.getEventPixel).toHaveBeenCalled();+ expect(map.render).toHaveBeenCalled();+ });++ test('label top is calculated correctly from pixel', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ instance.updateSpy({ pixel: [100, 200] });++ const DEFAULT_RADIUS = 140;+ const offSetXandY = Math.sqrt((DEFAULT_RADIUS * DEFAULT_RADIUS) / 2);+ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.style.top).toBe(`${200 + offSetXandY - 10}px`);+ });++ test('label left is calculated correctly from pixel', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ instance.updateSpy({ pixel: [100, 200] });++ const DEFAULT_RADIUS = 140;+ const offSetXandY = Math.sqrt((DEFAULT_RADIUS * DEFAULT_RADIUS) / 2);+ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.style.left).toBe(`${100 + offSetXandY - 5}px`);+ });+});++// ─── hideSpy ────────────────────────────────────────────────────────────────++describe('hideSpy', () => {+ test('hides label and calls map.render', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ map.render.mockClear();+ instance.hideSpy({});++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.style.display).toBe('none');+ expect(map.render).toHaveBeenCalled();+ });+});++// ─── showSpy ────────────────────────────────────────────────────────────────++describe('showSpy', () => {+ test('shows label and calls map.render', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ instance.hideSpy({});+ map.render.mockClear();+ instance.showSpy();++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.style.display).toBe('block');+ expect(map.render).toHaveBeenCalled();+ });+});++// ─── update ─────────────────────────────────────────────────────────────────++describe('update', () => {+ test('updates label innerHTML when dateA changes', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ getCompareDates.mockReturnValue({ dateA: '2021-01-01', dateB: '2020-06-01' });+ instance.update(store);++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.innerHTML).toContain('2020-06-01');+ });++ test('updates label innerHTML when dateB changes', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ getCompareDates.mockReturnValue({ dateA: '2020-01-01', dateB: '2021-12-01' });+ instance.update(store);++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label.innerHTML).toContain('2021-12-01');+ });++ test('updates label innerHTML when dates are the same', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ getCompareDates.mockReturnValue({ dateA: '2020-01-01', dateB: '2020-01-01' });+ new Spy(map, store);++ const label = document.querySelector('.ab-spy-span.inside-label');+ // same date means no date text appended+ expect(label.innerHTML).not.toContain('monospace');+ });++ test('applies layer listeners during update', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();++ new Spy(map, store);++ expect(layer0.on).toHaveBeenCalled();+ expect(layer1.on).toHaveBeenCalled();+ });++ test('calls destroy and create when isBInside changes', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore({ compare: { isCompareA: true } });+ const instance = new Spy(map, store);++ const destroySpy = jest.spyOn(instance, 'destroy');+ const createSpy = jest.spyOn(instance, 'create');++ // Flip isCompareA+ store.getState.mockReturnValue({+ compare: { isCompareA: false },+ });+ getCompareDates.mockReturnValue({ dateA: '2020-01-01', dateB: '2020-06-01' });++ instance.update(store);++ expect(destroySpy).toHaveBeenCalled();+ expect(createSpy).toHaveBeenCalled();+ });++ test('does not call destroy when isBInside has not changed', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore({ compare: { isCompareA: true } });+ const instance = new Spy(map, store);++ const destroySpy = jest.spyOn(instance, 'destroy');++ instance.update(store);++ expect(destroySpy).not.toHaveBeenCalled();+ });+});++// ─── destroy ────────────────────────────────────────────────────────────────++describe('destroy', () => {+ test('removes label from mapCase', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ instance.destroy();++ const label = document.querySelector('.ab-spy-span.inside-label');+ expect(label).toBeNull();+ });++ test('calls map.un to remove pointerdrag listener', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ map.un.mockClear();+ instance.destroy();++ expect(map.un).toHaveBeenCalledWith('pointerdrag', expect.any(Function));+ });++ test('removes listeners from top layers', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ instance.destroy();++ expect(layer1.un).toHaveBeenCalledWith('prerender', expect.any(Function));+ expect(layer1.un).toHaveBeenCalledWith('postrender', expect.any(Function));+ });++ test('removes listeners from bottom layers', () => {+ const layer0 = makeLayer();+ const layer1 = makeLayer();+ const map = makeMap(layer0, layer1);+ const store = makeStore();+ const instance = new Spy(map, store);++ instance.destroy();++ expect(layer0.un).toHaveBeenCalledWith('postrender', expect.any(Function));+ });+});++// ─── applyEventsToBaseLayers (via layer groups) ──────────────────────────────++describe('applyEventsToBaseLayers recursion', () => {+ test('recursively applies listeners to nested layer groups', () => {+ const leafLayer0 = makeLayer();+ const leafLayer1 = makeLayer();+ const nestedGroup = makeLayerGroup([leafLayer0]);+ const topGroup = makeLayerGroup([nestedGroup, leafLayer1]);+ const map = makeMap(topGroup, makeLayer());+ const store = makeStore();++ new Spy(map, store);++ expect(leafLayer0.on).toHaveBeenCalled();+ });});diff --git a/web/js/map/compare/swipe.test.js b/web/js/map/compare/swipe.test.jsindex e6f27beff..b4bd4996a 100644--- a/web/js/map/compare/swipe.test.js+++ b/web/js/map/compare/swipe.test.js@@ -1,3 +1,602 @@-test('swipe map test', () => {+/* eslint-disable no-new */+// swipe.test.js+import Swipe from './swipe';+import { getCompareDates } from '../../modules/compare/selectors';+import { getRenderPixel } from 'ol/render';+import util from '../../util/util';+import { COMPARE_MOVE_START } from '../../util/constants';++// ─────────────────────────────────────────────+// Mocks+// ─────────────────────────────────────────────++jest.mock('react-dom/client', () => ({+ createRoot: jest.fn(() => ({ render: jest.fn() })),+}));++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: () => null,+}));++jest.mock('lodash/round', () => jest.fn((val) => Math.round(val)));+jest.mock('lodash/each', () => jest.fn((collection, fn) => collection.forEach(fn)));++jest.mock('ol/render', () => ({+ getRenderPixel: jest.fn((event, coord) => coord),+}));++jest.mock('../../modules/compare/selectors', () => ({+ getCompareDates: jest.fn(),+}));++jest.mock('../../util/util', () => ({+ events: {+ trigger: jest.fn(),+ },+}));++jest.mock('../../util/constants', () => ({+ COMPARE_MOVE_START: 'compare:movestart',+}));++const registeredResizeListeners = [];+const originalAddEventListener = window.addEventListener.bind(window);+const originalRemoveEventListener = window.removeEventListener.bind(window);++// Override addEventListener once, before any tests run+window.addEventListener = (type, handler, ...rest) => {+ if (type === 'resize') {+ registeredResizeListeners.push(handler);+ }+ originalAddEventListener(type, handler, ...rest);+};++window.removeEventListener = (type, handler, ...rest) => {+ if (type === 'resize') {+ const idx = registeredResizeListeners.indexOf(handler);+ if (idx !== -1) registeredResizeListeners.splice(idx, 1);+ }+ originalRemoveEventListener(type, handler, ...rest);+};++// After EVERY test, purge all accumulated resize listeners+afterEach(() => {+ [...registeredResizeListeners].forEach((handler) => {+ originalRemoveEventListener('resize', handler);+ });+ registeredResizeListeners.length = 0;+});++// ─────────────────────────────────────────────+// Helpers+// ─────────────────────────────────────────────++/** Creates a mock OL layer with optional sub-layers */+const makeMockLayer = (subLayers = null) => {+ const layer = {+ on: jest.fn(),+ un: jest.fn(),+ get: jest.fn((key) => {+ if (key === 'layers' && subLayers) {+ return { getArray: () => subLayers };+ }+ return null;+ }),+ };+ return layer;+};++/** Creates a mock OL map */+const makeMockMap = (layerGroupsA = [], layerGroupsB = []) => {+ const mapEl = document.createElement('div');+ document.body.appendChild(mapEl);++ return {+ getTargetElement: jest.fn(() => mapEl),+ render: jest.fn(),+ getSize: jest.fn(() => [1000, 800]),+ getLayers: jest.fn(() => ({+ getArray: jest.fn(() => [+ { getLayersArray: jest.fn(() => layerGroupsA) },+ { getLayersArray: jest.fn(() => layerGroupsB) },+ ]),+ })),+ };+};++/** Creates a mock Redux-like store */+const makeMockStore = (dateA = '2023-01-01', dateB = '2023-06-01') => {+ getCompareDates.mockReturnValue({ dateA, dateB });+ return {+ getState: jest.fn(() => ({})),+ };+};++/** Default listener string object for mouse events */+const defaultListenerObj = {+ type: 'default',+ start: 'mousedown',+ move: 'mousemove',+ end: 'mouseup',+};++// ─────────────────────────────────────────────+// Test Suites+// ─────────────────────────────────────────────++describe('Swipe class', () => {+ let map;+ let store;+ let swipe;++ beforeEach(() => {+ jest.clearAllMocks();+ // Reset jsdom body between tests+ document.body.innerHTML = '';+ map = makeMockMap();+ store = makeMockStore();+ swipe = new Swipe(map, store, defaultListenerObj, 50);+ });++ // ── Constructor ──────────────────────────────++ describe('constructor', () => {+ it('should set percentSwipe from valueOverride / 100', () => {+ // Verify the swipe line is translated to 50% of window width+ const line = document.querySelector('.ab-swipe-line');+ expect(line).not.toBeNull();+ const expectedOffset = window.innerWidth * 0.5;+ expect(line.style.transform).toBe(`translateX( ${expectedOffset}px)`);+ });++ it('should call create() on construction', () => {+ const line = document.querySelector('.ab-swipe-line');+ expect(line).not.toBeNull();+ });++ it('should expose getSwipeOffset function', () => {+ expect(typeof swipe.getSwipeOffset).toBe('function');+ });++ it('should store a reference to the OL map', () => {+ expect(swipe.map).toBe(map);+ });++ it('should register a window resize listener', () => {+ const addEventSpy = jest.spyOn(window, 'addEventListener');+ const map2 = makeMockMap();+ const store2 = makeMockStore();+ new Swipe(map2, store2, defaultListenerObj, 50);+ const resizeCall = addEventSpy.mock.calls.find(([event]) => event === 'resize');+ expect(resizeCall).toBeDefined();+ });+ });++ // ── create() ────────────────────────────────++ describe('create()', () => {+ it('should read dates from the store via getCompareDates', () => {+ expect(getCompareDates).toHaveBeenCalled();+ expect(swipe.dateA).toBe('2023-01-01');+ expect(swipe.dateB).toBe('2023-06-01');+ });++ it('should append the swipe line element to the map container', () => {+ const mapEl = map.getTargetElement();+ expect(mapEl.querySelector('.ab-swipe-line')).not.toBeNull();+ });+ });++ // ── destroy() ───────────────────────────────++ describe('destroy()', () => {+ it('should remove the swipe line from the DOM', () => {+ swipe.destroy();+ const line = document.querySelector('.ab-swipe-line');+ expect(line).toBeNull();+ });++ it('should call layer.un() for prerender and postrender on side A layers', () => {+ const layerA = makeMockLayer();+ const layerB = makeMockLayer();+ const mapWithLayers = makeMockMap([layerA], [layerB]);+ const storeWithLayers = makeMockStore();+ const swipeWithLayers = new Swipe(mapWithLayers, storeWithLayers, defaultListenerObj, 50);++ swipeWithLayers.update(storeWithLayers);+ swipeWithLayers.destroy();++ expect(layerA.un).toHaveBeenCalledWith('prerender', expect.any(Function));+ expect(layerA.un).toHaveBeenCalledWith('postrender', expect.any(Function));+ });++ it('should call layer.un() for prerender and postrender on side B layers', () => {+ const layerA = makeMockLayer();+ const layerB = makeMockLayer();+ const mapWithLayers = makeMockMap([layerA], [layerB]);+ const storeWithLayers = makeMockStore();+ const swipeWithLayers = new Swipe(mapWithLayers, storeWithLayers, defaultListenerObj, 50);++ swipeWithLayers.update(storeWithLayers);+ swipeWithLayers.destroy();++ expect(layerB.un).toHaveBeenCalledWith('prerender', expect.any(Function));+ expect(layerB.un).toHaveBeenCalledWith('postrender', expect.any(Function));+ });++ it('should reset layersSideA and layersSideB to empty arrays after destroy', () => {+ // After destroy, a subsequent update should not attempt to un-register+ // old layers (no error thrown)+ expect(() => swipe.destroy()).not.toThrow();+ });+ });++ // ── update() ────────────────────────────────++ describe('update()', () => {+ it('should apply event listeners to side A and B layers when dates are unchanged', () => {+ const layerA = makeMockLayer();+ const layerB = makeMockLayer();+ const mapWithLayers = makeMockMap([layerA], [layerB]);+ const storeWithLayers = makeMockStore('2023-01-01', '2023-06-01');+ const swipeWithLayers = new Swipe(mapWithLayers, storeWithLayers, defaultListenerObj, 50);++ swipeWithLayers.update(storeWithLayers);++ expect(layerA.on).toHaveBeenCalledWith('prerender', expect.any(Function));+ expect(layerA.on).toHaveBeenCalledWith('postrender', expect.any(Function));+ expect(layerB.on).toHaveBeenCalledWith('prerender', expect.any(Function));+ expect(layerB.on).toHaveBeenCalledWith('postrender', expect.any(Function));+ });++ it('should call destroy() and create() when dates change', () => {+ const destroySpy = jest.spyOn(swipe, 'destroy');+ const createSpy = jest.spyOn(swipe, 'create');++ // Simulate new dates+ getCompareDates.mockReturnValue({ dateA: '2024-01-01', dateB: '2024-06-01' });+ swipe.update(store);++ expect(destroySpy).toHaveBeenCalledTimes(1);+ expect(createSpy).toHaveBeenCalledTimes(1);+ });++ it('should not call destroy() when dates are unchanged', () => {+ const destroySpy = jest.spyOn(swipe, 'destroy');++ // Same dates as initial+ getCompareDates.mockReturnValue({ dateA: '2023-01-01', dateB: '2023-06-01' });+ swipe.update(store);++ expect(destroySpy).not.toHaveBeenCalled();+ });+ });++ // ── applyEventListeners() ───────────────────++ describe('applyEventListeners()', () => {+ it('should call callback directly for a flat (non-group) layer', () => {+ const layer = makeMockLayer();+ const callback = jest.fn();+ swipe.applyEventListeners(layer, callback);+ expect(callback).toHaveBeenCalledWith(layer);+ });++ it('should recurse into sub-layers for a layer group', () => {+ const subLayer = makeMockLayer();+ const groupLayer = makeMockLayer([subLayer]);+ const callback = jest.fn();++ swipe.applyEventListeners(groupLayer, callback);++ // callback should be applied to the leaf sub-layer, not the group+ expect(callback).toHaveBeenCalledWith(subLayer);+ expect(callback).not.toHaveBeenCalledWith(groupLayer);+ });++ it('should handle deeply nested layer groups', () => {+ const deepLeaf = makeMockLayer();+ const midLayer = makeMockLayer([deepLeaf]);+ const topGroup = makeMockLayer([midLayer]);+ const callback = jest.fn();++ swipe.applyEventListeners(topGroup, callback);++ expect(callback).toHaveBeenCalledWith(deepLeaf);+ expect(callback).toHaveBeenCalledTimes(1);+ });+ });++ // ── setClipMaskA() ──────────────────────────++ describe('setClipMaskA()', () => {+ it('should call context.save(), beginPath(), and clip()', () => {+ const ctx = {+ save: jest.fn(),+ beginPath: jest.fn(),+ moveTo: jest.fn(),+ lineTo: jest.fn(),+ closePath: jest.fn(),+ clip: jest.fn(),+ restore: jest.fn(),+ };+ const event = { context: ctx };+ swipe.setClipMaskA(event);++ expect(ctx.save).toHaveBeenCalled();+ expect(ctx.beginPath).toHaveBeenCalled();+ expect(ctx.clip).toHaveBeenCalled();+ });++ it('should call getRenderPixel with the correct map size coordinates', () => {+ const ctx = {+ save: jest.fn(),+ beginPath: jest.fn(),+ moveTo: jest.fn(),+ lineTo: jest.fn(),+ closePath: jest.fn(),+ clip: jest.fn(),+ };+ const event = { context: ctx };+ swipe.setClipMaskA(event);++ // percentSwipe = 50/100 = 0.5, mapSize = [1000, 800] → widthSideA = 500+ expect(getRenderPixel).toHaveBeenCalledWith(event, [0, 0]);+ expect(getRenderPixel).toHaveBeenCalledWith(event, [0, 800]);+ expect(getRenderPixel).toHaveBeenCalledWith(event, [500, 800]);+ expect(getRenderPixel).toHaveBeenCalledWith(event, [500, 0]);+ });+ });++ // ── setClipMaskB() ──────────────────────────++ describe('setClipMaskB()', () => {+ it('should call context.save(), beginPath(), and clip()', () => {+ const ctx = {+ save: jest.fn(),+ beginPath: jest.fn(),+ moveTo: jest.fn(),+ lineTo: jest.fn(),+ closePath: jest.fn(),+ clip: jest.fn(),+ };+ const event = { context: ctx };+ swipe.setClipMaskB(event);++ expect(ctx.save).toHaveBeenCalled();+ expect(ctx.beginPath).toHaveBeenCalled();+ expect(ctx.clip).toHaveBeenCalled();+ });++ it('should call getRenderPixel with the correct side B coordinates', () => {+ const ctx = {+ save: jest.fn(),+ beginPath: jest.fn(),+ moveTo: jest.fn(),+ lineTo: jest.fn(),+ closePath: jest.fn(),+ clip: jest.fn(),+ };+ const event = { context: ctx };+ swipe.setClipMaskB(event);++ // widthSideB = 1000 * 0.5 = 500, mapSize = [1000, 800]+ expect(getRenderPixel).toHaveBeenCalledWith(event, [500, 0]);+ expect(getRenderPixel).toHaveBeenCalledWith(event, [500, 800]);+ expect(getRenderPixel).toHaveBeenCalledWith(event, [1000, 800]);+ expect(getRenderPixel).toHaveBeenCalledWith(event, [1000, 0]);+ });+ });+});++// ─────────────────────────────────────────────+// addLineOverlay / DOM structure tests+// ─────────────────────────────────────────────++describe('addLineOverlay DOM structure', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ document.body.innerHTML = '';+ });++ const buildSwipe = (dateA, dateB, valueOverride = 50) => {+ const map = makeMockMap();+ const store = makeMockStore(dateA, dateB);+ return { swipe: new Swipe(map, store, defaultListenerObj, valueOverride), map };+ };++ it('should render an element with class "ab-swipe-line"', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ expect(document.querySelector('.ab-swipe-line')).not.toBeNull();+ });++ it('should render the left label with text "A"', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ const leftLabel = document.querySelector('.left-label');+ expect(leftLabel.textContent).toContain('A');+ });++ it('should render the right label with text "B"', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ const rightLabel = document.querySelector('.right-label');+ expect(rightLabel.textContent).toContain('B');+ });++ it('should show date labels with "show-date-label" class when dates differ', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ const leftLabel = document.querySelector('.left-label');+ const rightLabel = document.querySelector('.right-label');+ expect(leftLabel.classList).toContain('show-date-label');+ expect(rightLabel.classList).toContain('show-date-label');+ });++ it('should include dateA text in the left label when dates differ', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ const leftLabel = document.querySelector('.left-label');+ expect(leftLabel.textContent).toContain('2023-01-01');+ });++ it('should include dateB text in the right label when dates differ', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ const rightLabel = document.querySelector('.right-label');+ expect(rightLabel.textContent).toContain('2023-06-01');+ });++ it('should NOT add "show-date-label" class when dates are the same', () => {+ buildSwipe('2023-01-01', '2023-01-01');+ const leftLabel = document.querySelector('.left-label');+ const rightLabel = document.querySelector('.right-label');+ expect(leftLabel.classList).not.toContain('show-date-label');+ expect(rightLabel.classList).not.toContain('show-date-label');+ });++ it('should render an element with class "ab-swipe-dragger"', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ expect(document.querySelector('.ab-swipe-dragger')).not.toBeNull();+ });++ it('should render an element with class "swipe-dragger-circle"', () => {+ buildSwipe('2023-01-01', '2023-06-01');+ expect(document.querySelector('.swipe-dragger-circle')).not.toBeNull();+ });++ it('should set initial translateX to 50% of window.innerWidth when valueOverride is 50', () => {+ buildSwipe('2023-01-01', '2023-06-01', 50);+ const line = document.querySelector('.ab-swipe-line');+ const expectedOffset = window.innerWidth * 0.5;+ expect(line.style.transform).toBe(`translateX( ${expectedOffset}px)`);+ });++ it('should set initial translateX to 25% of window.innerWidth when valueOverride is 25', () => {+ buildSwipe('2023-01-01', '2023-06-01', 25);+ const line = document.querySelector('.ab-swipe-line');+ const expectedOffset = window.innerWidth * 0.25;+ expect(line.style.transform).toBe(`translateX( ${expectedOffset}px)`);+ });+});++// ─────────────────────────────────────────────+// dragLine / mouse & touch interaction tests+// ─────────────────────────────────────────────++describe('dragLine interactions', () => {+ let map;+ let line;++ beforeEach(() => {+ jest.clearAllMocks();+ document.body.innerHTML = '';+ map = makeMockMap();+ const store = makeMockStore();+ new Swipe(map, store, defaultListenerObj, 50);+ line = document.querySelector('.ab-swipe-line');++ window.dispatchEvent(new MouseEvent('mouseup'));+ });++ it('should add mousemove listener to window on mousedown', () => {+ const addEventSpy = jest.spyOn(window, 'addEventListener');+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ const moveCall = addEventSpy.mock.calls.find(([event]) => event === 'mousemove');+ expect(moveCall).toBeDefined();+ });++ it('should add mouseup listener to window on mousedown', () => {+ const addEventSpy = jest.spyOn(window, 'addEventListener');+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ const endCall = addEventSpy.mock.calls.find(([event]) => event === 'mouseup');+ expect(endCall).toBeDefined();+ });++ it('should add touchmove listener to window on touchstart', () => {+ const addEventSpy = jest.spyOn(window, 'addEventListener');+ line.dispatchEvent(new TouchEvent('touchstart', { bubbles: true }));+ const moveCall = addEventSpy.mock.calls.find(([event]) => event === 'touchmove');+ expect(moveCall).toBeDefined();+ });++ it('should trigger COMPARE_MOVE_START on first mousemove', () => {+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ window.dispatchEvent(new MouseEvent('mousemove', { clientX: 400 }));+ expect(util.events.trigger).toHaveBeenCalledWith(COMPARE_MOVE_START);+ });++ it('should trigger COMPARE_MOVE_START only once during a single drag', () => {+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));++ window.dispatchEvent(new MouseEvent('mousemove', { clientX: 400 }));+ window.dispatchEvent(new MouseEvent('mousemove', { clientX: 500 }));+ window.dispatchEvent(new MouseEvent('mouseup'));++ const moveStartCalls = util.events.trigger.mock.calls.filter(+ ([evt]) => evt === COMPARE_MOVE_START,+ );+ expect(moveStartCalls).toHaveLength(1);+ });++ it('should clamp swipe offset to SWIPE_PADDING (30) when dragged to x=0', () => {+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ window.dispatchEvent(new MouseEvent('mousemove', { clientX: 0 }));+ const updatedLine = document.querySelector('.ab-swipe-line');+ expect(updatedLine.style.transform).toBe('translateX( 30px)');+ });++ it('should clamp swipe offset to (windowWidth - SWIPE_PADDING) when dragged beyond right edge', () => {+ const windowWidth = window.innerWidth;+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ window.dispatchEvent(new MouseEvent('mousemove', { clientX: windowWidth + 100 }));+ const updatedLine = document.querySelector('.ab-swipe-line');+ expect(updatedLine.style.transform).toBe(`translateX( ${windowWidth - 30}px)`);+ });++ it('should call map.render() on mousemove', () => {+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ window.dispatchEvent(new MouseEvent('mousemove', { clientX: 400 }));+ expect(map.render).toHaveBeenCalled();+ });++ it('should trigger compare:moveend on mouseup', () => {+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ window.dispatchEvent(new MouseEvent('mousemove', { clientX: 400 }));+ window.dispatchEvent(new MouseEvent('mouseup'));+ expect(util.events.trigger).toHaveBeenCalledWith('compare:moveend', expect.any(Number));+ });++ it('should remove mousemove and mouseup listeners from window after mouseup', () => {+ const removeEventSpy = jest.spyOn(window, 'removeEventListener');+ line.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ window.dispatchEvent(new MouseEvent('mouseup'));+ expect(removeEventSpy).toHaveBeenCalledWith('mousemove', expect.any(Function));+ expect(removeEventSpy).toHaveBeenCalledWith('mouseup', expect.any(Function));+ });+});++// ─────────────────────────────────────────────+// Window resize tests+// ─────────────────────────────────────────────++describe('window resize handler', () => {+ it('should rebuild the swipe line in the DOM when resized', () => {+ document.body.innerHTML = '';+ const map = makeMockMap();+ const store = makeMockStore();+ new Swipe(map, store, defaultListenerObj, 50);++ expect(document.querySelector('.ab-swipe-line')).not.toBeNull();+ window.dispatchEvent(new Event('resize'));+ expect(document.querySelector('.ab-swipe-line')).not.toBeNull();+ });++ it('should NOT rebuild the swipe line if it was already removed before resize', () => {+ document.body.innerHTML = '';+ const map = makeMockMap();+ const store = makeMockStore();+ const swipe = new Swipe(map, store, defaultListenerObj, 50);++ swipe.destroy();+ expect(document.querySelector('.ab-swipe-line')).toBeNull();+ window.dispatchEvent(new Event('resize'));+ expect(document.querySelector('.ab-swipe-line')).toBeNull();+ });});diff --git a/web/js/map/granule/granule-layer-builder.test.js b/web/js/map/granule/granule-layer-builder.test.jsindex b93d4730e..3b20e38ef 100644--- a/web/js/map/granule/granule-layer-builder.test.js+++ b/web/js/map/granule/granule-layer-builder.test.js@@ -3,13 +3,19 @@ import { thunk } from 'redux-thunk';import fixtures from '../../fixtures';import layerbuilder from '../layerbuilder';import granuleLayerBuilder from './granule-layer-builder';-// import { LOADING_START, LOADING_STOP } from '../../modules/loading/constants';-// import { LOADING_GRANULES } from '../../modules/loading/actions';-// import { ADD_GRANULE_LAYER_DATES } from '../../modules/layers/constants';+import { LOADING_START, LOADING_STOP } from '../../modules/loading/constants';+import { LOADING_GRANULES } from '../../modules/loading/actions';const mockBaseCmrApi = 'mock.cmr.api/';-const queryString = '?bounding_box=-180%2C-65%2C180%2C65&shortName=VJ102IMG&day_night_flag=day&temporal=2019-09-23T20%3A54%3A00.000Z%2C2019-09-24T12%3A54%3A00.000Z&pageSize=500';-const queryString2 = '?bounding_box=-180%2C-65%2C180%2C65&shortName=VJ102IMG_NRT&day_night_flag=day&temporal=2019-09-23T20%3A54%3A00.000Z%2C2019-09-24T12%3A54%3A00.000Z&pageSize=500';++const queryString =+ '?bounding_box=-180%2C-65%2C180%2C65&shortName=VJ102IMG&day_night_flag=day' ++ '&temporal=2019-09-23T20%3A54%3A00.000Z%2C2019-09-24T12%3A54%3A00.000Z&pageSize=500';++const queryString2 =+ '?bounding_box=-180%2C-65%2C180%2C65&shortName=VJ102IMG_NRT&day_night_flag=day' ++ '&temporal=2019-09-23T20%3A54%3A00.000Z%2C2019-09-24T12%3A54%3A00.000Z&pageSize=500';+const cmrGranules = require('../../../mock/cmr_granules.json');const mockStore = configureMockStore([thunk]);@@ -17,21 +23,45 @@ const config = fixtures.config();const { cache } = fixtures;const granuleLayerDef = config.layers['granule-cr'];+const IN_RANGE_DATE = new Date(Date.UTC(2019, 8, 24, 8, 54, 0));+const OUT_OF_RANGE_DATE = new Date(Date.UTC(2016, 8, 24, 8, 54, 0));+let createGranuleLayer;let store;-// const expectedDates = [-// '2019-09-23T23:12:00Z',-// '2019-09-23T23:18:00Z',-// '2019-09-23T23:24:00Z',-// '2019-09-23T23:30:00Z',-// '2019-09-23T23:54:00Z',-// '2019-09-24T00:00:00Z',-// '2019-09-24T00:06:00Z',-// '2019-09-24T00:12:00Z',-// '2019-09-24T00:18:00Z',-// '2019-09-24T00:48:00Z',-// ];+function buildOptionsAndAttributes(date, overrides = {}) {+ const options = { group: 'active', date, ...overrides };+ const attributes = { ...options, def: granuleLayerDef };+ return { options, attributes };+}++function mockSuccessfulCmrFetch() {+ fetch.mockResponse((req) => {+ if (+ req.url === `${mockBaseCmrApi}granules.json${queryString}` ||+ req.url === `${mockBaseCmrApi}granules.json${queryString2}`+ ) {+ return Promise.resolve({ status: 200, body: cmrGranules });+ }+ return Promise.resolve({+ status: 404,+ body: JSON.stringify({ error: 'Not found' }),+ });+ });+}++function mockFailingCmrFetch() {+ fetch.mockReject(new Error('Network failure'));+}++function mockEmptyCmrFetch() {+ fetch.mockResponse(() =>+ Promise.resolve({+ status: 200,+ body: JSON.stringify({ feed: { entry: [] } }),+ }),+ );+}describe('granule layer builder', () => {beforeEach(() => {@@ -40,72 +70,370 @@ describe('granule layer builder', () => {const { getGranuleLayer } = granuleLayerBuilder(cache, store, createLayerWMTS);createGranuleLayer = getGranuleLayer;fetch.resetMocks();- fetch.mockResponse((req) => {- if (req.url === `${mockBaseCmrApi}granules.json${queryString}` || req.url === `${mockBaseCmrApi}granules.json${queryString2}`) {- return Promise.resolve({- status: 200,- body: cmrGranules,- });+ mockSuccessfulCmrFetch();+ });++ describe('date range guard', () => {+ it('returns an empty layer group and dispatches no actions when the date is outside the layer date range', async () => {+ const { options, attributes } = buildOptionsAndAttributes(OUT_OF_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(store.getActions().length).toEqual(0);+ expect(granuleLayer).toBeDefined();+ expect(granuleLayer.wv).toBeDefined();+ expect(granuleLayer.wv.date).toEqual(OUT_OF_RANGE_DATE);+ });++ it('proceeds past the date guard and dispatches loading actions when the date is in range', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ await createGranuleLayer(granuleLayerDef, attributes, options);++ const types = store.getActions().map((a) => a.type);+ expect(types).toContain(LOADING_START);+ expect(types).toContain(LOADING_STOP);+ });+ });++ describe('layer properties', () => {+ it('sets granuleGroup flag and layerId on the returned layer', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer.get('granuleGroup')).toBe(true);+ expect(granuleLayer.get('layerId')).toBe(`${granuleLayerDef.id}-${options.group}`);+ });++ it('attaches wv.visibleGranules and wv.invisibleGranules arrays to the layer', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(Array.isArray(granuleLayer.wv.visibleGranules)).toBe(true);+ expect(Array.isArray(granuleLayer.wv.invisibleGranules)).toBe(true);+ });++ it('attaches wv.granuleDates array that is the union of visible and invisible dates', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);+ const { visibleGranules, invisibleGranules, granuleDates } = granuleLayer.wv;++ const expectedDates = [+ ...visibleGranules.map((g) => g.date),+ ...invisibleGranules.map((g) => g.date),+ ];+ expect(granuleDates).toEqual(expectedDates);+ });+ });++ describe('pendingCmrRebuild and cmrRebuildAttempts', () => {+ it('sets pendingCmrRebuild=true and increments cmrRebuildAttempts when no visible granules are returned', async () => {+ mockEmptyCmrFetch();+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer.wv.pendingCmrRebuild).toBe(true);+ expect(granuleLayer.wv.cmrRebuildAttempts).toBe(1);+ });++ it('accumulates cmrRebuildAttempts across successive empty responses', async () => {+ mockEmptyCmrFetch();+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE, {+ cmrRebuildAttempts: 3,+ });++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer.wv.cmrRebuildAttempts).toBe(4);+ });++ it('sets pendingCmrRebuild=false and does not increment cmrRebuildAttempts when visible granules exist', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ if (granuleLayer.wv.visibleGranules.length > 0) {+ expect(granuleLayer.wv.pendingCmrRebuild).toBe(false);+ expect(granuleLayer.wv.cmrRebuildAttempts).toBe(0);}- return Promise.resolve({- status: 404,- body: JSON.stringify({ error: 'Not found' }),+ });+ });++ describe('shiftadjacentdays', () => {+ it('creates the layer when shiftadjacentdays is true (default)', async () => {+ const defWithShift = { ...granuleLayerDef, shiftadjacentdays: true };+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(defWithShift, attributes, options);++ expect(granuleLayer.get('granuleGroup')).toBe(true);+ });++ it('creates the layer when shiftadjacentdays is explicitly false', async () => {+ const defWithoutShift = { ...granuleLayerDef, shiftadjacentdays: false };+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(defWithoutShift, attributes, options);++ expect(granuleLayer.get('granuleGroup')).toBe(true);+ });++ it('defaults shiftadjacentdays to true when the property is absent', async () => {+ const defNoShiftProp = { ...granuleLayerDef };+ delete defNoShiftProp.shiftadjacentdays;+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ await expect(+ createGranuleLayer(defNoShiftProp, attributes, options),+ ).resolves.toBeDefined();+ });+ });++ describe('animation isPlaying guard', () => {+ it('dispatches updateGranuleLayerState when animation is NOT playing', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ await createGranuleLayer(granuleLayerDef, attributes, options);++ const types = store.getActions().map((a) => a.type);+ expect(types).toContain('LAYERS/ADD_GRANULE_LAYER_DATES');+ });++ it('does NOT dispatch updateGranuleLayerState when animation IS playing', async () => {+ const playingState = {+ ...fixtures.getState(),+ animation: { ...fixtures.getState().animation, isPlaying: true },+ };+ store = mockStore(playingState);+ const { createLayerWMTS } = layerbuilder(config, cache, store);+ const { getGranuleLayer } = granuleLayerBuilder(cache, store, createLayerWMTS);+ createGranuleLayer = getGranuleLayer;++ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);+ await createGranuleLayer(granuleLayerDef, attributes, options);++ const types = store.getActions().map((a) => a.type);+ expect(types).not.toContain('LAYERS/ADD_GRANULE_LAYER_DATES');+ });+ });++ describe('loading spinner lifecycle', () => {+ it('dispatches LOADING_START then LOADING_STOP in the correct order', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ await createGranuleLayer(granuleLayerDef, attributes, options);++ const actions = store.getActions();+ const startIndex = actions.findIndex(+ (a) => a.type === LOADING_START && a.key === LOADING_GRANULES,+ );+ const stopIndex = actions.findIndex(+ (a) => a.type === LOADING_STOP && a.key === LOADING_GRANULES,+ );++ expect(startIndex).toBeGreaterThanOrEqual(0);+ expect(stopIndex).toBeGreaterThan(startIndex);+ });++ it('still dispatches LOADING_STOP even when the CMR fetch throws', async () => {+ mockFailingCmrFetch();+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ const types = store.getActions().map((a) => a.type);+ expect(types).toContain(LOADING_STOP);+ expect(granuleLayer).toBeDefined();+ });+ });++ describe('CMR error dialog', () => {+ it('dispatches loading start and stop and returns empty granule dates when the CMR request fails', async () => {+ mockFailingCmrFetch();+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ await createGranuleLayer(granuleLayerDef, attributes, options);++ const actions = store.getActions();+ const types = actions.map((a) => a.type);+ expect(types).toContain('LOADING/START');+ expect(types).toContain('LOADING/STOP');++ const granuleDatesAction = actions.find((a) => a.type === 'LAYERS/ADD_GRANULE_LAYER_DATES');+ expect(granuleDatesAction).toBeDefined();+ expect(granuleDatesAction.dates).toEqual([]);+ });++ it('does NOT dispatch the CMR error modal on a successful fetch', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ await createGranuleLayer(granuleLayerDef, attributes, options);++ const actions = store.getActions();+ const modalAction = actions.find((a) => a.type === 'MODAL/OPEN_BASIC_CONTENT');+ expect(modalAction).toBeUndefined();+ });+ });++ describe('granule deduplication', () => {+ it('removes duplicate granules that share the same time_start across standard and NRT feeds', async () => {+ const sharedEntry = cmrGranules.feed.entry[0];+ const duplicateFeed = JSON.stringify({ feed: { entry: [sharedEntry] } });+ fetch.mockResponse((req) => {+ if (req.url.includes('VJ102IMG') || req.url.includes('VJ102IMG_NRT')) {+ return Promise.resolve({ status: 200, body: duplicateFeed });+ }+ return Promise.resolve({ status: 404, body: '{}' });});++ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);+ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ const allDates = granuleLayer.wv.granuleDates;+ const uniqueDates = [...new Set(allDates)];+ expect(allDates.length).toEqual(uniqueDates.length);});});- // TODO: fix fetchMock in jest v28+- // it('dispatches expected actions', async () => {- // const options = {- // group: 'active',- // date: new Date(Date.UTC('2019', '08', '24', '08', '54', '00')),- // };- // const attributes = {- // ...options,- // def: granuleLayerDef,- // };- // await createGranuleLayer(granuleLayerDef, attributes, options);- // const [firstAction, secondAction, thirdAction] = store.getActions();-- // expect(firstAction.type).toEqual(LOADING_START);- // expect(firstAction.key).toEqual(LOADING_GRANULES);- // expect(secondAction.type).toEqual(LOADING_STOP);- // expect(secondAction.key).toEqual(LOADING_GRANULES);- // expect(thirdAction.type).toEqual(ADD_GRANULE_LAYER_DATES);- // expect(thirdAction.dates).toEqual(expectedDates);- // expect(Object.keys(thirdAction.granuleFootprints)).toEqual(expectedDates);- // expect(thirdAction.count).toEqual(thirdAction.dates.length);- // });-- it('doesnt query cmr when date falls outside range', async () => {- const options = {- group: 'active',- date: new Date(Date.UTC('2016', '08', '24', '08', '54', '00')),- };- const attributes = {- ...options,- def: granuleLayerDef,- };- await createGranuleLayer(granuleLayerDef, attributes, options);- const actions = store.getActions();- expect(actions.length).toEqual(0);- });-- // TODO: fix fetchMock in jest v28+- // it('sets expected layer properties', async () => {- // const options = {- // group: 'active',- // date: new Date(Date.UTC('2019', '08', '24', '08', '54', '00')),- // };- // const attributes = {- // ...options,- // def: granuleLayerDef,- // };- // const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);- // const filteredDates = granuleLayer.wv.visibleGranules.map(({ date }) => date);-- // expect(granuleLayer.get('granuleGroup')).toEqual(true);- // expect(granuleLayer.wv.granuleDates).toEqual(expectedDates);- // expect(filteredDates).toEqual(expectedDates);- // });+ describe('tile layer caching', () => {+ it('reuses cached tile layers on repeated calls for the same date', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const firstLayer = await createGranuleLayer(granuleLayerDef, attributes, options);+ store.clearActions();+ const secondLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(firstLayer.get('granuleGroup')).toBe(true);+ expect(secondLayer.get('granuleGroup')).toBe(true);+ expect(firstLayer.wv.visibleGranules.length).toEqual(secondLayer.wv.visibleGranules.length);+ });+ });++ describe('getVisibleGranules edge cases', () => {+ it('returns empty granule lists when CMR provides no entries', async () => {+ mockEmptyCmrFetch();+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer.wv.visibleGranules.length).toBe(0);+ expect(granuleLayer.wv.invisibleGranules.length).toBe(0);+ });++ it('returns empty granule lists when granuleCount is high but CMR returns no data', async () => {+ const highCountDef = { ...granuleLayerDef, count: 9999 };+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(highCountDef, attributes, options);++ expect(granuleLayer.wv.visibleGranules.length).toBe(0);+ expect(granuleLayer.wv.invisibleGranules.length).toBe(0);+ expect(granuleLayer.wv.count).toBe(9999);+ });+ });++ describe('granuleDateRanges cache bypass', () => {+ it('uses pre-existing granuleDateRanges when they already cover the selected date', async () => {+ const coveredDef = {+ ...granuleLayerDef,+ granuleDateRanges: [['2019-01-01T00:00:00Z', '2020-01-01T00:00:00Z']],+ };+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(coveredDef, attributes, options);++ expect(granuleLayer.get('granuleGroup')).toBe(true);+ });++ it('fetches granuleDateRanges when none are provided on the layer definition', async () => {+ const defWithoutRanges = { ...granuleLayerDef };+ delete defWithoutRanges.granuleDateRanges;+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ await expect(+ createGranuleLayer(defWithoutRanges, attributes, options),+ ).resolves.toBeDefined();+ });+ });++ describe('layer extent based on CRS', () => {+ it('sets the full map extent for the geographic projection', async () => {+ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);++ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer.getExtent()).toBeDefined();+ });++ it('sets the projection maxExtent for a non-geographic (polar) projection', async () => {+ const arcticState = {+ ...fixtures.getState(),+ proj: {+ selected: {+ crs: 'EPSG:3413',+ maxExtent: [-4194304, -4194304, 4194304, 4194304],+ },+ },+ };+ store = mockStore(arcticState);+ const { createLayerWMTS } = layerbuilder(config, cache, store);+ const { getGranuleLayer } = granuleLayerBuilder(cache, store, createLayerWMTS);+ createGranuleLayer = getGranuleLayer;+ fetch.resetMocks();+ mockSuccessfulCmrFetch();++ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);+ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer.getExtent()).toEqual([-4194304, -4194304, 4194304, 4194304]);+ });+ });++ describe('partial CMR responses', () => {+ it('builds the layer from NRT data alone when the standard CMR request rejects', async () => {+ fetch.mockResponse((req) => {+ if (req.url === `${mockBaseCmrApi}granules.json${queryString}`) {+ return Promise.reject(new Error('Standard CMR unavailable'));+ }+ if (req.url === `${mockBaseCmrApi}granules.json${queryString2}`) {+ return Promise.resolve({ status: 200, body: cmrGranules });+ }+ return Promise.resolve({ status: 404, body: '{}' });+ });++ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);+ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer).toBeDefined();+ expect(granuleLayer.get('granuleGroup')).toBe(true);+ });++ it('builds the layer from standard data alone when the NRT CMR request rejects', async () => {+ fetch.mockResponse((req) => {+ if (req.url === `${mockBaseCmrApi}granules.json${queryString}`) {+ return Promise.resolve({ status: 200, body: cmrGranules });+ }+ return Promise.reject(new Error('NRT CMR unavailable'));+ });++ const { options, attributes } = buildOptionsAndAttributes(IN_RANGE_DATE);+ const granuleLayer = await createGranuleLayer(granuleLayerDef, attributes, options);++ expect(granuleLayer).toBeDefined();+ expect(granuleLayer.get('granuleGroup')).toBe(true);+ });+ });++ describe('module export', () => {+ it('exports getGranuleLayer as a function', () => {+ const { createLayerWMTS } = layerbuilder(config, cache, store);+ const builder = granuleLayerBuilder(cache, store, createLayerWMTS);++ expect(typeof builder.getGranuleLayer).toBe('function');+ });+ });});diff --git a/web/js/map/granule/util.test.js b/web/js/map/granule/util.test.jsindex c6ac3b26b..fd919eb05 100644--- a/web/js/map/granule/util.test.js+++ b/web/js/map/granule/util.test.js@@ -1,6 +1,15 @@import {- datelineShiftGranules, getCMRQueryDates,- transformGranuleData, areCoordinatesAndPolygonExtentValid,+ datelineShiftGranules,+ getCMRQueryDates,+ getCMRQueryDateUpdateOptions,+ transformGranuleData,+ transformGranulesForProj,+ areCoordinatesAndPolygonExtentValid,+ getGranuleTileLayerExtent,+ getIndexForSortedInsert,+ isWithinDateRange,+ getParamsForGranuleRequest,+ granuleFootprint,} from './util';import { CRS } from '../../modules/map/constants';import util from '../../util/util';@@ -8,52 +17,108 @@ import util from '../../util/util';const mockGranules = require('../../../mock/granules.json');const cmrGranules = require('../../../mock/cmr_granules.json');+// ---------------------------------------------------------------------------+// Shared fixture+// ---------------------------------------------------------------------------const singleTransformedGranule = {date: '2019-09-24T00:12:00Z',polygon: [- [- -176.277237,- 4.723897,- ],- [- -149.287964,- 8.797498,- ],- [- -152.546494,- 29.685362,- ],- [- -182.751724,- 25.140713,- ],- [- -176.277237,- 4.723897,- ],+ [-176.277237, 4.723897],+ [-149.287964, 8.797498],+ [-152.546494, 29.685362],+ [-182.751724, 25.140713],+ [-176.277237, 4.723897],],dayNight: 'DAY',};+// ===========================================================================+// datelineShiftGranules+// ===========================================================================describe('shifting dateline granules', () => {- it('no shift when datline is crossed with same day', async () => {+ it('no shift when dateline is crossed with same day', () => {const selectedDate = new Date('2019-09-24T00:24:00.000Z');const granules = datelineShiftGranules(mockGranules.three, selectedDate, CRS.GEOGRAPHIC);-expect(granules).toEqual(mockGranules.three);});- it('shifts when granules cross days', async () => {+ it('shifts when granules cross days', () => {const selectedDate = new Date('2019-09-24T00:12:00.000Z');const shiftedGranules = datelineShiftGranules(mockGranules.two, selectedDate, CRS.GEOGRAPHIC);-expect(shiftedGranules).toEqual(mockGranules.twoShifted);expect(shiftedGranules.every(({ shifted }) => shifted)).toEqual(true);});++ // Branch: crs !== CRS.GEOGRAPHIC → datelineShiftNeeded is always false → returns granules as-is+ it('no shift when crs is not GEOGRAPHIC (e.g. ARCTIC)', () => {+ const selectedDate = new Date('2019-09-24T00:12:00.000Z');+ // Even if granules span different days, non-geographic CRS must not shift+ const granules = datelineShiftGranules(mockGranules.two, selectedDate, CRS.ARCTIC);+ expect(granules).toEqual(mockGranules.two);+ });++ // Branch: same day but polygon is on the west side → shifted = true+ it('shifts a same-day granule whose polygon is on the west side (lon < 0)', () => {+ const currentDate = new Date('2019-09-24T00:00:00.000Z');+ const granules = [+ {+ date: '2019-09-24T00:00:00Z', // same UTC day+ polygon: [+ [-170, 10],+ [-160, 20],+ [-150, 10],+ [-170, 10],+ ],+ },+ // Second granule from a different day to trigger datelineShiftNeeded = true+ {+ date: '2019-09-23T23:00:00Z',+ polygon: [+ [10, 10],+ [20, 20],+ [10, 10],+ ],+ },+ ];+ const shifted = datelineShiftGranules(granules, currentDate, CRS.GEOGRAPHIC);+ // The same-day west-side granule should be shifted+ expect(shifted[0].shifted).toBe(true);+ expect(shifted[0].polygon[0][0]).toBeCloseTo(-170 + 360);+ });++ // Branch: same day, east side polygon → shifted = false+ it('does not shift a same-day granule whose polygon is on the east side (lon >= 0)', () => {+ const currentDate = new Date('2019-09-24T00:00:00.000Z');+ const granules = [+ {+ date: '2019-09-24T01:00:00Z', // same UTC day+ polygon: [+ [10, 10],+ [20, 20],+ [10, 10],+ ],+ },+ // Different day to trigger shift logic+ {+ date: '2019-09-23T23:00:00Z',+ polygon: [+ [-170, 10],+ [-170, 10],+ ],+ },+ ];+ const shifted = datelineShiftGranules(granules, currentDate, CRS.GEOGRAPHIC);+ expect(shifted[0].shifted).toBe(false);+ // Polygon coordinates should be unchanged+ expect(shifted[0].polygon).toEqual(granules[0].polygon);+ });});+// ===========================================================================+// getCMRQueryDates+// ===========================================================================describe('getting CMR query date range', () => {- it('starts 8 hours before, 4 hours after, ', () => {+ it('starts 12 hours before, 4 hours after for GEOGRAPHIC', () => {const selectedDate = new Date('2019-09-24T00:00:00.000Z');const expectedStart = new Date('2019-09-23T12:00:00.000Z');const expectedEnd = new Date('2019-09-24T04:00:00.000Z');@@ -62,10 +127,160 @@ describe('getting CMR query date range', () => {expect(startQueryDate).toEqual(expectedStart);expect(endQueryDate).toEqual(expectedEnd);});++ it('starts 12 hours before, 4 hours after for WEB_MERCATOR', () => {+ const selectedDate = new Date('2019-09-24T00:00:00.000Z');+ const expectedStart = new Date('2019-09-23T12:00:00.000Z');+ const expectedEnd = new Date('2019-09-24T04:00:00.000Z');++ const { startQueryDate, endQueryDate } = getCMRQueryDates(CRS.WEB_MERCATOR, selectedDate);+ expect(startQueryDate).toEqual(expectedStart);+ expect(endQueryDate).toEqual(expectedEnd);+ });++ // Branch: polar projections → -48 hours+ it('starts 48 hours before, 4 hours after for ARCTIC (polar)', () => {+ const selectedDate = new Date('2019-09-24T00:00:00.000Z');+ const expectedStart = new Date('2019-09-22T00:00:00.000Z');+ const expectedEnd = new Date('2019-09-24T04:00:00.000Z');++ const { startQueryDate, endQueryDate } = getCMRQueryDates(CRS.ARCTIC, selectedDate);+ expect(startQueryDate).toEqual(expectedStart);+ expect(endQueryDate).toEqual(expectedEnd);+ });++ it('starts 48 hours before, 4 hours after for ANTARCTIC (polar)', () => {+ const selectedDate = new Date('2019-09-24T00:00:00.000Z');+ const expectedStart = new Date('2019-09-22T00:00:00.000Z');+ const expectedEnd = new Date('2019-09-24T04:00:00.000Z');++ const { startQueryDate, endQueryDate } = getCMRQueryDates(CRS.ANTARCTIC, selectedDate);+ expect(startQueryDate).toEqual(expectedStart);+ expect(endQueryDate).toEqual(expectedEnd);+ });});+// ===========================================================================+// getCMRQueryDateUpdateOptions+// ===========================================================================+describe('getCMRQueryDateUpdateOptions', () => {+ // Branch: no CMRDateStoreForLayer → early return+ it('returns canExtendRange false and needRangeUpdate true when no store provided', () => {+ const { startQueryDate, endQueryDate } = getCMRQueryDates(CRS.GEOGRAPHIC, new Date('2019-09-24T00:00:00.000Z'));+ const result = getCMRQueryDateUpdateOptions(null, new Date('2019-09-24T00:00:00.000Z'), startQueryDate, endQueryDate);+ expect(result.canExtendRange).toBe(false);+ expect(result.needRangeUpdate).toBe(true);+ });++ // Branch: new range is entirely within the current range → needRangeUpdate = false (first check)+ it('needRangeUpdate is false when new range is within existing range', () => {+ const currentStart = new Date('2019-09-23T00:00:00.000Z');+ const currentEnd = new Date('2019-09-25T00:00:00.000Z');+ const CMRDateStoreForLayer = { startDate: currentStart, endDate: currentEnd };+ // new range [Sep 23 12:00, Sep 24 04:00] is inside [Sep 23, Sep 25]+ const date = new Date('2019-09-24T00:00:00.000Z');+ const { startQueryDate, endQueryDate } = getCMRQueryDates(CRS.GEOGRAPHIC, date);+ const result = getCMRQueryDateUpdateOptions(+ CMRDateStoreForLayer, date, startQueryDate, endQueryDate);+ expect(result.needRangeUpdate).toBe(false);+ });++ // Branch: date is within [currentStart+1day, currentEnd] → needRangeUpdate = false (second check)+ it('needRangeUpdate is false when selected date is within existing range cushion', () => {+ const currentStart = new Date('2019-09-22T00:00:00.000Z');+ const currentEnd = new Date('2019-09-26T00:00:00.000Z');+ const CMRDateStoreForLayer = { startDate: currentStart, endDate: currentEnd };+ // Query range wider than existing, but the date itself is within [currentStart+1, currentEnd]+ const date = new Date('2019-09-24T00:00:00.000Z');+ const startQueryDate = new Date('2019-09-20T00:00:00.000Z'); // before currentStart+ const endQueryDate = new Date('2019-09-27T00:00:00.000Z'); // after currentEnd+ const result = getCMRQueryDateUpdateOptions(+ CMRDateStoreForLayer, date, startQueryDate, endQueryDate);+ expect(result.needRangeUpdate).toBe(false);+ });++ // Branch: newEnd extends current range from the left (newEndEqualsCurrentCMRStart)+ it('canExtendRange is true when new end equals current start (extend left)', () => {+ const currentStart = new Date('2019-09-24T04:00:00.000Z');+ const currentEnd = new Date('2019-09-26T00:00:00.000Z');+ const CMRDateStoreForLayer = { startDate: currentStart, endDate: currentEnd };+ const date = new Date('2019-09-20T00:00:00.000Z'); // well outside, force needRangeUpdate path+ const startQueryDate = new Date('2019-09-22T00:00:00.000Z');+ const endQueryDate = new Date('2019-09-24T04:00:00.000Z'); // exactly equals currentStart+ const result = getCMRQueryDateUpdateOptions(+ CMRDateStoreForLayer, date, startQueryDate, endQueryDate);+ expect(result.canExtendRange).toBe(true);+ expect(result.rangeStart).toBe(startQueryDate.getTime());+ expect(result.rangeEnd).toBe(currentEnd.getTime());+ });++ // Branch: newEnd can extend current range (newEndCanExtendCurrentCMREnd)+ it('canExtendRange is true when new range overlaps current range from the left', () => {+ const currentStart = new Date('2019-09-24T00:00:00.000Z');+ const currentEnd = new Date('2019-09-26T00:00:00.000Z');+ const CMRDateStoreForLayer = { startDate: currentStart, endDate: currentEnd };+ const date = new Date('2019-09-20T00:00:00.000Z');+ // newStart < currentStart AND newEnd >= currentStart (overlaps left side)+ const startQueryDate = new Date('2019-09-22T00:00:00.000Z');+ const endQueryDate = new Date('2019-09-25T00:00:00.000Z');+ const result = getCMRQueryDateUpdateOptions(+ CMRDateStoreForLayer, date, startQueryDate, endQueryDate);+ expect(result.canExtendRange).toBe(true);+ expect(result.rangeStart).toBe(startQueryDate.getTime());+ expect(result.rangeEnd).toBe(currentEnd.getTime());+ });++ // Branch: newStart extends current range from the right (newStartEqualsCurrentCMREnd)+ it('canExtendRange is true when new start equals current end (extend right)', () => {+ const currentStart = new Date('2019-09-22T00:00:00.000Z');+ const currentEnd = new Date('2019-09-24T00:00:00.000Z');+ const CMRDateStoreForLayer = { startDate: currentStart, endDate: currentEnd };+ const date = new Date('2019-09-28T00:00:00.000Z');+ const startQueryDate = new Date('2019-09-24T00:00:00.000Z'); // exactly equals currentEnd+ const endQueryDate = new Date('2019-09-26T00:00:00.000Z');+ const result = getCMRQueryDateUpdateOptions(+ CMRDateStoreForLayer, date, startQueryDate, endQueryDate);+ expect(result.canExtendRange).toBe(true);+ expect(result.rangeStart).toBe(currentStart.getTime());+ expect(result.rangeEnd).toBe(endQueryDate.getTime());+ });++ // Branch: newStart can extend current range (newStartCanExtendCurrentCMRStart)+ it('canExtendRange is true when new range overlaps current range from the right', () => {+ const currentStart = new Date('2019-09-22T00:00:00.000Z');+ const currentEnd = new Date('2019-09-25T00:00:00.000Z');+ const CMRDateStoreForLayer = { startDate: currentStart, endDate: currentEnd };+ const date = new Date('2019-09-28T00:00:00.000Z');+ // newStart > currentStart AND newStart <= currentEnd (overlaps right side)+ const startQueryDate = new Date('2019-09-23T00:00:00.000Z');+ const endQueryDate = new Date('2019-09-27T00:00:00.000Z');+ const result = getCMRQueryDateUpdateOptions(+ CMRDateStoreForLayer, date, startQueryDate, endQueryDate);+ expect(result.canExtendRange).toBe(true);+ expect(result.rangeStart).toBe(currentStart.getTime());+ expect(result.rangeEnd).toBe(endQueryDate.getTime());+ });++ // Branch: completely disjoint range → canExtendRange false, needRangeUpdate true+ it('canExtendRange is false and needRangeUpdate is true for completely disjoint ranges', () => {+ const currentStart = new Date('2019-09-22T00:00:00.000Z');+ const currentEnd = new Date('2019-09-23T00:00:00.000Z');+ const CMRDateStoreForLayer = { startDate: currentStart, endDate: currentEnd };+ const date = new Date('2019-09-30T00:00:00.000Z');+ const startQueryDate = new Date('2019-09-28T00:00:00.000Z'); // completely after current range+ const endQueryDate = new Date('2019-09-30T00:00:00.000Z');+ const result = getCMRQueryDateUpdateOptions(+ CMRDateStoreForLayer, date, startQueryDate, endQueryDate);+ expect(result.canExtendRange).toBe(false);+ expect(result.needRangeUpdate).toBe(true);+ });+});++// ===========================================================================+// transformGranuleData+// ===========================================================================describe('transform cmr granule data', () => {- it('converts cmr metadata into expected granule format', () => {+ it('converts cmr metadata into expected granule format (GEOGRAPHIC)', () => {const singleEntry = cmrGranules.feed.entry[0];const date = util.toISOStringSeconds(singleEntry.time_start);const transformedEntry = transformGranuleData(singleEntry, date, CRS.GEOGRAPHIC);@@ -74,51 +289,343 @@ describe('transform cmr granule data', () => {expect(transformedEntry.date).toEqual('2019-09-22T23:54:00Z');expect(transformedEntry.polygon.length).toEqual(5);});++ // Branch: entry has no polygons property → points = []+ it('returns empty polygon array when entry has no polygons', () => {+ const entry = { day_night_flag: 'DAY' }; // no polygons key+ const result = transformGranuleData(entry, '2019-09-24T00:00:00Z', CRS.GEOGRAPHIC);+ expect(result.polygon).toEqual([]);+ expect(result.dayNight).toEqual('DAY');+ });++ // Branch: non-GEOGRAPHIC CRS → maxDistance = Infinity (no coordinate wrapping)+ it('transforms granule data for a non-geographic (polar) projection without wrapping', () => {+ const singleEntry = cmrGranules.feed.entry[0];+ const date = util.toISOStringSeconds(singleEntry.time_start);+ const transformedEntry = transformGranuleData(singleEntry, date, CRS.ARCTIC);+ expect(transformedEntry.polygon.length).toEqual(5);+ });});+// ===========================================================================+// transformGranulesForProj+// ===========================================================================+describe('transformGranulesForProj', () => {+ it('transforms granule polygon coordinates into the target projection', () => {+ const granules = [singleTransformedGranule];+ const transformed = transformGranulesForProj(granules, CRS.WEB_MERCATOR);+ expect(transformed).toHaveLength(1);+ // The coordinates should now be in WEB_MERCATOR (metres), not degrees+ const [lon] = transformed[0].polygon[0];+ // WEB_MERCATOR x values for ~-176° lon will be in the order of -19 million+ expect(Math.abs(lon)).toBeGreaterThan(1000);+ // Original date and dayNight should be preserved+ expect(transformed[0].date).toEqual(singleTransformedGranule.date);+ expect(transformed[0].dayNight).toEqual(singleTransformedGranule.dayNight);+ });+});++// ===========================================================================+// areCoordinatesAndPolygonExtentValid+// ===========================================================================describe('areCoordinatesAndPolygonExtentValid', () => {- it('mouse coordinates inside polygon', () => {+ it('returns true when mouse coordinates are inside the polygon', () => {const visibleExtent = [-250, -90, 250, 90];const mouseCoords = [-165, 18];const points = singleTransformedGranule.polygon;- const isValid = areCoordinatesAndPolygonExtentValid(points, mouseCoords, visibleExtent);- expect(isValid).toEqual(true);+ expect(areCoordinatesAndPolygonExtentValid(points, mouseCoords, visibleExtent)).toEqual(true);});- it('mouse coordinates outside polygon', () => {+ it('returns false when mouse coordinates are outside the polygon', () => {const visibleExtent = [-250, -90, 250, 90];const mouseCoords = [-18, 18];const points = singleTransformedGranule.polygon;- const isValid = areCoordinatesAndPolygonExtentValid(points, mouseCoords, visibleExtent);- expect(isValid).toEqual(false);+ expect(areCoordinatesAndPolygonExtentValid(points, mouseCoords, visibleExtent)).toEqual(false);});- it('polygon outside map extent', () => {+ it('returns false when polygon is outside the map extent', () => {const visibleExtent = [-250, -90, 250, 90];const mouseCoords = [-18, 18];const points = [- [- -270,- 4.723897,- ],- [- -270,- 8.797498,- ],- [- -270,- 29.685362,- ],- [- -270,- 25.140713,- ],- [- -270,- 100,- ],+ [-270, 4.723897],+ [-270, 8.797498],+ [-270, 29.685362],+ [-270, 25.140713],+ [-270, 100],];- const isValid = areCoordinatesAndPolygonExtentValid(points, mouseCoords, visibleExtent);- expect(isValid).toEqual(false);+ expect(areCoordinatesAndPolygonExtentValid(points, mouseCoords, visibleExtent)).toEqual(false);+ });++ // Branch: polygon is larger than maxExtent → isPolygonLargerThanMaxExtent = true → returns false+ it('returns false when polygon extent contains (is larger than) the max extent', () => {+ // A polygon that covers the entire world and beyond+ const visibleExtent = [-180, -90, 180, 90];+ const mouseCoords = [0, 0]; // inside the huge polygon+ const points = [+ [-200, -100],+ [200, -100],+ [200, 100],+ [-200, 100],+ [-200, -100],+ ];+ expect(areCoordinatesAndPolygonExtentValid(points, mouseCoords, visibleExtent)).toEqual(false);+ });+});++// ===========================================================================+// getGranuleTileLayerExtent+// ===========================================================================+describe('getGranuleTileLayerExtent', () => {+ const fallbackExtent = [-180, -90, 180, 90];++ it('returns the polygon extent when it is finite', () => {+ const polygon = singleTransformedGranule.polygon;+ const result = getGranuleTileLayerExtent(polygon, fallbackExtent);+ // The result should be a bounding-box array [minX, minY, maxX, maxY]+ expect(result).toHaveLength(4);+ expect(Number.isFinite(result[0])).toBe(true);+ });++ // Branch: polygonExtent[0] is not finite → returns fallback extent+ it('returns the fallback extent when polygon extent is not finite', () => {+ // An empty polygon array produces a non-finite extent+ const result = getGranuleTileLayerExtent([], fallbackExtent);+ expect(result).toEqual(fallbackExtent);+ });+});++// ===========================================================================+// getIndexForSortedInsert+// ===========================================================================+describe('getIndexForSortedInsert', () => {+ const sortedDates = [+ '2019-09-22T00:00:00.000Z',+ '2019-09-23T00:00:00.000Z',+ '2019-09-25T00:00:00.000Z',+ ];++ // Branch: new date is before the first element → return 0+ it('returns 0 when the date is before the first element', () => {+ expect(getIndexForSortedInsert(sortedDates, '2019-09-21T00:00:00.000Z')).toEqual(0);+ });++ // Middle insertion+ it('returns the correct middle index', () => {+ expect(getIndexForSortedInsert(sortedDates, '2019-09-24T00:00:00.000Z')).toEqual(2);+ });++ // Append at end+ it('returns the last index when the date is after all elements', () => {+ expect(getIndexForSortedInsert(sortedDates, '2019-09-26T00:00:00.000Z')).toEqual(3);+ });+});++// ===========================================================================+// isWithinDateRange+// ===========================================================================+describe('isWithinDateRange', () => {+ const startDate = '2019-09-22T00:00:00.000Z';+ const endDate = '2019-09-25T00:00:00.000Z';++ it('returns true when date is within range', () => {+ expect(isWithinDateRange('2019-09-23T00:00:00.000Z', startDate, endDate)).toBe(true);+ });++ it('returns true when date equals startDate (boundary)', () => {+ expect(isWithinDateRange(startDate, startDate, endDate)).toBe(true);+ });++ it('returns true when date equals endDate (boundary)', () => {+ expect(isWithinDateRange(endDate, startDate, endDate)).toBe(true);+ });++ it('returns false when date is before startDate', () => {+ expect(isWithinDateRange('2019-09-21T00:00:00.000Z', startDate, endDate)).toBe(false);+ });++ it('returns false when date is after endDate', () => {+ expect(isWithinDateRange('2019-09-26T00:00:00.000Z', startDate, endDate)).toBe(false);+ });++ // Branch: no startDate provided → returns false+ it('returns false when startDate is not provided', () => {+ expect(isWithinDateRange('2019-09-23T00:00:00.000Z', null, endDate)).toBe(false);+ });++ // Branch: no endDate provided → uses current date as end, still checks range+ it('returns false when endDate is not provided and date is in the future', () => {+ // Use a date far in the past relative to "now"; no endDate → end defaults to now+ expect(isWithinDateRange('1990-01-01T00:00:00.000Z', '1989-01-01T00:00:00.000Z', null)).toBe(true);+ });+});++// ===========================================================================+// getParamsForGranuleRequest+// ===========================================================================+describe('getParamsForGranuleRequest', () => {+ const date = new Date('2019-09-24T00:00:00.000Z');++ // Branch: layer has no NRT conceptId → returns a single-element array+ it('returns a single request param object when no NRT conceptId exists', () => {+ const def = {+ id: 'test-layer',+ daynight: ['DAY'],+ conceptIds: [{ type: 'STD', shortName: 'MOD09GA' }],+ };+ const result = getParamsForGranuleRequest(def, date, CRS.GEOGRAPHIC);+ expect(result).toHaveLength(1);+ expect(result[0].shortName).toEqual('MOD09GA');+ expect(result[0].dayNight).toEqual('DAY');+ expect(result[0].bbox).toEqual([-180, -65, 180, 65]);+ expect(result[0].pageSize).toEqual(500);+ });++ // Branch: layer has an NRT conceptId → returns two-element array (STD + NRT)+ it('returns two request param objects when an NRT conceptId exists', () => {+ const def = {+ id: 'test-layer',+ daynight: ['NIGHT'],+ conceptIds: [+ { type: 'STD', shortName: 'MOD09GA' },+ { type: 'NRT', shortName: 'MOD09GA_NRT' },+ ],+ };+ const result = getParamsForGranuleRequest(def, date, CRS.GEOGRAPHIC);+ expect(result).toHaveLength(2);+ // NRT-sorted first entry returns the NRT shortName (with _NRT stripped) and the NRT shortName+ expect(result[0].shortName).toEqual('MOD09GA'); // _NRT stripped+ expect(result[1].shortName).toEqual('MOD09GA_NRT');+ });++ // Branch: ARCTIC projection → correct bbox+ it('uses the correct ARCTIC bbox', () => {+ const def = {+ id: 'test-layer',+ daynight: ['DAY'],+ conceptIds: [{ type: 'STD', shortName: 'MOD09GA' }],+ };+ const result = getParamsForGranuleRequest(def, date, CRS.ARCTIC);+ expect(result[0].bbox).toEqual([-180, 65, 180, 90]);+ });++ // Branch: ANTARCTIC projection → correct bbox+ it('uses the correct ANTARCTIC bbox', () => {+ const def = {+ id: 'test-layer',+ daynight: ['DAY'],+ conceptIds: [{ type: 'STD', shortName: 'MOD09GA' }],+ };+ const result = getParamsForGranuleRequest(def, date, CRS.ANTARCTIC);+ expect(result[0].bbox).toEqual([-180, -90, 180, -65]);+ });++ // Branch: WEB_MERCATOR projection → correct bbox+ it('uses the correct WEB_MERCATOR bbox', () => {+ const def = {+ id: 'test-layer',+ daynight: ['DAY'],+ conceptIds: [{ type: 'STD', shortName: 'MOD09GA' }],+ };+ const result = getParamsForGranuleRequest(def, date, CRS.WEB_MERCATOR);+ expect(result[0].bbox).toEqual([-180, -65, 180, 65]);+ });++ it('returns undefined shortName when conceptIds entries have no shortName', () => {+ const def = {+ id: 'bad-layer',+ daynight: ['DAY'],+ conceptIds: [{ type: 'STD' }], // valid array so .filter() works, but no shortName property+ };+ const result = getParamsForGranuleRequest(def, date, CRS.GEOGRAPHIC);+ expect(result[0].shortName).toBeUndefined();+ });+});++// ===========================================================================+// granuleFootprint+// ===========================================================================+describe('granuleFootprint', () => {+ // Minimal OpenLayers map mock+ const createMapMock = () => ({+ addLayer: jest.fn(),+ removeLayer: jest.fn(),+ });++ const points = singleTransformedGranule.polygon;+ const dateStr = '2019-09-24T00:12:00Z';++ describe('non-mobile (desktop) mode', () => {+ it('addFootprint draws the footprint on the map', () => {+ const map = createMapMock();+ const { addFootprint } = granuleFootprint(map, false);+ addFootprint(points, dateStr);+ expect(map.addLayer).toHaveBeenCalledTimes(1);+ });++ it('addFootprint is a no-op when called a second time with the same date (already drawn)', () => {+ const map = createMapMock();+ const { addFootprint } = granuleFootprint(map, false);+ addFootprint(points, dateStr);+ addFootprint(points, dateStr); // second call → currentGranule[date] already true+ // addLayer should only be called once+ expect(map.addLayer).toHaveBeenCalledTimes(1);+ });++ // Branch: !points → removeFootprint is called+ it('addFootprint calls removeFootprint when points is null/undefined', () => {+ const map = createMapMock();+ const { addFootprint } = granuleFootprint(map, false);+ addFootprint(null, dateStr);+ expect(map.removeLayer).toHaveBeenCalled();+ expect(map.addLayer).not.toHaveBeenCalled();+ });++ // Branch: !date → removeFootprint is called+ it('addFootprint calls removeFootprint when date is null/undefined', () => {+ const map = createMapMock();+ const { addFootprint } = granuleFootprint(map, false);+ addFootprint(points, null);+ expect(map.removeLayer).toHaveBeenCalled();+ expect(map.addLayer).not.toHaveBeenCalled();+ });++ it('updateFootprint removes the old footprint and draws a new one', () => {+ const map = createMapMock();+ const { updateFootprint } = granuleFootprint(map, false);+ updateFootprint(points, dateStr);+ expect(map.removeLayer).toHaveBeenCalled();+ expect(map.addLayer).toHaveBeenCalledTimes(1);+ });+ });++ describe('mobile mode', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ // Branch: initialIsMobile = true → uses debouncedDrawFootprint+ it('addFootprint debounces drawing on mobile', () => {+ const map = createMapMock();+ const { addFootprint } = granuleFootprint(map, true);+ addFootprint(points, dateStr);+ // Before debounce fires, addLayer should NOT have been called yet+ expect(map.addLayer).not.toHaveBeenCalled();+ // Advance timers past the 850ms debounce+ jest.advanceTimersByTime(900);+ expect(map.addLayer).toHaveBeenCalledTimes(1);+ });++ it('updateFootprint debounces drawing on mobile', () => {+ const map = createMapMock();+ const { updateFootprint } = granuleFootprint(map, true);+ updateFootprint(points, dateStr);+ expect(map.addLayer).not.toHaveBeenCalled();+ jest.advanceTimersByTime(900);+ expect(map.addLayer).toHaveBeenCalledTimes(1);+ });});});diff --git a/web/js/map/layerbuilder.test.js b/web/js/map/layerbuilder.test.jsindex 9cfe4d677..399a3908e 100644--- a/web/js/map/layerbuilder.test.js+++ b/web/js/map/layerbuilder.test.js@@ -1,3 +1,1244 @@-test('layerbuilder map test', () => {+import mapLayerBuilder from './layerbuilder';+jest.mock('ol/tilegrid/WMTS', () => jest.fn().mockImplementation(() => ({})));+jest.mock('ol/source/WMTS', () => jest.fn().mockImplementation(() => ({})));+jest.mock('ol/source/TileWMS', () => jest.fn().mockImplementation(() => ({})));+jest.mock('ol/source/XYZ', () => jest.fn().mockImplementation(() => ({})));+jest.mock('ol/source/ImageTile', () => jest.fn().mockImplementation(() => ({})));+jest.mock('ol/layer/Group', () =>+ jest.fn().mockImplementation(({ layers } = {}) => ({+ wv: null,+ layers,+ getLayers: () => ({ getArray: () => layers || [] }),+ getLayersArray: () => layers || [],+ setOpacity: jest.fn(),+ setVisible: jest.fn(),+ })),+);+jest.mock('ol/layer/Tile', () =>+ jest.fn().mockImplementation(() => ({+ wv: null,+ setOpacity: jest.fn(),+ setVisible: jest.fn(),+ setExtent: jest.fn(),+ getLayersArray: () => [],+ isWMS: false,+ })),+);+jest.mock('ol/proj', () => ({+ get: jest.fn().mockReturnValue({+ getExtent: jest.fn().mockReturnValue([-180, -90, 180, 90]),+ }),+}));+jest.mock('ol/tilegrid', () => ({+ TileGrid: jest.fn().mockImplementation(() => ({})),+ createXYZ: jest.fn().mockReturnValue({+ getResolutions: jest.fn().mockReturnValue([1, 0.5]),+ getTileSize: jest.fn().mockReturnValue([512, 512]),+ }),+}));+jest.mock('ol/format/MVT', () => jest.fn().mockImplementation(() => ({})));+jest.mock('ol/format/GeoJSON', () =>+ jest.fn().mockImplementation(() => ({+ readFeatures: jest.fn().mockReturnValue([]),+ })),+);+jest.mock('ol/source/VectorTile', () => jest.fn().mockImplementation(() => ({})));+jest.mock('ol/layer/Vector', () =>+ jest.fn().mockImplementation(() => ({+ wv: null,+ setOpacity: jest.fn(),+ setVisible: jest.fn(),+ getLayersArray: () => [],+ vectorData: null,+ isVector: false,+ })),+);+jest.mock('ol/source/Vector', () =>+ jest.fn().mockImplementation(() => ({+ getFormat: jest.fn().mockReturnValue({+ readFeatures: jest.fn().mockReturnValue([]),+ }),+ addFeatures: jest.fn(),+ })),+);+jest.mock('ol/layer/VectorTile', () =>+ jest.fn().mockImplementation(() => ({+ wv: null,+ setOpacity: jest.fn(),+ setVisible: jest.fn(),+ getLayersArray: () => [],+ })),+);+jest.mock('ol/style', () => ({+ Circle: jest.fn().mockImplementation(() => ({})),+ Fill: jest.fn().mockImplementation(() => ({})),+ Stroke: jest.fn().mockImplementation(() => ({})),+ Style: jest.fn().mockImplementation(() => ({})),+}));+jest.mock('ol/layer/Image', () =>+ jest.fn().mockImplementation(() => ({+ wv: null,+ setOpacity: jest.fn(),+ setVisible: jest.fn(),+ getLayersArray: () => [],+ })),+);+jest.mock('ol/source/ImageStatic', () => jest.fn().mockImplementation(() => ({})));++jest.mock('lodash/merge', () => jest.requireActual('lodash/merge'));+jest.mock('lodash/each', () => jest.requireActual('lodash/each'));+jest.mock('lodash/get', () => jest.requireActual('lodash/get'));+jest.mock('lodash/cloneDeep', () => jest.requireActual('lodash/cloneDeep'));++jest.mock('ol-mapbox-style', () => ({+ applyBackground: jest.fn().mockResolvedValue(undefined),+ applyStyle: jest.fn().mockResolvedValue(undefined),+}));++jest.mock('../util/util', () => ({+ __esModule: true,+ default: {+ toISOStringSeconds: jest.fn((date) => (date ? date.toISOString() : '')),+ roundTimeOneMinute: jest.fn((date) => date),+ clearTimeUTC: jest.fn((date) => {+ if (!date) return date;+ const d = new Date(date);+ d.setUTCHours(0, 0, 0, 0);+ return d;+ }),+ dateAdd: jest.fn((date, unit, amount) => {+ const d = new Date(date);+ if (unit === 'day') d.setDate(d.getDate() + amount);+ if (unit === 'month') d.setMonth(d.getMonth() + amount);+ if (unit === 'year') d.setFullYear(d.getFullYear() + amount);+ return d;+ }),+ },+}));++jest.mock('../util/cmr', () => ({+ buildGranulesUrl: jest.fn().mockReturnValue('http://cmr.example.com/granules'),+ cmrSearchAfterFetch: jest.fn().mockResolvedValue({ entries: [] }),+}));++jest.mock('../ol/lookupimagetile', () => jest.fn().mockReturnValue(jest.fn()));++jest.mock('./granule/granule-layer-builder', () =>+ jest.fn().mockReturnValue({+ getGranuleLayer: jest.fn().mockResolvedValue({+ wv: null,+ setOpacity: jest.fn(),+ setVisible: jest.fn(),+ getLayersArray: () => [],+ }),+ }),+);++jest.mock('./util', () => ({+ createVectorUrl: jest.fn().mockReturnValue('?TIME=2021-01-01'),+ getGeographicResolutionWMS: jest.fn().mockReturnValue([1, 0.5, 0.25]),+ mergeBreakpointLayerAttributes: jest.fn((def) => def),+}));++jest.mock('../modules/layers/util', () => ({+ datesInDateRanges: jest.fn().mockReturnValue([new Date('2021-01-01')]),+ prevDateInDateRange: jest.fn().mockReturnValue({+ next: new Date('2021-01-02'),+ previous: new Date('2020-12-31'),+ }),+ nearestInterval: jest.fn().mockReturnValue(new Date('2021-01-01')),+}));++jest.mock('../modules/date/selectors', () => ({+ getSelectedDate: jest.fn().mockReturnValue('2021-01-01T00:00:00.000Z'),+}));++jest.mock('../modules/palettes/selectors', () => ({+ isActive: jest.fn().mockReturnValue(false),+ getKey: jest.fn().mockReturnValue('palette-key'),+ getLookup: jest.fn().mockReturnValue({}),+}));++jest.mock('../modules/vector-styles/selectors', () => ({+ isActive: jest.fn().mockReturnValue(false),+ getKey: jest.fn().mockReturnValue('vector-style-key'),+ applyStyle: jest.fn(),+}));++jest.mock('../modules/map/constants', () => ({+ LEFT_WING_EXTENT: [-250, -90, -180, 90],+ RIGHT_WING_EXTENT: [180, -90, 250, 90],+ LEFT_WING_ORIGIN: [-250, 90],+ RIGHT_WING_ORIGIN: [180, 90],+ CENTER_MAP_ORIGIN: [0, 90],+}));++const buildMockLayer = () => ({+ wv: null,+ setOpacity: jest.fn(),+ setVisible: jest.fn(),+ setExtent: jest.fn(),+ getLayersArray: () => [],+});++const buildMockState = (overrides = {}) => ({+ proj: {+ id: 'geographic',+ selected: {+ id: 'geographic',+ crs: 'EPSG:4326',+ maxExtent: [-180, -90, 180, 90],+ resolutions: [1, 0.5, 0.25],+ },+ },+ date: {+ selected: new Date('2021-01-01T00:00:00.000Z'),+ selectedB: new Date('2021-01-02T00:00:00.000Z'),+ appNow: new Date('2021-01-01T00:00:00.000Z'),+ },+ compare: {+ activeString: 'active',+ },+ ui: {+ isKioskModeActive: false,+ displayStaticMap: false,+ },+ layers: {+ active: { activeTab: 'layers' },+ activeB: { activeTab: 'layers' },+ },+ animation: {+ isPlaying: false,+ },+ palettes: {+ custom: {},+ rendered: {},+ },+ config: {+ features: {+ describeDomains: { url: 'https://gibs.earthdata.nasa.gov' },+ cmr: { url: 'https://cmr.earthdata.nasa.gov' },+ },+ },+ sidebar: {+ activeTab: 'layers',+ },+ ...overrides,+});++const buildConfig = (sourceOverrides = {}) => ({+ sources: {+ 'test-source': {+ url: 'https://gibs.example.com',+ matrixSets: {+ EPSG4326_250m: {+ id: 'EPSG4326_250m',+ resolutions: [0.5, 0.25],+ tileSize: [512, 512],+ tileMatrices: [+ { matrixWidth: 2, matrixHeight: 1 },+ { matrixWidth: 4, matrixHeight: 2 },+ ],+ },+ },+ },+ 'EUMETSAT:wms': {+ url: 'https://eumetsat.example.com',+ matrixSets: {},+ },+ AERONET: {+ url: 'https://aeronet.example.com',+ matrixSets: {},+ },+ 'test-xyz': {+ url: 'https://xyz.example.com',+ },+ 'test-esri': {+ url: 'https://esri.example.com',+ },+ 'test-vector': {+ url: 'https://vector.example.com',+ matrixSets: {+ testMatrixSet: {+ resolutions: [0.5, 0.25],+ tileSize: [512, 512],+ tileMatrices: [[2, 1], [4, 2]],+ },+ },+ },+ 'test-indexed': {+ url: 'https://indexed.example.com',+ matrixSets: {+ testMatrixSet: {+ resolutions: [0.5, 0.25],+ tileSize: [512, 512],+ },+ },+ },+ ...sourceOverrides,+ },+});++const buildCache = () => ({+ getItem: jest.fn().mockReturnValue(null),+ setItem: jest.fn(),+});++const buildStore = (stateOverrides = {}) => ({+ getState: jest.fn().mockReturnValue(buildMockState(stateOverrides)),+});++const buildDef = (overrides = {}) => ({+ id: 'test-layer',+ type: 'wmts',+ source: 'test-source',+ matrixSet: 'EPSG4326_250m',+ format: 'image/jpeg',+ period: 'daily',+ projections: {+ geographic: {},+ },+ opacity: 1,+ wrapadjacentdays: false,+ wrapX: false,+ ...overrides,+});++const buildOptions = (overrides = {}) => ({+ group: 'active',+ date: new Date('2021-01-01T00:00:00.000Z'),+ ...overrides,+});++describe('mapLayerBuilder', () => {+ let config;+ let cache;+ let store;+ let builder;++ beforeEach(() => {+ jest.clearAllMocks();+ config = buildConfig();+ cache = buildCache();+ store = buildStore();+ builder = mapLayerBuilder(config, cache, store);+ });++ describe('createLayer - wmts type', () => {+ it('returns a layer for a wmts def', async () => {+ const layer = await builder.createLayer(buildDef(), buildOptions());+ expect(layer).toBeDefined();+ });++ it('sets layer visibility to false after creation', async () => {+ const layer = await builder.createLayer(buildDef(), buildOptions());+ expect(layer.setVisible).toHaveBeenCalledWith(false);+ });++ it('sets item in cache after creation', async () => {+ await builder.createLayer(buildDef(), buildOptions());+ expect(cache.setItem).toHaveBeenCalled();+ });++ it('returns cached layer when available', async () => {+ const cached = buildMockLayer();+ cache.getItem.mockReturnValue(cached);+ const layer = await builder.createLayer(buildDef(), buildOptions());+ expect(layer).toBe(cached);+ expect(cache.setItem).not.toHaveBeenCalled();+ });++ it('sets opacity from cached layer', async () => {+ const cached = buildMockLayer();+ cache.getItem.mockReturnValue(cached);+ await builder.createLayer(buildDef({ opacity: 0.5 }), buildOptions());+ expect(cached.setOpacity).toHaveBeenCalledWith(0.5);+ });++ it('defaults opacity to 1.0 when opacity is undefined', async () => {+ const cached = buildMockLayer();+ cache.getItem.mockReturnValue(cached);+ await builder.createLayer(buildDef({ opacity: undefined }), buildOptions());+ expect(cached.setOpacity).toHaveBeenCalledWith(1.0);+ });++ it('sets opacity on breakPointLayer sublayers when using cache', async () => {+ const sublayer = buildMockLayer();+ const cached = { ...buildMockLayer(), getLayersArray: () => [sublayer] };+ cache.getItem.mockReturnValue(cached);+ const def = buildDef({+ opacity: 0.7,+ breakPointLayer: { projections: { geographic: {} }, breakPointType: 'max' },+ });+ await builder.createLayer(def, buildOptions());+ expect(sublayer.setOpacity).toHaveBeenCalledWith(0.7);+ });++ it('uses options.group activeB', async () => {+ const layer = await builder.createLayer(buildDef(), buildOptions({ group: 'activeB' }));+ expect(layer).toBeDefined();+ });++ it('falls back to activeString when options.group is not set', async () => {+ const layer = await builder.createLayer(buildDef(), buildOptions({ group: undefined }));+ expect(layer).toBeDefined();+ });++ it('creates wrapped layer group for geographic proj with wrapadjacentdays', async () => {+ const OlLayerGroup = require('ol/layer/Group');+ await builder.createLayer(buildDef({ wrapadjacentdays: true }), buildOptions());+ expect(OlLayerGroup).toHaveBeenCalled();+ });++ it('does not wrap in non-geographic projection', async () => {+ const OlLayerGroup = require('ol/layer/Group');+ store = buildStore({+ proj: {+ id: 'arctic',+ selected: { id: 'arctic', crs: 'EPSG:3413', maxExtent: [-4194304, -4194304, 4194304, 4194304], resolutions: [1, 0.5] },+ },+ layers: { active: { activeTab: 'layers' }, activeB: { activeTab: 'layers' } },+ });+ builder = mapLayerBuilder(config, cache, store);+ OlLayerGroup.mockClear();+ const def = buildDef({ wrapadjacentdays: true, projections: { arctic: {} } });+ await builder.createLayer(def, buildOptions());+ expect(OlLayerGroup).not.toHaveBeenCalled();+ });++ it('handles wrapX flag on def', async () => {+ const layer = await builder.createLayer(buildDef({ wrapX: true }), buildOptions());+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - wms type', () => {+ it('returns a layer for a wms def', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'wms', format: 'image/png', tileSize: [512, 512] }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('throws error when wms source is invalid', async () => {+ await expect(+ builder.createLayer(buildDef({ type: 'wms', source: 'nonexistent-source' }), buildOptions()),+ ).rejects.toThrow('Invalid source');+ });++ it('handles geographic proj resolution override for WMS', async () => {+ const { getGeographicResolutionWMS } = require('./util');+ await builder.createLayer(+ buildDef({ type: 'wms', format: 'image/png', tileSize: [512, 512] }),+ buildOptions(),+ );+ expect(getGeographicResolutionWMS).toHaveBeenCalled();+ });++ it('handles EUMETSAT wms source with version 1.3.0', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'wms', source: 'EUMETSAT:wms', format: 'image/png', tileSize: [512, 512] }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles wms with styles property', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'wms', format: 'image/png', styles: 'my-style' }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles wms with wrapadjacentdays (covers day=1 and day=-1 branches)', async () => {+ const OlLayerGroup = require('ol/layer/Group');+ await builder.createLayer(+ buildDef({ type: 'wms', format: 'image/png', wrapadjacentdays: true }),+ buildOptions(),+ );+ expect(OlLayerGroup).toHaveBeenCalled();+ });++ it('handles wms with palette active', async () => {+ const { isActive, getLookup } = require('../modules/palettes/selectors');+ isActive.mockReturnValue(true);+ getLookup.mockReturnValue({ 0: { r: 255, g: 0, b: 0 } });+ const layer = await builder.createLayer(+ buildDef({ type: 'wms', format: 'image/png' }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles wms with resolutionBreakPoint', async () => {+ const layer = await builder.createLayer(+ buildDef({+ type: 'wms',+ format: 'image/png',+ breakPointLayer: { projections: { geographic: { resolutionBreakPoint: 500 } } },+ }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles non-geographic proj for WMS', async () => {+ store = buildStore({+ proj: {+ id: 'arctic',+ selected: { id: 'arctic', crs: 'EPSG:3413', maxExtent: [-4194304, -4194304, 4194304, 4194304], resolutions: [1, 0.5] },+ },+ layers: { active: { activeTab: 'layers' }, activeB: { activeTab: 'layers' } },+ });+ builder = mapLayerBuilder(config, cache, store);+ const layer = await builder.createLayer(+ buildDef({ type: 'wms', source: 'test-source', format: 'image/png', projections: { arctic: {} } }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles wms with subdaily period', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'wms', format: 'image/png', period: 'subdaily' }),+ buildOptions({ date: new Date('2021-01-01T12:00:00.000Z') }),+ );+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - xyz type', () => {+ it('returns a layer for xyz def with active group', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'xyz', source: 'test-xyz', layerName: 'test-xyz-layer', maxZoom: 10 }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('returns a layer for xyz def with activeB group', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'xyz', source: 'test-xyz', layerName: 'test-xyz-layer', maxZoom: 10 }),+ buildOptions({ group: 'activeB' }),+ );+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - esriMapServer type', () => {+ it('returns a layer for esriMapServer def', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'esriMapServer', source: 'test-esri' }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - vector type', () => {+ it('returns a layer for vector def (non-AERONET)', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'vector', source: 'test-vector', matrixSet: 'testMatrixSet', projections: { geographic: {} } }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('throws error for vector layer with invalid source', async () => {+ await expect(+ builder.createLayer(+ buildDef({ type: 'vector', source: 'nonexistent', matrixSet: 'testMatrixSet', projections: { geographic: {} } }),+ buildOptions(),+ ),+ ).rejects.toThrow('Invalid source');+ });++ it('throws error for vector layer with missing matrixSet', async () => {+ await expect(+ builder.createLayer(+ buildDef({ type: 'vector', source: 'test-vector', matrixSet: 'missingMatrixSet', projections: { geographic: {} } }),+ buildOptions(),+ ),+ ).rejects.toThrow('Undefined matrix set');+ });++ it('returns vector layer for AERONET source', async () => {+ builder = mapLayerBuilder(+ buildConfig({ AERONET: { url: 'https://aeronet.example.com', matrixSets: {} } }),+ cache,+ store,+ );+ const layer = await builder.createLayer(+ buildDef({ type: 'vector', source: 'AERONET', projections: { geographic: {} } }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('throws error for AERONET with missing source config', async () => {+ const noAeronetConfig = buildConfig();+ delete noAeronetConfig.sources.AERONET;+ builder = mapLayerBuilder(noAeronetConfig, cache, store);+ await expect(+ builder.createLayer(+ buildDef({ type: 'vector', source: 'AERONET', projections: { geographic: {} } }),+ buildOptions(),+ ),+ ).rejects.toThrow('Invalid source');+ });++ it('handles vector layer with def.matrixIds explicitly defined', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'vector', source: 'test-vector', matrixSet: 'testMatrixSet', matrixIds: [0, 1], projections: { geographic: {} } }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles vector layer with wrapadjacentdays', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'vector', source: 'test-vector', matrixSet: 'testMatrixSet', wrapadjacentdays: true, projections: { geographic: {} } }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles vector layer with max breakPointLayer and animation not playing', async () => {+ const layer = await builder.createLayer(+ buildDef({+ type: 'vector',+ source: 'test-vector',+ matrixSet: 'testMatrixSet',+ projections: { geographic: {} },+ breakPointLayer: { projections: { geographic: { resolutionBreakPoint: 1000 } }, breakPointType: 'max' },+ }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles vector layer with min breakPointLayer', async () => {+ const layer = await builder.createLayer(+ buildDef({+ type: 'vector',+ source: 'test-vector',+ matrixSet: 'testMatrixSet',+ projections: { geographic: {} },+ breakPointLayer: { projections: { geographic: { resolutionBreakPoint: 1000 } }, breakPointType: 'min' },+ }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles vector layer with breakPointLayer and animation playing', async () => {+ store = buildStore({+ animation: { isPlaying: true },+ layers: { active: { activeTab: 'layers' }, activeB: { activeTab: 'layers' } },+ });+ builder = mapLayerBuilder(config, cache, store);+ const layer = await builder.createLayer(+ buildDef({+ type: 'vector',+ source: 'test-vector',+ matrixSet: 'testMatrixSet',+ projections: { geographic: {} },+ breakPointLayer: { projections: { geographic: { resolutionBreakPoint: 1000 } }, breakPointType: 'max' },+ }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - indexedVector type', () => {+ const baseIndexedDef = () =>+ buildDef({+ type: 'indexedVector',+ source: 'test-indexed',+ layerName: 'test-indexed-layer',+ serviceName: 'testService',+ tiles: ['tile1'],+ vectorStyle: {},+ matrixSet: 'testMatrixSet',+ matrixSetLimits: null,+ projections: { geographic: {} },+ });++ it('returns a layer for indexedVector def without vectorStyle.url', async () => {+ const layer = await builder.createLayer(baseIndexedDef(), buildOptions());+ expect(layer).toBeDefined();+ });++ it('returns a layer for indexedVector def with vectorStyle.url', async () => {+ const { applyStyle: olmsApplyStyle, applyBackground } = require('ol-mapbox-style');+ const def = { ...baseIndexedDef(), vectorStyle: { url: 'https://style.example.com/style.json' } };+ await builder.createLayer(def, buildOptions());+ expect(olmsApplyStyle).toHaveBeenCalled();+ expect(applyBackground).toHaveBeenCalled();+ });++ it('uses configMatrixSet fallback when matrixSet missing from source', async () => {+ const def = { ...baseIndexedDef(), matrixSet: 'nonexistentMatrixSet' };+ const layer = await builder.createLayer(def, buildOptions());+ expect(layer).toBeDefined();+ });++ it('handles shifted option for indexedVector', async () => {+ const layer = await builder.createLayer(baseIndexedDef(), buildOptions({ shifted: true }));+ expect(layer).toBeDefined();+ });++ it('handles transformRequest with Source type returning modified Request', async () => {+ const { applyStyle: olmsApplyStyle } = require('ol-mapbox-style');+ let capturedTransformRequest;+ olmsApplyStyle.mockImplementationOnce((layer, url, opts) => {+ capturedTransformRequest = opts.transformRequest;+ return Promise.resolve();+ });+ const def = { ...baseIndexedDef(), vectorStyle: { url: 'https://style.example.com/style.json' } };+ await builder.createLayer(def, buildOptions());+ expect(capturedTransformRequest).toBeDefined();+ const result = capturedTransformRequest('https://example.com/VectorTileServer/layer', 'Source');+ expect(result).toBeDefined();+ });++ it('handles transformRequest with non-Source type returning undefined', async () => {+ const { applyStyle: olmsApplyStyle } = require('ol-mapbox-style');+ let capturedTransformRequest;+ olmsApplyStyle.mockImplementationOnce((layer, url, opts) => {+ capturedTransformRequest = opts.transformRequest;+ return Promise.resolve();+ });+ const def = { ...baseIndexedDef(), vectorStyle: { url: 'https://style.example.com/style.json' } };+ await builder.createLayer(def, buildOptions());+ const result = capturedTransformRequest('https://example.com/something', 'Tiles');+ expect(result).toBeUndefined();+ });+ });++ describe('createLayer - composite:wmts type', () => {+ it('returns a layer for composite:wmts with matching date', async () => {+ const def = buildDef({+ type: 'composite:wmts',+ source: 'test-source',+ matrixSet: 'EPSG4326_250m',+ format: 'image/jpeg',+ matrixSetLimits: null,+ layers: ['layer_20210101', 'layer_20210102'],+ projections: { geographic: {} },+ });+ const layer = await builder.createLayer(def, buildOptions({ date: new Date('2021-01-01T00:00:00.000Z') }));+ expect(layer).toBeDefined();+ });++ it('handles composite wmts where no layers match date', async () => {+ const def = buildDef({+ type: 'composite:wmts',+ source: 'test-source',+ matrixSet: 'EPSG4326_250m',+ format: 'image/jpeg',+ matrixSetLimits: null,+ layers: ['layer_20210102'],+ projections: { geographic: {} },+ });+ const layer = await builder.createLayer(def, buildOptions({ date: new Date('2021-01-01T00:00:00.000Z') }));+ expect(layer).toBeDefined();+ });++ it('handles composite wmts with MAXAR source', async () => {+ const maxarConfig = buildConfig({+ 'MAXAR:wmts': {+ url: 'https://maxar.example.com',+ matrixSets: {+ EPSG4326_250m: {+ id: 'EPSG4326_250m',+ resolutions: [0.5, 0.25],+ tileSize: [512, 512],+ tileMatrices: [],+ },+ },+ },+ });+ builder = mapLayerBuilder(maxarConfig, cache, store);+ const def = buildDef({+ type: 'composite:wmts',+ source: 'MAXAR:wmts',+ matrixSet: 'EPSG4326_250m',+ format: 'image/jpeg',+ matrixSetLimits: null,+ layers: ['layer_20210101'],+ projections: { geographic: {} },+ });+ const layer = await builder.createLayer(def, buildOptions({ date: new Date('2021-01-01T00:00:00.000Z') }));+ expect(layer).toBeDefined();+ });++ it('uses getSelectedDate when options.date is not available for composite', async () => {+ const def = buildDef({+ type: 'composite:wmts',+ source: 'test-source',+ matrixSet: 'EPSG4326_250m',+ format: 'image/jpeg',+ matrixSetLimits: null,+ layers: ['layer_20210101'],+ projections: { geographic: {} },+ });+ const layer = await builder.createLayer(def, buildOptions({ date: undefined }));+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - granule type', () => {+ it('returns a layer for granule def', async () => {+ const layer = await builder.createLayer(+ buildDef({ type: 'granule', projections: { geographic: {} } }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('does not call cache.setItem for granule type', async () => {+ await builder.createLayer(+ buildDef({ type: 'granule', projections: { geographic: {} } }),+ buildOptions(),+ );+ expect(cache.setItem).not.toHaveBeenCalled();+ });+ });++ describe('createLayer - titiler type', () => {+ const baseTitilerDef = () =>+ buildDef({+ type: 'titiler',+ source: 'test-source',+ bandCombo: {+ r: 'B4',+ g: 'B3',+ b: 'B2',+ assets: [],+ expression: 'B4/B3',+ rescale: '0,1',+ colormap_name: 'viridis',+ asset_as_band: true,+ bands_regex: '.*',+ color_formula: null,+ },+ collectionConceptID: 'C1234-PODAAC',+ minZoom: 3,+ projections: { geographic: {} },+ });++ it('returns a layer group for titiler def with active group', async () => {+ const layer = await builder.createLayer(baseTitilerDef(), buildOptions());+ expect(layer).toBeDefined();+ });++ it('does not call setVisible for titiler layer', async () => {+ const layer = await builder.createLayer(baseTitilerDef(), buildOptions());+ expect(layer.setVisible).not.toHaveBeenCalled();+ });++ it('returns a layer for titiler def with activeB group', async () => {+ const layer = await builder.createLayer(baseTitilerDef(), buildOptions({ group: 'activeB' }));+ expect(layer).toBeDefined();+ });++ it('uses conceptIds array when collectionConceptID is not set', async () => {+ const def = { ...baseTitilerDef(), collectionConceptID: undefined, conceptIds: [{ value: 'C9999-NSIDC' }] };+ const layer = await builder.createLayer(def, buildOptions());+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - unknown type', () => {+ it('throws for unknown layer type', async () => {+ await expect(+ builder.createLayer(buildDef({ type: 'unknown-type', projections: { geographic: {} } }), buildOptions()),+ ).rejects.toThrow('Unknown layer type');+ });+ });++ describe('createLayer - static image (kiosk mode)', () => {+ it('returns a static image layer in kiosk mode', async () => {+ store = buildStore({ ui: { isKioskModeActive: true, displayStaticMap: true } });+ builder = mapLayerBuilder(config, cache, store);+ const layer = await builder.createLayer(buildDef(), buildOptions());+ expect(layer).toBeDefined();+ });+ });++ describe('createLayer - TEMPO layer handling', () => {+ let mockWorker;++ beforeEach(() => {+ mockWorker = { postMessage: jest.fn(), terminate: jest.fn(), onmessage: null, onerror: null };+ global.Worker = jest.fn().mockImplementation(() => mockWorker);+ global.DOMParser = jest.fn().mockImplementation(() => ({+ parseFromString: jest.fn().mockReturnValue({+ querySelector: jest.fn().mockReturnValue(null),+ }),+ }));+ });++ it('calls tempoCallback immediately for TEMPO layers without tempoDateRanges', () => {+ const tempoCallback = jest.fn();+ const def = buildDef({ id: 'TEMPO_NO2_Hourly', projections: { geographic: {} } });+ builder.createLayer(def, buildOptions({ tempoCallback }));+ expect(tempoCallback).toHaveBeenCalledWith(def, [], 'active');+ });++ it('does not call tempoCallback when tempoDateRanges is already set', async () => {+ const tempoCallback = jest.fn();+ const def = buildDef({+ id: 'TEMPO_NO2_Hourly',+ tempoDateRanges: [{ startDate: '2021-01-01', endDate: '2021-01-02', dateInterval: '60' }],+ projections: { geographic: {} },+ });+ await builder.createLayer(def, buildOptions({ tempoCallback }));+ expect(tempoCallback).not.toHaveBeenCalled();+ });++ it('does not call tempoCallback when not a TEMPO layer', async () => {+ const tempoCallback = jest.fn();+ await builder.createLayer(buildDef({ id: 'regular-layer' }), buildOptions({ tempoCallback }));+ expect(tempoCallback).not.toHaveBeenCalled();+ });++ it('does not call tempoCallback when tempoCallback is not provided', async () => {+ const def = buildDef({ id: 'TEMPO_NO2_Hourly', projections: { geographic: {} } });+ const layer = await builder.createLayer(def, buildOptions({ tempoCallback: undefined }));+ expect(layer).toBeDefined();+ });+ });++ describe('getRequestDates', () => {+ it('uses options.date when provided', async () => {+ const layer = await builder.createLayer(buildDef(), buildOptions({ date: new Date('2020-06-15T00:00:00.000Z') }));+ expect(layer).toBeDefined();+ });++ it('falls back to stateCurrentDate when options.date is not set', async () => {+ const layer = await builder.createLayer(buildDef(), buildOptions({ date: undefined }));+ expect(layer).toBeDefined();+ });++ it('uses cached previousDate/nextDate range when current date is within it', async () => {+ const now = new Date('2021-01-01T12:00:00.000Z');+ const prev = new Date('2021-01-01T00:00:00.000Z');+ const next = new Date('2021-01-02T00:00:00.000Z');+ const layer = await builder.createLayer(+ buildDef(),+ buildOptions({ date: now, previousLayer: { previousDate: prev, nextDate: next } }),+ );+ expect(layer).toBeDefined();+ });++ it('handles ongoing daily period with multiple dateRange intervals', async () => {+ const layer = await builder.createLayer(+ buildDef({+ ongoing: true,+ period: 'daily',+ dateRanges: [+ { startDate: '2020-01-01', endDate: '2020-06-01', dateInterval: '1' },+ { startDate: '2020-06-01', endDate: '2021-01-01', dateInterval: '3' },+ ],+ }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles ongoing monthly period', async () => {+ const layer = await builder.createLayer(+ buildDef({ ongoing: true, period: 'monthly', dateRanges: [] }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles ongoing yearly period', async () => {+ const layer = await builder.createLayer(+ buildDef({ ongoing: true, period: 'yearly', dateRanges: [] }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles ongoing subdaily period (else branch)', async () => {+ const layer = await builder.createLayer(+ buildDef({ ongoing: true, period: 'subdaily', dateRanges: [] }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles non-ongoing with no dateRanges', async () => {+ const layer = await builder.createLayer(+ buildDef({ ongoing: false, period: 'daily' }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });+ });++ describe('layerKey', () => {+ it('cache key is a string for periodic layers', async () => {+ await builder.createLayer(buildDef({ period: 'daily' }), buildOptions());+ expect(typeof cache.setItem.mock.calls[0][0]).toBe('string');+ });++ it('does not include date in key for static layers (no period)', async () => {+ const layer = await builder.createLayer(buildDef({ period: undefined }), buildOptions());+ expect(layer).toBeDefined();+ });++ it('includes palette key when palette is active', async () => {+ const { isActive } = require('../modules/palettes/selectors');+ isActive.mockReturnValue(true);+ const layer = await builder.createLayer(buildDef(), buildOptions());+ expect(layer).toBeDefined();+ });++ it('includes vector style key when vector style is active', async () => {+ const { isActive } = require('../modules/vector-styles/selectors');+ isActive.mockReturnValue(true);+ const layer = await builder.createLayer(buildDef(), buildOptions());+ expect(layer).toBeDefined();+ });++ it('uses subdaily date format in key for subdaily period', async () => {+ await builder.createLayer(buildDef({ period: 'subdaily' }), buildOptions());+ expect(cache.setItem).toHaveBeenCalled();+ });+ });++ describe('getCacheOptions', () => {+ it('returns empty object for non-subdaily period', async () => {+ await builder.createLayer(buildDef({ period: 'daily' }), buildOptions());+ expect(cache.setItem.mock.calls[0][2]).toEqual({});+ });++ it('returns empty object for subdaily layer older than 30 minutes', async () => {+ await builder.createLayer(+ buildDef({ period: 'subdaily' }),+ buildOptions({ date: new Date('2000-01-01T00:00:00.000Z') }),+ );+ expect(cache.setItem.mock.calls[0][2]).toEqual({});+ });+ });++ describe('createLayerWMTS - internal branches', () => {+ it('handles palette active (tileClass lookup)', async () => {+ const { isActive, getLookup } = require('../modules/palettes/selectors');+ const lookupFactory = require('../ol/lookupimagetile');+ isActive.mockReturnValue(true);+ getLookup.mockReturnValue({ 0: { r: 255, g: 0, b: 0 } });+ await builder.createLayer(buildDef(), buildOptions());+ expect(lookupFactory).toHaveBeenCalled();+ });++ it('handles subdaily wmts layer', async () => {+ const layer = await builder.createLayer(+ buildDef({ period: 'subdaily' }),+ buildOptions({ date: new Date('2021-01-01T10:00:00.000Z') }),+ );+ expect(layer).toBeDefined();+ });++ it('handles subdaily wmts with null date', async () => {+ const layer = await builder.createLayer(+ buildDef({ period: 'subdaily' }),+ buildOptions({ date: null }),+ );+ expect(layer).toBeDefined();+ });++ it('uses sourceOverride url for wmts layer', async () => {+ const layer = await builder.createLayer(+ buildDef({ sourceOverride: 'https://override.example.com' }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles matching matrixSetLimits length (calcExtentsFromLimits full path)', async () => {+ const configWithLimits = buildConfig({+ 'test-source': {+ url: 'https://gibs.example.com',+ matrixSets: {+ EPSG4326_250m: {+ id: 'EPSG4326_250m',+ resolutions: [0.5, 0.25],+ tileSize: [512, 512],+ tileMatrices: [{+ matrixWidth: 2,+ matrixHeight: 1,+ }, { matrixWidth: 4, matrixHeight: 2 }],+ origin: [-180, 90],+ extent: [-180, -90, 180, 90],+ },+ },+ },+ });+ builder = mapLayerBuilder(configWithLimits, cache, store);+ const layer = await builder.createLayer(+ buildDef({+ matrixSetLimits: [+ { minTileCol: 0, maxTileCol: 1, minTileRow: 0, maxTileRow: 0 },+ { minTileCol: 0, maxTileCol: 3, minTileRow: 0, maxTileRow: 1 },+ ],+ }),+ buildOptions(),+ );+ expect(layer).toBeDefined();+ });++ it('handles wmts with explicit style defined', async () => {+ const layer = await builder.createLayer(buildDef({ style: 'my-style' }), buildOptions());+ expect(layer).toBeDefined();+ });++ it('throws error when wmts matrixSet is invalid', async () => {+ await expect(+ builder.createLayer(buildDef({ matrixSet: 'nonexistentMatrixSet' }), buildOptions()),+ ).rejects.toThrow('Undefined matrix set');+ });++ it('handles shifted option using RIGHT_WING_ORIGIN and RIGHT_WING_EXTENT', async () => {+ const layer = await builder.createLayer(buildDef(), buildOptions({ shifted: true }));+ expect(layer).toBeDefined();+ });++ it('handles tileMatrices undefined (produces empty sizes array)', async () => {+ const configNoMatrices = buildConfig({+ 'test-source': {+ url: 'https://gibs.example.com',+ matrixSets: {+ EPSG4326_250m: {+ id: 'EPSG4326_250m',+ resolutions: [0.5, 0.25],+ tileSize: [512, 512],+ tileMatrices: undefined,+ },+ },+ },+ });+ builder = mapLayerBuilder(configNoMatrices, cache, store);+ const layer = await builder.createLayer(buildDef(), buildOptions());+ expect(layer).toBeDefined();+ });+ });++ describe('createLayerVectorAeronet - internal branches', () => {+ it('handles subdaily AERONET with null date (uses getRequestDates)', async () => {+ builder = mapLayerBuilder(+ buildConfig({ AERONET: { url: 'https://aeronet.example.com', matrixSets: {} } }),+ cache,+ store,+ );+ const layer = await builder.createLayer(+ buildDef({ type: 'vector', source: 'AERONET', period: 'subdaily', projections: { geographic: {} } }),+ buildOptions({ date: null }),+ );+ expect(layer).toBeDefined();+ });+ });++ describe('cmrRebuildAttempts attribute spread', () => {+ it('includes cmrRebuildAttempts in attributes when provided as non-null', async () => {+ await builder.createLayer(buildDef(), buildOptions({ cmrRebuildAttempts: 3 }));+ expect(cache.setItem).toHaveBeenCalled();+ });++ it('excludes cmrRebuildAttempts from attributes when null', async () => {+ await builder.createLayer(buildDef(), buildOptions({ cmrRebuildAttempts: null }));+ expect(cache.setItem).toHaveBeenCalled();+ });+ });++ describe('getUpdatedDateRanges worker messaging', () => {+ let mockWorker;++ beforeEach(() => {+ mockWorker = { postMessage: jest.fn(), terminate: jest.fn(), onmessage: null, onerror: null };+ global.Worker = jest.fn().mockImplementation(() => mockWorker);+ global.DOMParser = jest.fn().mockImplementation(() => ({+ parseFromString: jest.fn().mockReturnValue({+ querySelector: jest.fn().mockReturnValue(null),+ }),+ }));+ });++ it('handles worker onmessage with final array data format', () => {+ const tempoCallback = jest.fn();+ const def = buildDef({+ id: 'TEMPO_NO2_Hourly',+ projections: { geographic: {} },+ dateRanges: [{ startDate: '2021-01-01', endDate: '2021-01-02', dateInterval: '60' }],+ });+ builder.createLayer(def, buildOptions({ tempoCallback }));+ mockWorker.onmessage({ data: [['2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z', '60']] });+ expect(mockWorker.terminate).toHaveBeenCalled();+ expect(tempoCallback).toHaveBeenCalledTimes(2);+ });++ it('handles worker onmessage with xml string and valid Domain element', () => {+ global.DOMParser = jest.fn().mockImplementation(() => ({+ parseFromString: jest.fn().mockReturnValue({+ querySelector: jest.fn().mockReturnValue({ textContent: 'domain1 domain2' }),+ }),+ }));+ const tempoCallback = jest.fn();+ builder.createLayer(+ buildDef({ id: 'TEMPO_NO2_Hourly', projections: { geographic: {} } }),+ buildOptions({ tempoCallback }),+ );+ mockWorker.onmessage({ data: '<xml>some xml</xml>' });+ expect(mockWorker.postMessage).toHaveBeenCalledTimes(2);+ });++ it('handles worker onmessage with xml string and null Domain element', () => {+ global.DOMParser = jest.fn().mockImplementation(() => ({+ parseFromString: jest.fn().mockReturnValue({+ querySelector: jest.fn().mockReturnValue(null),+ }),+ }));+ const tempoCallback = jest.fn();+ builder.createLayer(+ buildDef({ id: 'TEMPO_NO2_Hourly', projections: { geographic: {} } }),+ buildOptions({ tempoCallback }),+ );+ mockWorker.onmessage({ data: '<xml>empty</xml>' });+ expect(mockWorker.terminate).toHaveBeenCalled();+ expect(tempoCallback).toHaveBeenCalledTimes(2);+ });++ it('handles worker onerror by terminating and calling callback', () => {+ const tempoCallback = jest.fn();+ builder.createLayer(+ buildDef({ id: 'TEMPO_NO2_Hourly', projections: { geographic: {} } }),+ buildOptions({ tempoCallback }),+ );+ mockWorker.onerror();+ expect(mockWorker.terminate).toHaveBeenCalled();+ expect(tempoCallback).toHaveBeenCalledTimes(2);+ });++ it('formats existing dateRanges where startDate equals endDate', () => {+ const tempoCallback = jest.fn();+ const sameDate = '2021-01-01T00:00:00.000Z';+ const def = buildDef({+ id: 'TEMPO_NO2_Hourly',+ projections: { geographic: {} },+ dateRanges: [{ startDate: sameDate, endDate: sameDate, dateInterval: '60' }],+ });+ builder.createLayer(def, buildOptions({ tempoCallback }));+ mockWorker.onmessage({ data: [['2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z', '60']] });+ expect(tempoCallback).toHaveBeenCalledTimes(2);+ });+ });});diff --git a/web/js/map/map.test.js b/web/js/map/map.test.jsindex 66dafb453..96f9331c3 100644--- a/web/js/map/map.test.js+++ b/web/js/map/map.test.js@@ -1,4 +1,16 @@-import { mapParser } from './map';+import {+ CRS_WGS_84,+ CRS_WGS_84_QUERY_EXTENT,+ mapIsExtentValid,+ mapParser,+ mapAdjustAntiMeridian,+ mapDistance2D,+ mapDistanceX,+ mapInterpolate2D,+ setVisibility,+ setOpacity,+ getLayerByName,+} from './map';describe('permalink 1.1', () => {test('parses state', () => {@@ -36,3 +48,387 @@ describe('permalink 1.2', () => {expect(errors).toHaveLength(1);});});++// ─── constants ───────────────────────────────────────────────────────────────++describe('CRS_WGS_84', () => {+ test('equals EPSG:4326', () => {+ expect(CRS_WGS_84).toBe('EPSG:4326');+ });+});++describe('CRS_WGS_84_QUERY_EXTENT', () => {+ test('is the expected 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', () => {+ expect(mapIsExtentValid([-180, -90, 180, 90])).toBe(true);+ });++ test('returns false when any value in the array is NaN', () => {+ expect(mapIsExtentValid([-180, NaN, 180, 90])).toBe(false);+ });++ test('returns false when a string value produces NaN', () => {+ expect(mapIsExtentValid([-180, -90, 'x', 90])).toBe(false);+ });++ test('returns true for an extent object that exposes toArray()', () => {+ const extentObj = {+ toArray: () => [-180, -90, 180, 90],+ };+ expect(mapIsExtentValid(extentObj)).toBe(true);+ });++ test('returns false for an extent object whose toArray() contains NaN', () => {+ const extentObj = {+ toArray: () => [-180, NaN, 180, 90],+ };+ expect(mapIsExtentValid(extentObj)).toBe(false);+ });++ test('returns true for an all-zero extent', () => {+ expect(mapIsExtentValid([0, 0, 0, 0])).toBe(true);+ });+});++// ─── mapParser ────────────────────────────────────────────────────────────────++describe('mapParser — permalink 1.1 (map key)', () => {+ test('parses valid map value into state.v array', () => {+ const errors = [];+ const state = { map: '0,1,2,3' };+ mapParser(state, errors);+ expect(state.v).toEqual([0, 1, 2, 3]);+ expect(errors).toHaveLength(0);+ });++ test('records an error and leaves state.v falsy for invalid map value', () => {+ const errors = [];+ const state = { map: '0,1,x,3' };+ mapParser(state, errors);+ expect(state.v).toBeFalsy();+ expect(errors).toHaveLength(1);+ });+});++describe('mapParser — permalink 1.2 (v key)', () => {+ test('parses valid v value into state.v array', () => {+ 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('records an error and leaves state.v falsy for invalid v value', () => {+ const errors = [];+ const state = { v: 'a,b,c,d' };+ mapParser(state, errors);+ expect(state.v).toBeFalsy();+ expect(errors).toHaveLength(1);+ });+});++describe('mapParser — no map or v key', () => {+ test('does nothing when neither map nor v is present in state', () => {+ const errors = [];+ const state = {};+ mapParser(state, errors);+ expect(state.v).toBeUndefined();+ expect(errors).toHaveLength(0);+ });+});++// ─── mapAdjustAntiMeridian ────────────────────────────────────────────────────++describe('mapAdjustAntiMeridian', () => {+ test('returns an OlGeomPolygon instance', () => {+ const polygon = {+ getLinearRing: jest.fn().mockReturnValue({+ getCoordinates: jest.fn().mockReturnValue([[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]),+ }),+ };+ const result = mapAdjustAntiMeridian(polygon, 0);+ expect(result).toBeDefined();+ });++ test('shifts negative longitudes positive when adjustSign > 0', () => {+ const points = [[-10, 0], [10, 0], [10, 10], [-10, 10], [-10, 0]];+ const polygon = {+ getLinearRing: jest.fn().mockReturnValue({+ getCoordinates: jest.fn().mockReturnValue(points),+ }),+ };+ const result = mapAdjustAntiMeridian(polygon, 1);+ expect(result).toBeDefined();+ });++ test('shifts positive longitudes negative when adjustSign < 0', () => {+ const points = [[10, 0], [170, 0], [170, 10], [10, 10], [10, 0]];+ const polygon = {+ getLinearRing: jest.fn().mockReturnValue({+ getCoordinates: jest.fn().mockReturnValue(points),+ }),+ };+ const result = mapAdjustAntiMeridian(polygon, -1);+ expect(result).toBeDefined();+ });++ test('leaves points unchanged when adjustSign is 0', () => {+ const points = [[-10, 0], [10, 0], [10, 10], [-10, 10], [-10, 0]];+ const polygon = {+ getLinearRing: jest.fn().mockReturnValue({+ getCoordinates: jest.fn().mockReturnValue(points),+ }),+ };+ const result = mapAdjustAntiMeridian(polygon, 0);+ expect(result).toBeDefined();+ });+});++// ─── mapDistance2D ────────────────────────────────────────────────────────────++describe('mapDistance2D', () => {+ test('returns 0 for identical points', () => {+ expect(mapDistance2D([0, 0], [0, 0])).toBe(0);+ });++ test('returns correct distance for a 3-4-5 right triangle', () => {+ expect(mapDistance2D([0, 0], [3, 4])).toBe(5);+ });++ test('returns correct distance for points with negative coordinates', () => {+ expect(mapDistance2D([-3, -4], [0, 0])).toBe(5);+ });++ test('returns correct horizontal distance', () => {+ expect(mapDistance2D([0, 0], [10, 0])).toBe(10);+ });++ test('returns correct vertical distance', () => {+ expect(mapDistance2D([0, 0], [0, 7])).toBe(7);+ });+});++// ─── mapDistanceX ─────────────────────────────────────────────────────────────++describe('mapDistanceX', () => {+ test('returns 0 for equal values', () => {+ 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);+ });++ test('handles negative coordinates', () => {+ expect(mapDistanceX(-5, 5)).toBe(10);+ });+});++// ─── mapInterpolate2D ─────────────────────────────────────────────────────────++describe('mapInterpolate2D', () => {+ test('returns p1 when amount is 0', () => {+ expect(mapInterpolate2D([0, 0], [10, 10], 0)).toEqual([0, 0]);+ });++ test('returns p2 when amount is 1', () => {+ expect(mapInterpolate2D([0, 0], [10, 10], 1)).toEqual([10, 10]);+ });++ test('returns midpoint when amount is 0.5', () => {+ expect(mapInterpolate2D([0, 0], [10, 10], 0.5)).toEqual([5, 5]);+ });++ test('interpolates correctly with non-zero p1', () => {+ 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]);+ });+});++// ─── setVisibility ────────────────────────────────────────────────────────────++describe('setVisibility', () => {+ test('calls setVisibility on a control layer', () => {+ const layer = {+ isControl: true,+ setVisibility: jest.fn(),+ };+ setVisibility(layer, true, 0.8);+ expect(layer.setVisibility).toHaveBeenCalledWith(true);+ });++ test('calls setVisibility(false) on a control layer when visible is false', () => {+ const layer = {+ isControl: true,+ setVisibility: jest.fn(),+ };+ setVisibility(layer, false, 0.8);+ expect(layer.setVisibility).toHaveBeenCalledWith(false);+ });++ test('sets div opacity to the given opacity when visible is true', () => {+ const layer = {+ isControl: false,+ div: { style: { opacity: null } },+ getVisibility: jest.fn().mockReturnValue(true),+ setVisibility: jest.fn(),+ };+ 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 = {+ isControl: false,+ div: { style: { opacity: null } },+ getVisibility: jest.fn().mockReturnValue(true),+ setVisibility: jest.fn(),+ };+ setVisibility(layer, false, 0.6);+ expect(layer.div.style.opacity).toBe(0);+ });++ test('calls setVisibility(true) when visible and opacity > 0 and layer is currently invisible', () => {+ const layer = {+ isControl: false,+ div: { style: { opacity: null } },+ getVisibility: jest.fn().mockReturnValue(false), // currently invisible+ setVisibility: jest.fn(),+ };+ setVisibility(layer, true, 0.5);+ expect(layer.setVisibility).toHaveBeenCalledWith(true);+ });++ test('does not call setVisibility when visible but opacity is 0', () => {+ const layer = {+ isControl: false,+ div: { style: { opacity: null } },+ getVisibility: jest.fn().mockReturnValue(false),+ setVisibility: jest.fn(),+ };+ setVisibility(layer, true, 0);+ expect(layer.setVisibility).not.toHaveBeenCalled();+ });++ test('does not call setVisibility when layer is already visible', () => {+ const layer = {+ isControl: false,+ div: { style: { opacity: null } },+ getVisibility: jest.fn().mockReturnValue(true),+ setVisibility: jest.fn(),+ };+ setVisibility(layer, true, 0.9);+ expect(layer.setVisibility).not.toHaveBeenCalled();+ });+});++// ─── setOpacity ───────────────────────────────────────────────────────────────++describe('setOpacity', () => {+ test('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);+ });++ test('restores transitionEffect to originalTransitionEffect when opacity is 1', () => {+ const layer = {+ setOpacity: jest.fn(),+ transitionEffect: 'none',+ originalTransitionEffect: 'resize',+ };+ setOpacity(layer, 1);+ expect(layer.transitionEffect).toBe('resize');+ });++ test('falls back to "resize" when opacity is 1 and originalTransitionEffect is not set', () => {+ const layer = {+ setOpacity: jest.fn(),+ transitionEffect: 'none',+ originalTransitionEffect: undefined,+ };+ setOpacity(layer, 1);+ expect(layer.transitionEffect).toBe('resize');+ });++ test('saves current transitionEffect and sets it to "none" when opacity is not 1', () => {+ const layer = {+ setOpacity: jest.fn(),+ transitionEffect: 'resize',+ originalTransitionEffect: undefined,+ };+ setOpacity(layer, 0.5);+ expect(layer.originalTransitionEffect).toBe('resize');+ expect(layer.transitionEffect).toBe('none');+ });++ test('handles opacity of 0 as a non-1 value (stores effect and sets none)', () => {+ const layer = {+ setOpacity: jest.fn(),+ transitionEffect: 'resize',+ originalTransitionEffect: undefined,+ };+ setOpacity(layer, 0);+ expect(layer.transitionEffect).toBe('none');+ });+});++// ─── getLayerByName ───────────────────────────────────────────────────────────++describe('getLayerByName', () => {+ test('returns the matching layer when found by wvname', () => {+ const layerA = { wvname: 'layer-a' };+ const layerB = { wvname: 'layer-b' };+ const map = {+ getLayers: () => ({ getArray: () => [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 = {+ getLayers: () => ({ getArray: () => [layerA] }),+ };+ expect(getLayerByName(map, 'nonexistent')).toBeUndefined();+ });++ test('returns undefined when the layers array is empty', () => {+ const map = {+ getLayers: () => ({ getArray: () => [] }),+ };+ 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 = {+ getLayers: () => ({ getArray: () => [layerA1, layerA2] }),+ };+ expect(getLayerByName(map, 'layer-a')).toBe(layerA1);+ });+});diff --git a/web/js/map/model.test.js b/web/js/map/model.test.jsindex d9ec999f9..f155f3da7 100644--- a/web/js/map/model.test.js+++ b/web/js/map/model.test.js@@ -1,3 +1,507 @@-test('model map test', () => {+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);+ });+});++// =============================================================================+// 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);+ });+});++// =============================================================================+// 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);+ });++ test('works correctly with negative coordinates', () => {+ expect(mapDistance2D([-3, -4], [0, 0])).toBe(5);+ });++ test('returns the horizontal distance when y values are equal', () => {+ expect(mapDistance2D([0, 0], [10, 0])).toBe(10);+ });++ 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]));+ });+});++// =============================================================================+// 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);+ });++ test('handles negative values', () => {+ expect(mapDistanceX(-5, 5)).toBe(10);+ });++ test('handles both negative values', () => {+ expect(mapDistanceX(-10, -3)).toBe(7);+ });+});++// =============================================================================+// 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]);+ });+});++// =============================================================================+// 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]);+ });+});++// =============================================================================+// 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('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();+ });+ });+});++// =============================================================================+// 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');+ });+ });+});++// =============================================================================+// 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);+ });});diff --git a/web/js/map/natural-events/cluster.test.js b/web/js/map/natural-events/cluster.test.jsindex 9a2f1bbda..2dd0fd6a9 100644--- a/web/js/map/natural-events/cluster.test.js+++ b/web/js/map/natural-events/cluster.test.js@@ -1,3 +1,394 @@-test('cluster map test', () => {+import {+ naturalEventsClusterCreateObject,+ clusterPointToGeoJSON,+ clusterSort,+ getClusterPoints,+ getClusters,+} from './cluster';+// ---------------------------------------------------------------------------+// Mock external dependencies+// ---------------------------------------------------------------------------+jest.mock('../util', () => ({+ crossesDateLine: jest.fn(),+ getOverDateLineCoordinates: jest.fn(),+}));++import { crossesDateLine, getOverDateLineCoordinates } from '../util';++// ---------------------------------------------------------------------------+// Shared fixtures+// ---------------------------------------------------------------------------+const geoProj = { selected: { id: 'geographic' } };+const polarProj = { selected: { id: 'arctic' } };++const makeMapMock = (zoom = 3) => ({+ getView: () => ({ getZoom: () => zoom }),+});++// A minimal set of geometry entries used across getClusters tests+const makeGeometry = () => [+ { date: '2019-09-22T00:00:00Z', coordinates: [10, 40], magnitudeUnit: 'kts', magnitudeValue: 50 },+ { date: '2019-09-23T00:00:00Z', coordinates: [12, 41], magnitudeUnit: 'kts', magnitudeValue: 55 },+ { date: '2019-09-24T00:00:00Z', coordinates: [14, 42], magnitudeUnit: 'kts', magnitudeValue: 60 },+];++// ===========================================================================+// naturalEventsClusterCreateObject+// ===========================================================================+describe('naturalEventsClusterCreateObject', () => {+ // Branch: geographic → radius 0+ it('creates a Supercluster with radius 0 for geographic projection', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ expect(cluster.options.radius).toBe(0);+ expect(cluster.options.maxZoom).toBe(12);+ });++ // Branch: non-geographic → radius 60+ it('creates a Supercluster with radius 60 for non-geographic (polar) projection', () => {+ const cluster = naturalEventsClusterCreateObject(polarProj);+ expect(cluster.options.radius).toBe(60);+ expect(cluster.options.maxZoom).toBe(12);+ });++ it('map function returns startDate and endDate from props.date', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ const result = cluster.options.map({ date: '2019-09-24' });+ expect(result).toEqual({ startDate: '2019-09-24', endDate: '2019-09-24' });+ });++ describe('reduce function', () => {+ // Branch: !pastEndDate → set both start and end to newDate+ it('sets startDate and endDate when accumulator has no endDate yet', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ const accumulator = { startDate: undefined, endDate: undefined };+ cluster.options.reduce(accumulator, { startDate: '2019-09-24' });+ expect(accumulator.startDate).toBe('2019-09-24');+ expect(accumulator.endDate).toBe('2019-09-24');+ });++ // Branch: newDate is earlier than pastStartDate → update startDate+ it('updates startDate when newDate is earlier than the current startDate', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ const accumulator = { startDate: '2019-09-24', endDate: '2019-09-26' };+ cluster.options.reduce(accumulator, { startDate: '2019-09-22' });+ expect(accumulator.startDate).toBe('2019-09-22');+ expect(accumulator.endDate).toBe('2019-09-26'); // unchanged+ });++ // Branch: newDate is later than pastStartDate → keep pastStartDate+ it('keeps startDate when newDate is NOT earlier than the current startDate', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ const accumulator = { startDate: '2019-09-22', endDate: '2019-09-26' };+ cluster.options.reduce(accumulator, { startDate: '2019-09-23' });+ expect(accumulator.startDate).toBe('2019-09-22'); // unchanged+ });++ // Branch: newDate is later than pastEndDate → update endDate+ it('updates endDate when newDate is later than the current endDate', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ const accumulator = { startDate: '2019-09-22', endDate: '2019-09-24' };+ cluster.options.reduce(accumulator, { startDate: '2019-09-26' });+ expect(accumulator.endDate).toBe('2019-09-26');+ });++ // Branch: newDate is earlier than pastEndDate → keep pastEndDate+ it('keeps endDate when newDate is NOT later than the current endDate', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ const accumulator = { startDate: '2019-09-22', endDate: '2019-09-26' };+ cluster.options.reduce(accumulator, { startDate: '2019-09-23' });+ expect(accumulator.endDate).toBe('2019-09-26'); // unchanged+ });+ });++ it('setPolar returns radius 30 and maxZoom 7', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ expect(cluster.options.setPolar()).toEqual({ radius: 30, maxZoom: 7 });+ });++ it('setGeo returns radius 0 and maxZoom 12', () => {+ const cluster = naturalEventsClusterCreateObject(geoProj);+ expect(cluster.options.setGeo()).toEqual({ radius: 0, maxZoom: 12 });+ });+});++// ===========================================================================+// clusterPointToGeoJSON+// ===========================================================================+describe('clusterPointToGeoJSON', () => {+ it('returns a correctly shaped geoJSON Feature', () => {+ const result = clusterPointToGeoJSON(+ 'EONET_001',+ [10, 40],+ '2019-09-24',+ { magnitudeUnit: 'kts', magnitudeValue: 55 },+ );++ expect(result.type).toBe('Feature');+ expect(result.properties.id).toBe('EONET_001-2019-09-24');+ expect(result.properties.event_id).toBe('EONET_001');+ expect(result.properties.date).toBe('2019-09-24');+ expect(result.geometry.type).toBe('Point');+ expect(result.geometry.coordinates).toEqual([10, 40]);+ expect(result.geometry.magnitudeUnit).toBe('kts');+ expect(result.geometry.magnitudeValue).toBe(55);+ });++ it('handles undefined magnitude values gracefully', () => {+ const result = clusterPointToGeoJSON(+ 'EONET_002',+ [0, 0],+ '2019-09-25',+ { magnitudeUnit: undefined, magnitudeValue: undefined },+ );+ expect(result.geometry.magnitudeUnit).toBeUndefined();+ expect(result.geometry.magnitudeValue).toBeUndefined();+ });+});++// ===========================================================================+// clusterSort+// ===========================================================================+describe('clusterSort', () => {+ // Branch: uses properties.date for sorting+ it('sorts an array of cluster points by properties.date descending', () => {+ const input = [+ { properties: { date: '2019-09-22' } },+ { properties: { date: '2019-09-24' } },+ { properties: { date: '2019-09-23' } },+ ];+ const sorted = clusterSort(input);+ expect(sorted[0].properties.date).toBe('2019-09-24');+ expect(sorted[1].properties.date).toBe('2019-09-23');+ expect(sorted[2].properties.date).toBe('2019-09-22');+ });++ // Branch: falls back to properties.startDate when properties.date is absent+ it('falls back to properties.startDate when properties.date is absent', () => {+ const input = [+ { properties: { startDate: '2019-09-22' } },+ { properties: { startDate: '2019-09-24' } },+ { properties: { startDate: '2019-09-23' } },+ ];+ const sorted = clusterSort(input);+ expect(sorted[0].properties.startDate).toBe('2019-09-24');+ expect(sorted[2].properties.startDate).toBe('2019-09-22');+ });++ // Mixed: some entries use date, some use startDate+ it('handles a mix of date and startDate properties', () => {+ const input = [+ { properties: { date: '2019-09-22' } },+ { properties: { startDate: '2019-09-25' } },+ { properties: { date: '2019-09-24' } },+ ];+ const sorted = clusterSort(input);+ expect(sorted[0].properties.startDate).toBe('2019-09-25');+ expect(sorted[2].properties.date).toBe('2019-09-22');+ });++ it('returns a single-element array unchanged', () => {+ const input = [{ properties: { date: '2019-09-24' } }];+ expect(clusterSort(input)).toHaveLength(1);+ });+});++// ===========================================================================+// getClusterPoints+// ===========================================================================+describe('getClusterPoints', () => {+ it('loads points into the supercluster object and returns clusters', () => {+ const mockSuperCluster = {+ load: jest.fn(),+ getClusters: jest.fn().mockReturnValue([{ type: 'Feature' }]),+ };+ const points = [{ type: 'Feature', geometry: { coordinates: [10, 40] } }];+ const result = getClusterPoints(mockSuperCluster, points, 3.6, [-180, -90, 180, 90]);++ expect(mockSuperCluster.load).toHaveBeenCalledWith(points);+ // lodashRound(3.6) === 4+ expect(mockSuperCluster.getClusters).toHaveBeenCalledWith([-180, -90, 180, 90], 4);+ expect(result).toEqual([{ type: 'Feature' }]);+ });++ it('rounds the zoom level before passing it to getClusters', () => {+ const mockSuperCluster = {+ load: jest.fn(),+ getClusters: jest.fn().mockReturnValue([]),+ };+ getClusterPoints(mockSuperCluster, [], 2.1, [-180, -90, 180, 90]);+ // lodashRound(2.1) === 2+ expect(mockSuperCluster.getClusters).toHaveBeenCalledWith([-180, -90, 180, 90], 2);+ });+});++// ===========================================================================+// getClusters+// ===========================================================================+describe('getClusters', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ // Default: no dateline crossing+ crossesDateLine.mockReturnValue(false);+ getOverDateLineCoordinates.mockImplementation((coords) => coords);+ });++ const eventId = 'EONET_001';++ // ---------------------------------------------------------------------------+ // Geographic projection+ // ---------------------------------------------------------------------------+ describe('geographic projection', () => {+ it('returns clusters, firstClusterObj, and secondClusterObj', () => {+ const geometry = makeGeometry();+ const result = getClusters(+ { geometry, id: eventId },+ geoProj,+ '2019-09-23',+ makeMapMock(),+ );++ expect(result).toHaveProperty('clusters');+ expect(result).toHaveProperty('firstClusterObj');+ expect(result).toHaveProperty('secondClusterObj');+ });++ it('uses geographic extent [-250, -90, 250, 90]', () => {+ const geometry = makeGeometry();+ // Spy on the real Supercluster getClusters method to capture extent+ const result = getClusters(+ { geometry, id: eventId },+ geoProj,+ '2019-09-23',+ makeMapMock(),+ );+ // Clusters should be a non-empty array+ expect(Array.isArray(result.clusters)).toBe(true);+ });++ it('places the selected point in the clusters array', () => {+ const geometry = makeGeometry();+ const result = getClusters(+ { geometry, id: eventId },+ geoProj,+ '2019-09-23',+ makeMapMock(),+ );+ const dates = result.clusters.map(+ (c) => c.properties.date || c.properties.startDate,+ );+ expect(dates).toContain('2019-09-23');+ });++ it('sorts clusters in descending date order', () => {+ const geometry = makeGeometry();+ const { clusters } = getClusters(+ { geometry, id: eventId },+ geoProj,+ '2019-09-23',+ makeMapMock(),+ );+ const dates = clusters.map(+ (c) => c.properties.date || c.properties.startDate,+ );+ // First date should be the most recent+ expect(new Date(dates[0]) >= new Date(dates[dates.length - 1])).toBe(true);+ });++ it('groups points before the selected date into geoJSONPointsBeforeSelected', () => {+ const geometry = makeGeometry();+ // selectedDate is the last entry, so two points go "before"+ const { clusters } = getClusters(+ { geometry, id: eventId },+ geoProj,+ '2019-09-24',+ makeMapMock(),+ );+ // All three dates should be represented+ expect(clusters.length).toBeGreaterThanOrEqual(1);+ });++ it('groups points after the selected date into geoJSONPointsAfterSelected', () => {+ const geometry = makeGeometry();+ // selectedDate is the first entry, so two points go "after"+ const { clusters } = getClusters(+ { geometry, id: eventId },+ geoProj,+ '2019-09-22',+ makeMapMock(),+ );+ expect(clusters.length).toBeGreaterThanOrEqual(1);+ });++ // Branch: isOverDateline = true → getOverDateLineCoordinates is called+ it('replaces coordinates when a point crosses the dateline', () => {+ crossesDateLine.mockReturnValue(true);+ const shiftedCoords = [170, 40];+ getOverDateLineCoordinates.mockReturnValue(shiftedCoords);++ const geometry = makeGeometry();+ const { clusters } = getClusters(+ { geometry, id: eventId },+ geoProj,+ '2019-09-23',+ makeMapMock(),+ );++ expect(getOverDateLineCoordinates).toHaveBeenCalled();+ expect(Array.isArray(clusters)).toBe(true);+ });+ });++ // ---------------------------------------------------------------------------+ // Polar projection+ // ---------------------------------------------------------------------------+ describe('polar projection', () => {+ it('uses polar extent [-180, -90, 180, 90] for non-geographic projection', () => {+ const geometry = makeGeometry();+ const result = getClusters(+ { geometry, id: eventId },+ polarProj,+ '2019-09-23',+ makeMapMock(),+ );+ expect(Array.isArray(result.clusters)).toBe(true);+ });++ // Branch: isOverDateline is always false for non-geographic → crossesDateLine never called+ it('never calls crossesDateLine for polar projection', () => {+ const geometry = makeGeometry();+ getClusters(+ { geometry, id: eventId },+ polarProj,+ '2019-09-23',+ makeMapMock(),+ );+ expect(crossesDateLine).not.toHaveBeenCalled();+ });++ // Branch: proj.selected.id !== 'geographic' → setPolar called on cluster objects+ it('calls setPolar on both cluster objects for polar projection', () => {+ const geometry = makeGeometry();+ const { firstClusterObj, secondClusterObj } = getClusters(+ { geometry, id: eventId },+ polarProj,+ '2019-09-23',+ makeMapMock(),+ );+ // After getClusters runs, the options should reflect polar settings+ expect(firstClusterObj.options.radius).toBe(60); // created with polar (radius 60)+ expect(secondClusterObj.options.radius).toBe(60);+ });+ });++ // ---------------------------------------------------------------------------+ // Zoom level is forwarded correctly+ // ---------------------------------------------------------------------------+ it('reads zoom from map.getView().getZoom()', () => {+ const getZoom = jest.fn().mockReturnValue(5);+ const map = { getView: () => ({ getZoom }) };+ const geometry = makeGeometry();+ getClusters({ geometry, id: eventId }, geoProj, '2019-09-23', map);+ expect(getZoom).toHaveBeenCalled();+ });});diff --git a/web/js/map/natural-events/event-markers.test.js b/web/js/map/natural-events/event-markers.test.jsindex d3736265f..45b554a7d 100644--- a/web/js/map/natural-events/event-markers.test.js+++ b/web/js/map/natural-events/event-markers.test.js@@ -1,3 +1,698 @@-test('event-markers map test', () => {+// event-markers.test.js+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('react-dom/client', () => ({+ createRoot: jest.fn(() => ({ render: jest.fn() })),+}));++jest.mock('ol/Overlay', () =>+ jest.fn().mockImplementation((opts) => ({+ element: null,+ setPosition: jest.fn(),+ setMap: jest.fn(),+ ...opts,+ })),+);++jest.mock('ol/Feature', () => jest.fn().mockImplementation(() => ({})));++jest.mock('ol/style/Style', () => jest.fn().mockImplementation(() => ({})));++jest.mock('ol/style/Stroke', () => jest.fn().mockImplementation(() => ({})));++jest.mock('ol/layer/Vector', () =>+ jest.fn().mockImplementation(() => ({+ setMap: jest.fn(),+ })),+);++jest.mock('ol/source/Vector', () => jest.fn().mockImplementation(() => ({})));++jest.mock('ol/geom/Polygon', () =>+ jest.fn().mockImplementation(() => ({+ transform: jest.fn().mockReturnThis(),+ })),+);++jest.mock('ol/extent', () => ({+ boundingExtent: jest.fn(() => [0, 0, 10, 10]),+ getCenter: jest.fn(() => [5, 5]),+}));++jest.mock('ol/proj', () => ({+ transform: jest.fn((coords) => coords),+}));++jest.mock('googleTagManager', () => ({ pushEvent: jest.fn() }));++jest.mock('../../components/sidebar/event-icon', () => () => null);++jest.mock('../../modules/natural-events/actions', () => ({+ selectEvent: jest.fn(),+ highlightEvent: jest.fn(),+ unHighlightEvent: jest.fn(),+}));++jest.mock('../../modules/natural-events/util', () => ({+ getDefaultEventDate: jest.fn(() => '2023-01-01'),+}));++jest.mock('../../modules/natural-events/selectors', () => ({+ getFilteredEvents: jest.fn(() => []),+}));++jest.mock('../../modules/map/constants', () => ({+ CRS: {+ GEOGRAPHIC: 'EPSG:4326',+ ARCTIC: 'EPSG:3413',+ ANTARCTIC: 'EPSG:3031',+ },+}));++// ---------------------------------------------------------------------------+// Imports+// ---------------------------------------------------------------------------+import googleTagManager from 'googleTagManager';+import { getDefaultEventDate } from '../../modules/natural-events/util';+import * as olExtent from 'ol/extent';+import * as olProj from 'ol/proj';++import ConnectedEventMarkers from './event-markers';++const EventMarkers = ConnectedEventMarkers.WrappedComponent;++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const buildMap = () => ({+ addOverlay: jest.fn(),+ removeOverlay: jest.fn(),+ addLayer: jest.fn(),+ removeLayer: jest.fn(),+ getView: jest.fn(() => ({ changed: jest.fn() })),+ renderSync: jest.fn(),+});++const buildMapUi = (supportsPassive = false) => ({ supportsPassive });++const geographicProj = () => ({ selected: { id: 'geographic', crs: 'EPSG:4326' } });+const polarProj = () => ({ selected: { id: 'arctic', crs: 'EPSG:3413' } });++const buildPointEvent = (overrides = {}) => ({+ id: 'event-1',+ title: 'Test Wildfire',+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ geometry: [{ type: 'Point', date: '2023-01-01T00:00:00Z', coordinates: [10, 20] }],+ ...overrides,+});++const buildPolygonEvent = (overrides = {}) => ({+ id: 'event-2',+ title: 'Test Flood',+ categories: [{ id: 'floods', title: 'Floods' }],+ geometry: [+ {+ type: 'Polygon',+ date: '2023-01-01T00:00:00Z',+ coordinates: [[[0, 0], [0, 10], [10, 10], [10, 0], [0, 0]]],+ },+ ],+ ...overrides,+});++const defaultProps = () => ({+ eventsData: [],+ eventsDataIsLoading: false,+ map: buildMap(),+ mapUi: buildMapUi(),+ proj: geographicProj(),+ selectedEvent: null,+ selectedDate: '2023-01-01',+ isMobile: false,+ isAnimatingToEvent: false,+ selectEvent: jest.fn(),+ highlightEvent: jest.fn(),+ unHighlightEvent: jest.fn(),+});++const createInstance = (props) => {+ const instance = new EventMarkers(props);+ instance.props = props;+ instance.state = { markers: [] };+ instance.setState = jest.fn((updater, callback) => {+ const next = typeof updater === 'function' ? updater(instance.state) : updater;+ instance.state = { ...instance.state, ...next };+ if (callback) callback();+ });+ return instance;+};++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe('EventMarkers', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ getDefaultEventDate.mockReturnValue('2023-01-01');+ });++ // -------------------------------------------------------------------------+ // componentDidMount+ // -------------------------------------------------------------------------+ describe('componentDidMount', () => {+ it('calls draw() when eventsDataIsLoading is false', () => {+ const instance = createInstance(defaultProps());+ const drawSpy = jest.spyOn(instance, 'draw').mockImplementation(() => {});+ instance.componentDidMount();+ expect(drawSpy).toHaveBeenCalledTimes(1);+ });++ it('does NOT call draw() when eventsDataIsLoading is true', () => {+ const instance = createInstance({ ...defaultProps(), eventsDataIsLoading: true });+ const drawSpy = jest.spyOn(instance, 'draw').mockImplementation(() => {});+ instance.componentDidMount();+ expect(drawSpy).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // componentDidUpdate+ // -------------------------------------------------------------------------+ describe('componentDidUpdate', () => {+ let instance;+ let removeSpy;+ let drawSpy;++ beforeEach(() => {+ instance = createInstance(defaultProps());+ removeSpy = jest.spyOn(instance, 'remove').mockImplementation(() => {});+ drawSpy = jest.spyOn(instance, 'draw').mockImplementation(() => {});+ });++ it('calls remove() + draw() when loading transitions from true → false', () => {+ instance.props = { ...defaultProps(), eventsDataIsLoading: false };+ instance.componentDidUpdate({ ...defaultProps(), eventsDataIsLoading: true });+ expect(removeSpy).toHaveBeenCalled();+ expect(drawSpy).toHaveBeenCalled();+ });++ it('calls remove() + draw() when the projection changes', () => {+ const prevProj = geographicProj();+ const nextProj = polarProj();+ instance.props = { ...defaultProps(), proj: nextProj };+ instance.componentDidUpdate({ ...defaultProps(), proj: prevProj });+ expect(removeSpy).toHaveBeenCalled();+ expect(drawSpy).toHaveBeenCalled();+ });++ it('calls remove() + draw() when animation finishes (true → false)', () => {+ instance.props = { ...defaultProps(), isAnimatingToEvent: false };+ instance.componentDidUpdate({ ...defaultProps(), isAnimatingToEvent: true });+ expect(removeSpy).toHaveBeenCalled();+ expect(drawSpy).toHaveBeenCalled();+ });++ it('calls remove() + draw() when selectedEvent changes', () => {+ const prevEvent = { id: 'event-old' };+ const nextEvent = { id: 'event-new' };+ instance.props = { ...defaultProps(), selectedEvent: nextEvent };+ instance.componentDidUpdate({ ...defaultProps(), selectedEvent: prevEvent });+ expect(removeSpy).toHaveBeenCalled();+ expect(drawSpy).toHaveBeenCalled();+ });++ it('does NOT call remove() or draw() when nothing relevant changes', () => {+ const props = defaultProps();+ instance.props = { ...props };+ instance.componentDidUpdate({ ...props });+ expect(removeSpy).not.toHaveBeenCalled();+ expect(drawSpy).not.toHaveBeenCalled();+ });++ it('does NOT call remove() or draw() when selectedEvent stays null', () => {+ // Both current and prev props must share the same proj reference so+ // projChange is false, and eventsDataIsLoading/isAnimatingToEvent must+ // also be unchanged — only selectedEvent (null → null) differs.+ const sharedProj = geographicProj();+ instance.props = { ...defaultProps(), proj: sharedProj, selectedEvent: null };+ instance.componentDidUpdate({ ...defaultProps(), proj: sharedProj, selectedEvent: null });+ expect(removeSpy).not.toHaveBeenCalled();+ expect(drawSpy).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // componentWillUnmount+ // -------------------------------------------------------------------------+ describe('componentWillUnmount', () => {+ it('calls remove() when the component unmounts', () => {+ const instance = createInstance(defaultProps());+ const removeSpy = jest.spyOn(instance, 'remove').mockImplementation(() => {});+ instance.componentWillUnmount();+ expect(removeSpy).toHaveBeenCalledTimes(1);+ });+ });++ // -------------------------------------------------------------------------+ // render+ // -------------------------------------------------------------------------+ describe('render', () => {+ it('returns null', () => {+ const instance = createInstance(defaultProps());+ expect(instance.render()).toBeNull();+ });+ });++ // -------------------------------------------------------------------------+ // draw() – guard clauses+ // -------------------------------------------------------------------------+ describe('draw() – guard clauses', () => {+ it('returns null when eventsData is null', () => {+ const instance = createInstance({ ...defaultProps(), eventsData: null });+ expect(instance.draw()).toBeNull();+ });++ it('returns null when eventsData is an empty array', () => {+ const instance = createInstance({ ...defaultProps(), eventsData: [] });+ expect(instance.draw()).toBeNull();+ });+ });++ // -------------------------------------------------------------------------+ // draw() – geographic projection, Point geometry+ // -------------------------------------------------------------------------+ describe('draw() – geographic projection, Point geometry', () => {+ it('adds a pin overlay to the map', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPointEvent()],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(map.addOverlay).toHaveBeenCalled();+ });++ it('sets the correct pin position from Point coordinates', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPointEvent()],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ const overlay = map.addOverlay.mock.calls[0][0];+ expect(overlay.setPosition).toHaveBeenCalledWith([10, 20]);+ });++ it('falls back to a default category when the category id is not in the icons list', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPointEvent({ categories: [{ id: 'unknown', title: 'Unknown' }] })],+ selectedEvent: { id: 'other-event' },+ });+ expect(() => instance.draw()).not.toThrow();+ expect(map.addOverlay).toHaveBeenCalled();+ });++ it('uses selectedEvent.date for geometry lookup when the event is selected', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPointEvent()],+ selectedEvent: { id: 'event-1', date: '2023-02-15' },+ });+ instance.draw();+ expect(map.addOverlay).toHaveBeenCalled();+ });++ it('calls map.getView().changed() and map.renderSync() via the setState callback', () => {+ const mockChanged = jest.fn();+ const map = {+ ...buildMap(),+ getView: jest.fn(() => ({ changed: mockChanged })),+ };+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPointEvent()],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(mockChanged).toHaveBeenCalled();+ expect(map.renderSync).toHaveBeenCalled();+ });++ it('hides tooltips when isMobile is true', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ isMobile: true,+ eventsData: [buildPointEvent()],+ selectedEvent: { id: 'other-event' },+ });+ expect(() => instance.draw()).not.toThrow();+ });++ it('hides tooltips when isAnimatingToEvent is true', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ isAnimatingToEvent: true,+ eventsData: [buildPointEvent()],+ selectedEvent: { id: 'other-event' },+ });+ expect(() => instance.draw()).not.toThrow();+ });+ });++ // -------------------------------------------------------------------------+ // draw() – geographic projection, Polygon geometry+ // -------------------------------------------------------------------------+ describe('draw() – geographic projection, Polygon geometry', () => {+ it('computes the bounding-box centre for a Polygon event', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPolygonEvent()],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(olExtent.boundingExtent).toHaveBeenCalled();+ expect(olExtent.getCenter).toHaveBeenCalled();+ expect(map.addOverlay).toHaveBeenCalled();+ });++ it('adds a bounding-box layer when the Polygon event IS selected', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPolygonEvent()],+ selectedEvent: { id: 'event-2' },+ });+ instance.draw();+ expect(map.addLayer).toHaveBeenCalled();+ });++ it('does NOT add a bounding-box layer when the Polygon event is NOT selected', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPolygonEvent()],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(map.addLayer).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // draw() – polar projection+ // -------------------------------------------------------------------------+ describe('draw() – polar projection', () => {+ it('transforms Point coordinates for a polar projection', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ proj: polarProj(),+ eventsData: [buildPointEvent()],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(olProj.transform).toHaveBeenCalled();+ expect(map.addOverlay).toHaveBeenCalled();+ });++ it('handles a Polygon in polar projection and adds bounding-box when selected', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ proj: polarProj(),+ eventsData: [buildPolygonEvent()],+ selectedEvent: { id: 'event-2' },+ });+ instance.draw();+ expect(map.addLayer).toHaveBeenCalled();+ expect(olExtent.getCenter).toHaveBeenCalled();+ });++ it('handles a Polygon in polar projection WITHOUT bounding-box when not selected', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ proj: polarProj(),+ eventsData: [buildPolygonEvent()],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(map.addLayer).not.toHaveBeenCalled();+ expect(map.addOverlay).toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // draw() – geometry edge cases+ // -------------------------------------------------------------------------+ describe('draw() – geometry edge cases', () => {+ it('skips adding an overlay when the event has no geometry entries', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPointEvent({ geometry: [] })],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(map.addOverlay).not.toHaveBeenCalled();+ });++ it('falls back to geometry[0] when no geometry matches the resolved date', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [buildPointEvent({+ geometry: [{ type: 'Point', date: '2022-06-15T00:00:00Z', coordinates: [5, 15] }],+ })],+ selectedEvent: { id: 'other-event' },+ });+ instance.draw();+ expect(map.addOverlay).toHaveBeenCalled();+ });++ it('creates a marker overlay for each event in eventsData', () => {+ const map = buildMap();+ const instance = createInstance({+ ...defaultProps(),+ map,+ eventsData: [+ buildPointEvent({ id: 'event-1' }),+ buildPointEvent({ id: 'event-2', categories: [{ id: 'volcanoes', title: 'Volcanoes' }] }),+ buildPolygonEvent({ id: 'event-3' }),+ ],+ selectedEvent: { id: 'event-1' },+ });+ instance.draw();+ expect(map.addOverlay).toHaveBeenCalledTimes(3);+ });+ });++ // -------------------------------------------------------------------------+ // remove()+ // -------------------------------------------------------------------------+ describe('remove()', () => {+ it('is a no-op when the markers array is empty', () => {+ const map = buildMap();+ const instance = createInstance({ ...defaultProps(), map });+ instance.remove();+ expect(map.removeOverlay).not.toHaveBeenCalled();+ expect(map.removeLayer).not.toHaveBeenCalled();+ });++ it('calls setMap(null) and removeOverlay for a marker pin', () => {+ const map = buildMap();+ const pin = { setMap: jest.fn(), element: document.createElement('div'), setPosition: jest.fn() };+ const instance = createInstance({ ...defaultProps(), map });+ instance.state = { markers: [{ pin }] };+ instance.remove();+ expect(pin.setMap).toHaveBeenCalledWith(null);+ expect(map.removeOverlay).toHaveBeenCalledWith(pin);+ });++ it('calls setMap(null) and removeLayer for a marker boundingBox', () => {+ const map = buildMap();+ const pin = { setMap: jest.fn(), element: document.createElement('div'), setPosition: jest.fn() };+ const boundingBox = { setMap: jest.fn() };+ const instance = createInstance({ ...defaultProps(), map });+ instance.state = { markers: [{ pin, boundingBox }] };+ instance.remove();+ expect(boundingBox.setMap).toHaveBeenCalledWith(null);+ expect(map.removeLayer).toHaveBeenCalledWith(boundingBox);+ });++ it('resets markers state to []', () => {+ const map = buildMap();+ const pin = { setMap: jest.fn(), element: document.createElement('div'), setPosition: jest.fn() };+ const instance = createInstance({ ...defaultProps(), map });+ instance.state = { markers: [{ pin }] };+ instance.remove();+ expect(instance.setState).toHaveBeenCalledWith({ markers: [] });+ });++ it('removes tooltip DOM elements with class event-icon-tooltip', () => {+ const map = buildMap();+ const pin = { setMap: jest.fn(), element: document.createElement('div'), setPosition: jest.fn() };+ const tooltip = document.createElement('div');+ tooltip.className = 'event-icon-tooltip';+ document.body.appendChild(tooltip);+ const tooltipRemoveSpy = jest.spyOn(tooltip, 'remove');++ const instance = createInstance({ ...defaultProps(), map });+ instance.state = { markers: [{ pin }] };+ instance.remove();++ expect(tooltipRemoveSpy).toHaveBeenCalled();+ tooltip.parentNode?.removeChild(tooltip);+ });+ });++ // -------------------------------------------------------------------------+ // addInteractions()+ // -------------------------------------------------------------------------+ describe('addInteractions()', () => {+ const setup = (overrides = {}) => {+ const selectEvent = jest.fn();+ const highlightEvent = jest.fn();+ const unHighlightEvent = jest.fn();+ const instance = createInstance({+ ...defaultProps(),+ selectEvent,+ highlightEvent,+ unHighlightEvent,+ mapUi: buildMapUi(overrides.supportsPassive || false),+ });+ const pinEl = document.createElement('div');+ document.body.appendChild(pinEl);+ const event = buildPointEvent();+ const date = '2023-01-01';+ const isSelected = overrides.isSelected || false;+ instance.addInteractions({ pin: { element: pinEl } }, event, date, isSelected);+ return { pinEl, selectEvent, highlightEvent, unHighlightEvent, event, date };+ };++ afterEach(() => {+ document.body.innerHTML = '';+ });++ it('calls highlightEvent on mouseenter', () => {+ const { pinEl, highlightEvent, event, date } = setup();+ pinEl.dispatchEvent(new MouseEvent('mouseenter'));+ expect(highlightEvent).toHaveBeenCalledWith(event.id, date);+ });++ it('calls unHighlightEvent on mouseleave', () => {+ const { pinEl, unHighlightEvent } = setup();+ pinEl.dispatchEvent(new MouseEvent('mouseleave'));+ expect(unHighlightEvent).toHaveBeenCalled();+ });++ it('calls selectEvent on click when not selected and not dragged', () => {+ const { pinEl, selectEvent, event, date } = setup();+ pinEl.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(selectEvent).toHaveBeenCalledWith(event.id, date);+ });++ it('does NOT call selectEvent when the event is already selected', () => {+ const { pinEl, selectEvent } = setup({ isSelected: true });+ pinEl.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(selectEvent).not.toHaveBeenCalled();+ });++ it('does NOT call selectEvent after more than 2 mousemove events (drag)', () => {+ const { pinEl, selectEvent } = setup();+ pinEl.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(selectEvent).not.toHaveBeenCalled();+ });++ it('pushes a Google Tag Manager event on successful selection', () => {+ const { pinEl } = setup();+ pinEl.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith(+ expect.objectContaining({ event: 'natural_event_selected' }),+ );+ });++ it('resets willSelect and moveCount on a new mousedown after a drag', () => {+ const { pinEl, selectEvent } = setup();+ pinEl.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));+ // A fresh mousedown resets willSelect and moveCount+ pinEl.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));+ pinEl.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ expect(selectEvent).toHaveBeenCalled();+ });++ it('fires selectEvent on touchend when not selected and not dragged', () => {+ const { pinEl, selectEvent, event, date } = setup();+ pinEl.dispatchEvent(new TouchEvent('touchstart', { bubbles: true }));+ pinEl.dispatchEvent(new TouchEvent('touchend', { bubbles: true }));+ expect(selectEvent).toHaveBeenCalledWith(event.id, date);+ });++ it('uses { passive: true } listener option when supportsPassive is true', () => {+ const spy = jest.spyOn(HTMLElement.prototype, 'addEventListener');+ setup({ supportsPassive: true });+ const passiveCalls = spy.mock.calls.filter(([, , opts]) => opts?.passive === true);+ expect(passiveCalls.length).toBeGreaterThan(0);+ spy.mockRestore();+ });++ it('uses false as the listener option when supportsPassive is false', () => {+ const spy = jest.spyOn(HTMLElement.prototype, 'addEventListener');+ setup({ supportsPassive: false });+ const falseCalls = spy.mock.calls.filter(([, , opts]) => opts === false);+ expect(falseCalls.length).toBeGreaterThan(0);+ spy.mockRestore();+ });+ });++ // -------------------------------------------------------------------------+ // Redux connect wiring smoke test+ // -------------------------------------------------------------------------+ describe('redux connect wiring', () => {+ it('exports a connected component as the default export', () => {+ expect(ConnectedEventMarkers).toBeDefined();+ });++ it('exposes the unwrapped class as WrappedComponent', () => {+ expect(ConnectedEventMarkers.WrappedComponent).toBe(EventMarkers);+ });+ });});diff --git a/web/js/map/natural-events/event-track.test.js b/web/js/map/natural-events/event-track.test.jsindex 21476edec..4c8c7f8f9 100644--- a/web/js/map/natural-events/event-track.test.js+++ b/web/js/map/natural-events/event-track.test.js@@ -1,3 +1,1041 @@-test('event-track map test', () => {+import { render, act } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('ol/extent', () => ({+ containsCoordinate: jest.fn(() => true),+}));++jest.mock('ol/proj', () => ({+ transform: jest.fn((coords) => coords),+}));++jest.mock('lodash', () => ({+ each: jest.fn((arr, fn) => { if (arr) arr.forEach(fn); }),+ debounce: jest.fn((fn) => {+ const debounced = (...args) => fn(...args);+ debounced.cancel = jest.fn();+ return debounced;+ }),+}));++jest.mock('./cluster', () => ({+ getClusters: jest.fn(() => ({+ clusters: [],+ firstClusterObj: {},+ secondClusterObj: {},+ })),+}));++jest.mock('./util', () => ({+ getTrackLines: jest.fn(() => ({ getId: jest.fn(() => 'track-line-1'), getPosition: jest.fn(() => [0, 0]) })),+ getTrackPoint: jest.fn(() => ({ getId: jest.fn(() => 'track-point-1'), getPosition: jest.fn(() => [0, 0]) })),+ getArrows: jest.fn(() => ({ getId: jest.fn(() => 'arrow-1'), getPosition: jest.fn(() => [0, 0]) })),+ getClusterPointEl: jest.fn(() => ({ getId: jest.fn(() => 'cluster-1'), getPosition: jest.fn(() => [0, 0]) })),+}));++jest.mock('../../modules/natural-events/actions', () => ({+ selectEvent: jest.fn((id, date) => ({ type: 'SELECT_EVENT', id, date })),+ highlightEvent: jest.fn((id, date) => ({ type: 'HIGHLIGHT_EVENT', id, date })),+ unHighlightEvent: jest.fn(() => ({ type: 'UN_HIGHLIGHT_EVENT' })),+}));++jest.mock('../../modules/natural-events/selectors', () => ({+ getFilteredEvents: jest.fn((state) => state.events.filteredEvents || []),+}));++jest.mock('../../modules/natural-events/util', () => ({+ getDefaultEventDate: jest.fn(() => '2023-01-01'),+}));++jest.mock('../../modules/map/constants', () => ({+ CRS: { GEOGRAPHIC: 'EPSG:4326' },+}));++jest.mock('../../util/customHooks', () => jest.fn((val) => val));++// ---------------------------------------------------------------------------+// Imports+// ---------------------------------------------------------------------------+import EventTrack from './event-track';+import { getClusters } from './cluster';+import { getTrackLines, getTrackPoint, getArrows } from './util';+import * as olExtent from 'ol/extent';++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const mockStore = configureMockStore([]);++const buildOverlay = (id, position = [0, 0]) => ({+ getId: jest.fn(() => id),+ getPosition: jest.fn(() => position),+});++/**+ * Build a map stub where getView() always returns the SAME view object.+ * This is critical — if getView() returns a new object each call the spy+ * set up in the test and the one called inside the component will differ.+ */+const buildMap = (overlays = []) => {+ const overlayList = [...overlays];+ const view = {+ on: jest.fn(),+ un: jest.fn(),+ calculateExtent: jest.fn(() => [-180, -90, 180, 90]),+ };+ return {+ addOverlay: jest.fn(),+ removeOverlay: jest.fn(),+ getOverlayById: jest.fn((id) => overlayList.find((o) => o.getId() === id) || null),+ getOverlays: jest.fn(() => ({ forEach: jest.fn((fn) => overlayList.forEach(fn)) })),+ // Always return the same view instance+ getView: jest.fn(() => view),+ };+};++const buildEvent = (overrides = {}) => ({+ id: 'event-1',+ title: 'Test Event',+ categories: [{ id: 'wildfires' }],+ geometry: [+ { date: '2023-01-01T00:00:00Z', coordinates: [10, 20], type: 'Point' },+ { date: '2022-12-31T00:00:00Z', coordinates: [11, 21], type: 'Point' },+ ],+ ...overrides,+});++const defaultState = (overrides = {}) => ({+ events: {+ filteredEvents: [],+ isAnimatingToEvent: false,+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: false,+ highlighted: { id: null },+ },+ animation: { isPlaying: false },+ map: {+ ui: { selected: buildMap() },+ extent: [0, 0, 10, 10],+ },+ proj: { selected: { id: 'geographic', crs: 'EPSG:4326' } },+ date: { selected: '2023-01-01' },+ ...overrides,+});++const renderWithStore = (state = defaultState()) => {+ const store = mockStore(state);+ let result;+ act(() => {+ result = render(+ <Provider store={store}>+ <EventTrack />+ </Provider>,+ );+ });+ return { ...result, store };+};++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe('EventTrack', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ // -------------------------------------------------------------------------+ // Rendering+ // -------------------------------------------------------------------------+ describe('rendering', () => {+ it('renders null into the DOM', () => {+ const { container } = renderWithStore();+ expect(container.innerHTML).toBe('');+ });+ });++ // -------------------------------------------------------------------------+ // initialize — map view propertychange listener+ // -------------------------------------------------------------------------+ describe('initialize()', () => {+ it('registers a propertychange listener on the map view on mount', () => {+ const map = buildMap();+ const view = map.getView(); // capture the single shared view instance+ const state = defaultState({ map: { ui: { selected: map }, extent: [0, 0, 10, 10] } });+ renderWithStore(state);+ expect(view.on).toHaveBeenCalledWith('propertychange', expect.any(Function));+ });++ it('does not throw when map is null', () => {+ const state = defaultState({ map: { ui: { selected: null }, extent: [0, 0, 10, 10] } });+ expect(() => renderWithStore(state)).not.toThrow();+ });+ });++ // -------------------------------------------------------------------------+ // Cleanup on unmount+ // -------------------------------------------------------------------------+ describe('unmount cleanup', () => {+ it('unregisters the propertychange listener on unmount', () => {+ const map = buildMap();+ const view = map.getView(); // capture the single shared view instance+ const state = defaultState({ map: { ui: { selected: map }, extent: [0, 0, 10, 10] } });+ const { unmount } = renderWithStore(state);+ act(() => { unmount(); });+ expect(view.un).toHaveBeenCalledWith('propertychange', expect.any(Function));+ });++ it('calls removeAllTracks on unmount when showAllTracks is true', () => {+ const map = buildMap();+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ showAllTracks: true,+ filteredEvents: [buildEvent()],+ },+ });+ const { unmount } = renderWithStore(state);+ act(() => { unmount(); });+ expect(map.removeOverlay).toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // addOverlayIfIsVisible+ // -------------------------------------------------------------------------+ describe('addOverlayIfIsVisible()', () => {+ it('adds a point overlay to the map when the position is within the extent', () => {+ const map = buildMap();+ olExtent.containsCoordinate.mockReturnValue(true);++ const point = buildOverlay('point-1', [5, 5]);+ getTrackPoint.mockReturnValue(point);++ getClusters.mockReturnValue({+ clusters: [{+ geometry: { coordinates: [5, 5] },+ properties: { date: '2023-01-01', cluster: false },+ }],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });++ renderWithStore(state);+ // addOverlay is called at least once (for the point overlay)+ expect(map.addOverlay).toHaveBeenCalled();+ });++ it('does NOT add a point overlay when the position is outside the extent', () => {+ const map = buildMap();+ // containsCoordinate returns false so addOverlayIfIsVisible skips the call+ olExtent.containsCoordinate.mockReturnValue(false);++ const point = buildOverlay('point-1', [200, 200]);+ getTrackPoint.mockReturnValue(point);++ // getTrackLines returns undefined so the track addOverlay branch is skipped too+ getTrackLines.mockReturnValue(undefined);++ getClusters.mockReturnValue({+ clusters: [{+ geometry: { coordinates: [200, 200] },+ properties: { date: '2023-01-01', cluster: false },+ }],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });++ renderWithStore(state);+ expect(map.addOverlay).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // updateCurrentTrack / debouncedTrackUpdate+ // -------------------------------------------------------------------------+ describe('updateCurrentTrack()', () => {+ it('calls getTracksAndPoints (via getClusters) when a valid selected event exists', () => {+ const map = buildMap();+ const event = buildEvent();+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [event],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });+ renderWithStore(state);+ expect(getClusters).toHaveBeenCalled();+ });++ it('does not call getClusters when selectedEvent has no id', () => {+ const map = buildMap();+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: null, date: null },+ },+ });+ renderWithStore(state);+ expect(getClusters).not.toHaveBeenCalled();+ });++ it('does not call getClusters when the event is not found in eventsData', () => {+ const map = buildMap();+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [],+ selected: { id: 'event-999', date: '2023-01-01' },+ },+ });+ renderWithStore(state);+ expect(getClusters).not.toHaveBeenCalled();+ });++ it('does not build a track for single-geometry events', () => {+ const map = buildMap();+ const singleGeomEvent = buildEvent({+ geometry: [{ date: '2023-01-01T00:00:00Z', coordinates: [10, 20], type: 'Point' }],+ });+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [singleGeomEvent],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });+ renderWithStore(state);+ expect(getClusters).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // updateAllTracks / debouncedUpdateAllTracks+ // -------------------------------------------------------------------------+ describe('updateAllTracks()', () => {+ it('calls getClusters once per multi-geometry event when showAllTracks is true', () => {+ const map = buildMap();+ const events = [buildEvent(), buildEvent({ id: 'event-2' })];+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: events,+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: true,+ },+ });+ renderWithStore(state);+ expect(getClusters).toHaveBeenCalledTimes(events.length);+ });++ it('skips single-geometry events when building all tracks', () => {+ const map = buildMap();+ const events = [+ buildEvent({ id: 'event-multi' }),+ buildEvent({+ id: 'event-single',+ geometry: [{ date: '2023-01-01T00:00:00Z', coordinates: [10, 20], type: 'Point' }],+ }),+ ];+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: events,+ selected: { id: 'event-multi', date: '2023-01-01' },+ showAllTracks: true,+ },+ });+ renderWithStore(state);+ expect(getClusters).toHaveBeenCalledTimes(1);+ });+ });++ // -------------------------------------------------------------------------+ // getTracksAndPoints — arrow and point creation+ // -------------------------------------------------------------------------+ describe('getTracksAndPoints()', () => {+ it('creates arrow overlays between consecutive cluster points', () => {+ const map = buildMap();+ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ { geometry: { coordinates: [1, 1] }, properties: { date: '2022-12-31', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });+ getArrows.mockReturnValue(buildOverlay('arrow-1'));++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });+ renderWithStore(state);+ expect(getArrows).toHaveBeenCalled();+ });++ it('transforms coordinates for polar projections', () => {+ const olProj = require('ol/proj');+ const map = buildMap();+ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ { geometry: { coordinates: [1, 1] }, properties: { date: '2022-12-31', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ proj: { selected: { id: 'arctic', crs: 'EPSG:3413' } },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });+ renderWithStore(state);+ expect(olProj.transform).toHaveBeenCalled();+ });++ it('calls getTrackLines with correct arguments', () => {+ const map = buildMap();+ const event = buildEvent();+ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ { geometry: { coordinates: [1, 1] }, properties: { date: '2022-12-31', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [event],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });+ renderWithStore(state);+ expect(getTrackLines).toHaveBeenCalledWith(+ map,+ expect.any(Array),+ event.id,+ expect.any(String),+ expect.any(Function),+ expect.any(Object),+ );+ });+ });++ // -------------------------------------------------------------------------+ // removeTrack / removeAllTracks+ // -------------------------------------------------------------------------+ describe('removeTrack() and removeAllTracks()', () => {+ it('does not throw when called with a null map', () => {+ const state = defaultState({ map: { ui: { selected: null }, extent: [0, 0, 10, 10] } });+ expect(() => renderWithStore(state)).not.toThrow();+ });++ it('calls map.removeOverlay when removing a track that exists in the overlay mapping', () => {+ const trackOverlay = buildOverlay('track-id-1');+ const map = buildMap([trackOverlay]);++ getTrackLines.mockReturnValue(trackOverlay);+ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: true,+ },+ });++ const { unmount } = renderWithStore(state);+ act(() => { unmount(); });+ expect(map.removeOverlay).toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // isAnimatingToEvent guard+ // -------------------------------------------------------------------------+ describe('isAnimatingToEvent guard', () => {+ it('does not add overlays when isAnimatingToEvent is true', () => {+ const map = buildMap();+ const point = buildOverlay('point-1', [5, 5]);+ getTrackPoint.mockReturnValue(point);+ getTrackLines.mockReturnValue(undefined);+ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [5, 5] }, properties: { date: '2023-01-01', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ isAnimatingToEvent: true,+ },+ });+ renderWithStore(state);+ expect(map.addOverlay).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // isPlaying guard+ // -------------------------------------------------------------------------+ describe('isPlaying guard', () => {+ it('does not trigger track updates when animation is playing', () => {+ const map = buildMap();+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ animation: { isPlaying: true },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ });+ renderWithStore(state);+ expect(getClusters).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // showAllTracks toggle+ // -------------------------------------------------------------------------+ describe('showAllTracks toggle', () => {+ it('calls getClusters for each multi-geometry event when showAllTracks is enabled', () => {+ const map = buildMap();+ const events = [buildEvent(), buildEvent({ id: 'event-2' })];+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: events,+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: true,+ },+ });+ renderWithStore(state);+ expect(getClusters).toHaveBeenCalledTimes(events.length);+ });++ it('does not call getClusters when showAllTracks is false and selectedEvent has no id', () => {+ const map = buildMap();+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: null, date: null },+ showAllTracks: false,+ },+ });+ renderWithStore(state);+ expect(getClusters).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // highlighted event+ // -------------------------------------------------------------------------+ describe('highlighted event', () => {+ it('passes isHighlighted=true when event matches highlighted event and showAllTracks is true', () => {+ const map = buildMap();+ const event = buildEvent();+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [event],+ selected: { id: 'event-1', date: '2023-01-01' },+ highlighted: { id: 'event-1' },+ showAllTracks: true,+ },+ });+ renderWithStore(state);+ expect(getClusters).toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // createOverlayMapping+ // -------------------------------------------------------------------------+ describe('createOverlayMapping()', () => {+ it('groups overlays by shared id and calls removeOverlay on cleanup', () => {+ const sharedId = 'shared-id';+ const overlay1 = buildOverlay(sharedId);+ const overlay2 = buildOverlay(sharedId);+ const map = buildMap([overlay1, overlay2]);++ const track = buildOverlay(sharedId);+ getTrackLines.mockReturnValue(track);++ getClusters.mockReturnValue({+ clusters: [],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: true,+ },+ });+ const { unmount } = renderWithStore(state);+ act(() => { unmount(); });++ // removeTrackById finds the shared-id group in the mapping and iterates+ // it — verify removeOverlay was called and that the calls used overlays+ // from the mapped group (overlay1 and/or overlay2)+ expect(map.removeOverlay).toHaveBeenCalled();+ const removedArgs = map.removeOverlay.mock.calls.map((call) => call[0]);+ const removedIds = removedArgs.map((o) => o.getId());+ expect(removedIds.every((id) => id === sharedId)).toBe(true);+ });+ });++ describe('removePointOverlays() - overlay exists in overlayMapping (lines 29-34)', () => {+ it('removes sub-overlays from the mapping when the point overlay id is found', () => {+ const pointId = 'point-overlay-1';+ const subOverlay = { getId: jest.fn(() => pointId), getPosition: jest.fn(() => [0, 0]) };+ const map = buildMap([subOverlay]);++ // getOverlayById returns the overlay so the branch is entered+ map.getOverlayById = jest.fn((id) => (id === pointId ? subOverlay : null));++ const point = { getId: jest.fn(() => pointId), getPosition: jest.fn(() => [0, 0]) };+ getTrackPoint.mockReturnValue(point);+ getTrackLines.mockReturnValue(undefined);++ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: true,+ },+ });++ const { unmount } = renderWithStore(state);+ act(() => { unmount(); });+ expect(map.removeOverlay).toHaveBeenCalledWith(subOverlay);+ });+ });++ describe('removePointOverlays() - overlay NOT in overlayMapping (lines 61-68)', () => {+ it('calls removeOverlay directly with the pointsAndArrows array when id is not mapped', () => {+ const pointId = 'unmapped-point-1';+ const map = buildMap([]);++ // getOverlayById returns the overlay (so condition passes) but overlayMapping+ // will be empty so the else branch (removeOverlay(pointsAndArrows)) is hit+ const point = { getId: jest.fn(() => pointId), getPosition: jest.fn(() => [0, 0]) };+ map.getOverlayById = jest.fn((id) => (id === pointId ? point : null));+ getTrackPoint.mockReturnValue(point);+ getTrackLines.mockReturnValue(undefined);++ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: true,+ },+ });++ const { unmount } = renderWithStore(state);+ act(() => { unmount(); });+ expect(map.removeOverlay).toHaveBeenCalled();+ });+ });++ describe('onPropertyChange() - resolution/rotation change (lines 188-189)', () => {+ const setupWithTrack = (extraEventState = {}) => {+ const map = buildMap();+ const view = map.getView();+ let capturedHandler;+ view.on = jest.fn((evt, handler) => { capturedHandler = handler; });++ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ // Render once to build the track and populate trackDetails.id+ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ ...extraEventState,+ },+ });+ renderWithStore(state);++ map.removeOverlay.mockClear();+ return { map, capturedHandler: () => capturedHandler };+ };++ it('removes all tracks on resolution change when showAllTracks is true and tracks exist', () => {+ const { map, capturedHandler } = setupWithTrack({ showAllTracks: true });+ act(() => {+ const handler = capturedHandler();+ if (handler) handler({ key: 'resolution' });+ });+ expect(map.removeOverlay).toHaveBeenCalled();+ });+ });++ describe('update() - same event, same date with visible track marker (lines 218-225)', () => {+ it('updates DOM classNames when same event re-selected with a new non-clustered date', () => {+ const date1 = '2023-01-01';+ const date2 = '2023-01-02';++ // DOM elements updateSelection() will look up+ const oldSelected = document.createElement('div');+ oldSelected.className = 'track-marker-case-selected';+ document.body.appendChild(oldSelected);++ const newCaseEl = document.createElement('div');+ newCaseEl.id = `track-marker-case-${date2}`;+ document.body.appendChild(newCaseEl);++ // track-marker-${date2} must exist so isClusteredSelection is false+ const trackMarkerEl = document.createElement('div');+ trackMarkerEl.id = `track-marker-${date2}`;+ document.body.appendChild(trackMarkerEl);++ const map = buildMap();++ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: date1, cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const event = buildEvent({+ geometry: [+ { date: `${date1}T00:00:00Z`, coordinates: [0, 0], type: 'Point' },+ { date: `${date2}T00:00:00Z`, coordinates: [1, 1], type: 'Point' },+ ],+ });++ // First render: select date1 → populates trackDetailsRef with id=event-1+ const store1 = mockStore(defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [event],+ selected: { id: 'event-1', date: date1 },+ },+ }));++ const { rerender } = render(+ <Provider store={store1}>+ <EventTrack />+ </Provider>,+ );++ // Second render: same event, different date → sameEvent=true, sameDate=false+ // track-marker-${date2} exists so isClusteredSelection=false → updateSelection runs+ const store2 = mockStore(defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [event],+ selected: { id: 'event-1', date: date2 },+ },+ }));++ act(() => {+ rerender(+ <Provider store={store2}>+ <EventTrack />+ </Provider>,+ );+ });++ expect(newCaseEl.className).toContain('track-marker-case-selected');++ document.body.removeChild(oldSelected);+ document.body.removeChild(newCaseEl);+ document.body.removeChild(trackMarkerEl);+ });+ });++ describe('update() - same event, date changed, new date is clustered (line 271)', () => {+ it('rebuilds the track when the new date falls inside a cluster (no DOM marker)', () => {+ const map = buildMap();+ // No DOM element for the new date → isClusteredSelection = true+ // Ensure there is no element with id track-marker-2023-01-02+ const existing = document.getElementById('track-marker-2023-01-02');+ if (existing) existing.parentNode.removeChild(existing);++ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ { geometry: { coordinates: [1, 1] }, properties: { date: '2023-01-02', cluster: true } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ const state = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent({+ geometry: [+ { date: '2023-01-01T00:00:00Z', coordinates: [0, 0], type: 'Point' },+ { date: '2023-01-02T00:00:00Z', coordinates: [1, 1], type: 'Point' },+ ],+ })],+ selected: { id: 'event-1', date: '2023-01-02' },+ },+ });++ renderWithStore(state);+ expect(getClusters).toHaveBeenCalled();+ });+ });++ describe('useEffect - map instance change triggers re-initialize (lines 322-337)', () => {+ it('calls removeOverlay on the old map and registers listener on the new map', () => {+ const map1 = buildMap();+ const map2 = buildMap();+ const view2 = map2.getView();++ const store1 = mockStore(defaultState({+ map: { ui: { selected: map1 }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ }));++ const store2 = mockStore(defaultState({+ map: { ui: { selected: map2 }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ },+ }));++ const { rerender } = render(+ <Provider store={store1}>+ <EventTrack />+ </Provider>,+ );++ act(() => {+ rerender(+ <Provider store={store2}>+ <EventTrack />+ </Provider>,+ );+ });++ expect(view2.on).toHaveBeenCalledWith('propertychange', expect.any(Function));+ });+ });++ describe('useEffect - showAllTracks toggled off (lines 408-420)', () => {+ it('calls removeOverlay when showAllTracks transitions from true to false', () => {+ const map = buildMap();++ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ // Initial render with showAllTracks=true to populate allTrackDetails+ const stateWithTracks = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: true,+ },+ });++ const store1 = mockStore(stateWithTracks);+ const { rerender } = render(+ <Provider store={store1}>+ <EventTrack />+ </Provider>,+ );++ map.removeOverlay.mockClear();++ // Re-render with showAllTracks=false to trigger the removal branch+ const stateWithoutTracks = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: false,+ },+ });++ const store2 = mockStore(stateWithoutTracks);+ act(() => {+ rerender(+ <Provider store={store2}>+ <EventTrack />+ </Provider>,+ );+ });++ expect(map.removeOverlay).toHaveBeenCalled();+ });+ });++ describe('useEffect - event deselected, showAllTracks false (line 425)', () => {+ it('calls removeOverlay when event is deselected and showAllTracks is false', () => {+ const map = buildMap();++ getClusters.mockReturnValue({+ clusters: [+ { geometry: { coordinates: [0, 0] }, properties: { date: '2023-01-01', cluster: false } },+ ],+ firstClusterObj: {},+ secondClusterObj: {},+ });++ // First render: event is selected, builds a track+ const selectedState = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: 'event-1', date: '2023-01-01' },+ showAllTracks: false,+ },+ });++ const store1 = mockStore(selectedState);+ const { rerender } = render(+ <Provider store={store1}>+ <EventTrack />+ </Provider>,+ );++ map.removeOverlay.mockClear();++ // Second render: event is deselected (no id)+ const deselectedState = defaultState({+ map: { ui: { selected: map }, extent: [0, 0, 10, 10] },+ events: {+ ...defaultState().events,+ filteredEvents: [buildEvent()],+ selected: { id: null, date: null },+ showAllTracks: false,+ },+ });++ const store2 = mockStore(deselectedState);+ act(() => {+ rerender(+ <Provider store={store2}>+ <EventTrack />+ </Provider>,+ );+ });++ expect(map.removeOverlay).toHaveBeenCalled();+ });+ });});diff --git a/web/js/map/natural-events/natural-events.test.js b/web/js/map/natural-events/natural-events.test.jsindex ca5d35865..5e5c26f27 100644--- a/web/js/map/natural-events/natural-events.test.js+++ b/web/js/map/natural-events/natural-events.test.js@@ -1,3 +1,757 @@-test('natural-events map test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import ConnectedNaturalEvents from './natural-events';+import { fly } from '../util';+import util from '../../util/util';+import {+ getDefaultEventDate,+ validateGeometryCoords,+ toEventDateString,+} from '../../modules/natural-events/util';+import * as olExtent from 'ol/extent';+import * as olProj from 'ol/proj';++jest.mock('ol/extent', () => ({+ boundingExtent: jest.fn(() => [0, 0, 10, 10]),+}));++jest.mock('ol/proj', () => ({+ transform: jest.fn((coords) => coords),+}));++jest.mock('../../modules/natural-events/util', () => ({+ getDefaultEventDate: jest.fn(() => '2023-01-01'),+ validateGeometryCoords: jest.fn(() => true),+ toEventDateString: jest.fn((date) => date.toISOString().split('T')[0]),+}));++jest.mock('../../util/util', () => ({+ now: jest.fn(() => new Date('2023-06-15T00:00:00Z')),+ yesterday: jest.fn(() => new Date('2023-06-14T00:00:00Z')),+ parseDateUTC: jest.fn((dateStr) => new Date(dateStr)),+ dateAdd: jest.fn((date, unit, amount) => {+ const d = new Date(date);+ d.setDate(d.getDate() + amount);+ return d;+ }),+}));++jest.mock('../../modules/date/actions', () => ({+ selectDate: jest.fn((date) => ({ type: 'SELECT_DATE', date })),+}));++jest.mock('../../modules/natural-events/actions', () => ({+ selected: jest.fn(() => ({ type: 'SELECTED_EVENT' })),+}));++jest.mock('../../modules/layers/actions', () => ({+ addLayer: jest.fn((id) => ({ type: 'ADD_LAYER', id })),+ removeGroup: jest.fn((ids) => ({ type: 'REMOVE_GROUP', ids })),+ activateLayersForEventCategory: jest.fn((cat) => ({ type: 'ACTIVATE_LAYERS', cat })),+ toggleVisibility: jest.fn((id, vis) => ({ type: 'TOGGLE_VISIBILITY', id, vis })),+ toggleGroupVisibility: jest.fn((ids, vis) => ({ type: 'TOGGLE_GROUP_VISIBILITY', ids, vis })),+}));++jest.mock('../../modules/natural-events/selectors', () => ({+ getFilteredEvents: jest.fn((state) => state.events.filteredEvents || []),+}));++jest.mock('../../modules/map/constants', () => ({+ CRS: { GEOGRAPHIC: 'EPSG:4326' },+}));++jest.mock('./event-track', () => () => null);+jest.mock('./event-markers', () => ({ __esModule: true, default: () => null }));++jest.mock('../util', () => ({+ fly: jest.fn(() => Promise.resolve()),+}));++const NaturalEvents = ConnectedNaturalEvents.WrappedComponent;++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const mockStore = configureMockStore([]);++const zoomLevelReference = { wildfires: 8, volcanoes: 6 };++/**+ * Build a map stub where getView() always returns the SAME view instance.+ * This is required so that spies set up on view methods in tests are the+ * same objects that the component calls internally.+ */+const buildMap = () => {+ const view = {+ getZoom: jest.fn(() => 5),+ calculateExtent: jest.fn(() => [-180, -90, 180, 90]),+ };+ return {+ getView: jest.fn(() => view),+ addOverlay: jest.fn(),+ removeOverlay: jest.fn(),+ };+};++const geographicProj = () => ({+ selected: { id: 'geographic', crs: 'EPSG:4326' },+});++const buildPointEvent = (overrides = {}) => ({+ id: 'event-1',+ title: 'Test Wildfire',+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ geometry: [{ date: '2023-01-01T00:00:00Z', coordinates: [10, 20], type: 'Point' }],+ ...overrides,+});++const buildPolygonEvent = (overrides = {}) => ({+ id: 'event-2',+ title: 'Test Flood',+ categories: [{ id: 'floods', title: 'Floods' }],+ geometry: [+ {+ date: '2023-01-01T00:00:00Z',+ type: 'Polygon',+ coordinates: [[[0, 0], [0, 10], [10, 10], [10, 0], [0, 0]]],+ },+ ],+ ...overrides,+});++/**+ * selectedEvent must always be an object (never null) when passed as a prop+ * because componentDidMount accesses selectedEvent.date unconditionally.+ * Use `{ id: null, date: null }` to represent "no event selected".+ */+const defaultProps = (overrides = {}) => ({+ map: buildMap(),+ proj: geographicProj(),+ eventsData: [],+ eventsDataIsLoading: false,+ selectedEvent: { id: null, date: null },+ eventLayers: ['layer-1'],+ layers: [],+ defaultEventLayer: 'VIIRS_NOAA20_CorrectedReflectance_TrueColor',+ isKioskModeActive: false,+ selectDate: jest.fn(),+ selectEventFinished: jest.fn(),+ activateLayersForEventCategory: jest.fn(),+ removeGroup: jest.fn(),+ toggleVisibility: jest.fn(),+ toggleGroupVisibility: jest.fn(),+ addLayer: jest.fn(),+ ...overrides,+});++const createInstance = (props) => {+ const instance = new NaturalEvents(props);+ instance.props = props;+ instance.state = { prevSelectedEvent: {} };+ instance.setState = jest.fn((updater, callback) => {+ const next = typeof updater === 'function' ? updater(instance.state) : updater;+ instance.state = { ...instance.state, ...next };+ if (callback) callback();+ });+ return instance;+};++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe('NaturalEvents', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ toEventDateString.mockImplementation(+ (d) => (d instanceof Date ? d.toISOString().split('T')[0] : d),+ );+ util.now.mockReturnValue(new Date('2023-06-15T00:00:00Z'));+ util.yesterday.mockReturnValue(new Date('2023-06-14T00:00:00Z'));+ util.parseDateUTC.mockImplementation((s) => new Date(s));+ util.dateAdd.mockImplementation((date, unit, amt) => {+ const d = new Date(date);+ d.setDate(d.getDate() + amt);+ return d;+ });+ getDefaultEventDate.mockReturnValue('2023-01-01');+ validateGeometryCoords.mockReturnValue(true);+ fly.mockResolvedValue();+ });++ // -------------------------------------------------------------------------+ // render+ // -------------------------------------------------------------------------+ describe('render', () => {+ it('renders without crashing', () => {+ const instance = createInstance(defaultProps());+ expect(() => instance.render()).not.toThrow();+ });++ it('renders EventTrack and EventMarkers as children', () => {+ const { container } = render(<NaturalEvents {...defaultProps()} />);+ expect(container).toBeDefined();+ });+ });++ // -------------------------------------------------------------------------+ // componentDidMount+ // -------------------------------------------------------------------------+ describe('componentDidMount', () => {+ it('calls addLayer when the default event layer is not present in layers', () => {+ const addLayer = jest.fn();+ const props = defaultProps({+ addLayer,+ layers: [{ id: 'some-other-layer', group: 'baselayers' }],+ });+ const instance = createInstance(props);+ instance.componentDidMount();+ expect(addLayer).toHaveBeenCalledWith('VIIRS_NOAA20_CorrectedReflectance_TrueColor');+ });++ it('calls toggleVisibility(true) when default layer IS present and selectedEvent has no date', () => {+ const toggleVisibility = jest.fn();+ const defaultLayer = 'VIIRS_NOAA20_CorrectedReflectance_TrueColor';+ const props = defaultProps({+ toggleVisibility,+ layers: [{ id: defaultLayer, group: 'overlays', layergroup: 'Weather' }],+ selectedEvent: { id: null, date: null },+ });+ const instance = createInstance(props);+ instance.componentDidMount();+ expect(toggleVisibility).toHaveBeenCalledWith(defaultLayer, true);+ });++ it('hides overlay layers (excluding Reference group) when selectedEvent has no date', () => {+ const toggleGroupVisibility = jest.fn();+ const defaultLayer = 'VIIRS_NOAA20_CorrectedReflectance_TrueColor';+ const props = defaultProps({+ toggleGroupVisibility,+ layers: [+ { id: defaultLayer, group: 'overlays', layergroup: 'Weather' },+ { id: 'overlay-1', group: 'overlays', layergroup: 'Weather' },+ { id: 'reference-1', group: 'overlays', layergroup: 'Reference' },+ { id: 'base-1', group: 'baselayers', layergroup: 'Base' },+ ],+ selectedEvent: { id: null, date: null },+ });+ const instance = createInstance(props);+ instance.componentDidMount();+ expect(toggleGroupVisibility).toHaveBeenCalledWith(+ expect.arrayContaining(['overlay-1']),+ false,+ );+ const hiddenIds = toggleGroupVisibility.mock.calls[0][0];+ expect(hiddenIds).not.toContain('reference-1');+ expect(hiddenIds).not.toContain('base-1');+ });++ it('does NOT call toggleGroupVisibility when selectedEvent has a date', () => {+ const toggleGroupVisibility = jest.fn();+ const props = defaultProps({+ toggleGroupVisibility,+ layers: [{ id: 'overlay-1', group: 'overlays', layergroup: 'Weather' }],+ selectedEvent: { id: 'event-1', date: '2023-01-01' },+ });+ const instance = createInstance(props);+ instance.componentDidMount();+ expect(toggleGroupVisibility).not.toHaveBeenCalled();+ });++ it('does NOT call toggleVisibility when default layer is present and selectedEvent has a date', () => {+ const toggleVisibility = jest.fn();+ const defaultLayer = 'VIIRS_NOAA20_CorrectedReflectance_TrueColor';+ const props = defaultProps({+ toggleVisibility,+ layers: [{ id: defaultLayer, group: 'overlays', layergroup: 'Weather' }],+ selectedEvent: { id: 'event-1', date: '2023-01-01' },+ });+ const instance = createInstance(props);+ instance.componentDidMount();+ expect(toggleVisibility).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // componentWillUnmount+ // -------------------------------------------------------------------------+ describe('componentWillUnmount', () => {+ it('calls toggleVisibility with false on unmount', () => {+ const toggleVisibility = jest.fn();+ const defaultLayer = 'VIIRS_NOAA20_CorrectedReflectance_TrueColor';+ const instance = createInstance(defaultProps({ toggleVisibility }));+ instance.componentWillUnmount();+ expect(toggleVisibility).toHaveBeenCalledWith(defaultLayer, false);+ });+ });++ // -------------------------------------------------------------------------+ // componentDidUpdate+ // -------------------------------------------------------------------------+ describe('componentDidUpdate', () => {+ it('returns early when map is null', () => {+ const selectDate = jest.fn();+ const instance = createInstance(defaultProps({ map: null, selectDate }));+ instance.componentDidUpdate({+ map: null,+ eventsDataIsLoading: false,+ selectedEvent: { id: null, date: null },+ });+ expect(selectDate).not.toHaveBeenCalled();+ });++ it('returns early when eventsDataIsLoading is true', () => {+ const selectDate = jest.fn();+ const instance = createInstance(+ defaultProps({ eventsDataIsLoading: true, selectDate }),+ );+ instance.componentDidUpdate({+ map: buildMap(),+ eventsDataIsLoading: false,+ selectedEvent: { id: null, date: null },+ });+ expect(selectDate).not.toHaveBeenCalled();+ });++ it('calls zoomIfVisible when events finish loading with a selectedEvent', () => {+ const event = buildPointEvent();+ const selectedEvent = { id: 'event-1', date: '2023-01-01' };+ const props = defaultProps({+ eventsData: [event],+ selectedEvent,+ eventsDataIsLoading: false,+ });+ const instance = createInstance(props);+ const zoomSpy = jest.spyOn(instance, 'zoomIfVisible').mockImplementation(() => {});+ instance.componentDidUpdate({+ map: buildMap(),+ eventsDataIsLoading: true,+ selectedEvent,+ });+ expect(zoomSpy).toHaveBeenCalledWith(selectedEvent);+ });++ it('calls selectEvent when selectedEvent changes to a new event', () => {+ const event = buildPointEvent();+ const selectedEvent = { id: 'event-1', date: '2023-01-01' };+ const props = defaultProps({+ eventsData: [event],+ selectedEvent,+ });+ const instance = createInstance(props);+ const selectSpy = jest.spyOn(instance, 'selectEvent').mockImplementation(() => {});+ instance.componentDidUpdate({+ map: buildMap(),+ eventsDataIsLoading: false,+ selectedEvent: { id: null, date: null },+ });+ expect(selectSpy).toHaveBeenCalledWith('event-1', '2023-01-01', false);+ });++ it('does not call selectEvent when selectedEvent does not change', () => {+ const selectedEvent = { id: 'event-1', date: '2023-01-01' };+ const props = defaultProps({ selectedEvent });+ const instance = createInstance(props);+ const selectSpy = jest.spyOn(instance, 'selectEvent').mockImplementation(() => {});+ // same reference → no change+ instance.componentDidUpdate({+ map: buildMap(),+ eventsDataIsLoading: false,+ selectedEvent,+ });+ expect(selectSpy).not.toHaveBeenCalled();+ });++ it('passes loadingChange=true to selectEvent when events just finished loading', () => {+ const event = buildPointEvent();+ const selectedEvent = { id: 'event-1', date: '2023-01-01' };+ const props = defaultProps({+ eventsData: [event],+ selectedEvent,+ eventsDataIsLoading: false,+ });+ const instance = createInstance(props);+ const selectSpy = jest.spyOn(instance, 'selectEvent').mockImplementation(() => {});+ instance.componentDidUpdate({+ map: buildMap(),+ eventsDataIsLoading: true,+ selectedEvent: { id: null, date: null },+ });+ expect(selectSpy).toHaveBeenCalledWith('event-1', '2023-01-01', true);+ });+ });++ // -------------------------------------------------------------------------+ // zoomIfVisible+ // -------------------------------------------------------------------------+ describe('zoomIfVisible()', () => {+ it('calls zoomToEvent when the event has visible geometry', () => {+ const event = buildPointEvent();+ validateGeometryCoords.mockReturnValue(true);+ const props = defaultProps({ eventsData: [event] });+ const instance = createInstance(props);+ const zoomSpy = jest.spyOn(instance, 'zoomToEvent').mockResolvedValue();+ instance.zoomIfVisible({ id: 'event-1', date: '2023-01-01' });+ expect(zoomSpy).toHaveBeenCalledWith(event, '2023-01-01');+ });++ it('does NOT call zoomToEvent when no geometry passes validation', () => {+ const event = buildPointEvent();+ validateGeometryCoords.mockReturnValue(false);+ const props = defaultProps({ eventsData: [event] });+ const instance = createInstance(props);+ const zoomSpy = jest.spyOn(instance, 'zoomToEvent').mockResolvedValue();+ instance.zoomIfVisible({ id: 'event-1', date: '2023-01-01' });+ expect(zoomSpy).not.toHaveBeenCalled();+ });++ it('returns early when the event is not found in eventsData', () => {+ const props = defaultProps({ eventsData: [] });+ const instance = createInstance(props);+ const zoomSpy = jest.spyOn(instance, 'zoomToEvent').mockResolvedValue();+ instance.zoomIfVisible({ id: 'event-not-found', date: '2023-01-01' });+ expect(zoomSpy).not.toHaveBeenCalled();+ });+ });++ // -------------------------------------------------------------------------+ // getZoomPromise+ // -------------------------------------------------------------------------+ describe('getZoomPromise()', () => {+ it('returns a resolved promise immediately when isInitialLoad is true', async () => {+ const instance = createInstance(defaultProps());+ jest.spyOn(instance, 'zoomToEvent').mockResolvedValue();+ const result = instance.getZoomPromise(buildPointEvent(), '2023-01-01', false, true);+ await expect(result).resolves.toBeUndefined();+ });++ it('calls zoomToEvent and returns its promise when isInitialLoad is false', () => {+ const event = buildPointEvent();+ const instance = createInstance(defaultProps({ eventsData: [event] }));+ const zoomSpy = jest.spyOn(instance, 'zoomToEvent').mockResolvedValue();+ instance.getZoomPromise(event, '2023-01-01', true, false);+ expect(zoomSpy).toHaveBeenCalledWith(event, '2023-01-01', true);+ });+ });++ // -------------------------------------------------------------------------+ // selectEvent+ // -------------------------------------------------------------------------+ describe('selectEvent()', () => {+ it('returns early when event is not found in eventsData', () => {+ const selectDate = jest.fn();+ const instance = createInstance(defaultProps({ eventsData: [], selectDate }));+ instance.selectEvent('event-not-found', '2023-01-01', false);+ expect(selectDate).not.toHaveBeenCalled();+ });++ it('calls selectDate with the parsed date', () => {+ const event = buildPointEvent();+ const selectDate = jest.fn();+ const instance = createInstance(defaultProps({ eventsData: [event], selectDate }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2023-01-01', false);+ expect(selectDate).toHaveBeenCalled();+ });++ it('adds one day to wildfire date when the date is not recent', () => {+ const event = buildPointEvent({+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ });+ const oldDate = '2022-01-01';+ toEventDateString+ .mockReturnValueOnce('2023-06-15')+ .mockReturnValueOnce('2023-06-14');+ util.parseDateUTC.mockReturnValue(new Date(oldDate));+ const instance = createInstance(defaultProps({ eventsData: [event] }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', oldDate, false);+ expect(util.dateAdd).toHaveBeenCalledWith(expect.any(Date), 'day', 1);+ });++ it('does NOT add a day for a wildfire that happened today', () => {+ const event = buildPointEvent({+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ });+ const todayStr = '2023-06-15';+ toEventDateString.mockReturnValue(todayStr);+ util.parseDateUTC.mockReturnValue(new Date(todayStr));+ const instance = createInstance(defaultProps({ eventsData: [event] }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', todayStr, false);+ expect(util.dateAdd).not.toHaveBeenCalled();+ });++ it('does NOT add a day for a wildfire that happened yesterday', () => {+ const event = buildPointEvent({+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ });+ const yesterdayStr = '2023-06-14';+ toEventDateString.mockReturnValue(yesterdayStr);+ util.parseDateUTC.mockReturnValue(new Date(yesterdayStr));+ const instance = createInstance(defaultProps({ eventsData: [event] }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', yesterdayStr, false);+ expect(util.dateAdd).not.toHaveBeenCalled();+ });++ it('does NOT add a day for non-wildfire events regardless of date', () => {+ const event = buildPointEvent({+ categories: [{ id: 'volcanoes', title: 'Volcanoes' }],+ });+ const instance = createInstance(defaultProps({ eventsData: [event] }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2022-01-01', false);+ expect(util.dateAdd).not.toHaveBeenCalled();+ });++ it('calls removeGroup and activateLayersForEventCategory when category changes', async () => {+ const removeGroup = jest.fn();+ const activateLayersForEventCategory = jest.fn();+ const selectEventFinished = jest.fn();+ const prevEvent = buildPointEvent({+ id: 'event-0',+ categories: [{ id: 'volcanoes', title: 'Volcanoes' }],+ });+ const nextEvent = buildPointEvent({+ id: 'event-1',+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ });+ const instance = createInstance(defaultProps({+ eventsData: [prevEvent, nextEvent],+ removeGroup,+ activateLayersForEventCategory,+ selectEventFinished,+ eventLayers: ['layer-1'],+ }));+ instance.state = { prevSelectedEvent: { id: 'event-0', date: '2023-01-01' } };+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2023-01-01', false);+ await Promise.resolve();+ expect(removeGroup).toHaveBeenCalledWith(['layer-1']);+ expect(activateLayersForEventCategory).toHaveBeenCalledWith('Wildfires');+ });++ it('does NOT call removeGroup when category stays the same', async () => {+ const removeGroup = jest.fn();+ const prevEvent = buildPointEvent({+ id: 'event-0',+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ });+ const nextEvent = buildPointEvent({+ id: 'event-1',+ categories: [{ id: 'wildfires', title: 'Wildfires' }],+ });+ const instance = createInstance(defaultProps({+ eventsData: [prevEvent, nextEvent],+ removeGroup,+ }));+ instance.state = { prevSelectedEvent: { id: 'event-0', date: '2023-01-01' } };+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2023-01-01', false);+ await Promise.resolve();+ expect(removeGroup).not.toHaveBeenCalled();+ });++ it('calls selectEventFinished after zoom promise resolves', async () => {+ const event = buildPointEvent();+ const selectEventFinished = jest.fn();+ const instance = createInstance(defaultProps({+ eventsData: [event],+ selectEventFinished,+ }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2023-01-01', false);+ await Promise.resolve();+ expect(selectEventFinished).toHaveBeenCalled();+ });++ it('does NOT call removeGroup or activateLayersForEventCategory when isInitialLoad is true', async () => {+ const removeGroup = jest.fn();+ const activateLayersForEventCategory = jest.fn();+ const event = buildPointEvent();+ const instance = createInstance(defaultProps({+ eventsData: [event],+ removeGroup,+ activateLayersForEventCategory,+ }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2023-01-01', true);+ await Promise.resolve();+ expect(removeGroup).not.toHaveBeenCalled();+ expect(activateLayersForEventCategory).not.toHaveBeenCalled();+ });++ it('updates prevSelectedEvent state after being called', () => {+ const event = buildPointEvent();+ const instance = createInstance(defaultProps({ eventsData: [event] }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2023-01-01', false);+ expect(instance.setState).toHaveBeenCalledWith({+ prevSelectedEvent: { id: 'event-1', date: '2023-01-01' },+ });+ });++ it('uses getDefaultEventDate when no date is passed', () => {+ const event = buildPointEvent();+ getDefaultEventDate.mockReturnValue('2023-01-01');+ const instance = createInstance(defaultProps({ eventsData: [event] }));+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', null, false);+ expect(getDefaultEventDate).toHaveBeenCalledWith(event);+ });++ it('handles the case where prevSelectedEvent has no id (first selection)', async () => {+ const event = buildPointEvent();+ const activateLayersForEventCategory = jest.fn();+ const instance = createInstance(defaultProps({+ eventsData: [event],+ activateLayersForEventCategory,+ }));+ instance.state = { prevSelectedEvent: {} };+ jest.spyOn(instance, 'getZoomPromise').mockReturnValue(Promise.resolve());+ instance.selectEvent('event-1', '2023-01-01', false);+ await Promise.resolve();+ expect(activateLayersForEventCategory).toHaveBeenCalledWith('Wildfires');+ });+ });++ // -------------------------------------------------------------------------+ // zoomToEvent — Point geometry+ // -------------------------------------------------------------------------+ describe('zoomToEvent() – Point geometry', () => {+ it('calls fly() with transformed point coordinates', () => {+ const event = buildPointEvent();+ const map = buildMap();+ const instance = createInstance(defaultProps({ map, eventsData: [event] }));+ instance.zoomToEvent(event, '2023-01-01', false);+ expect(fly).toHaveBeenCalledWith(+ map,+ geographicProj(),+ expect.any(Array),+ false,+ zoomLevelReference.wildfires,+ null,+ );+ });++ it('uses the current map zoom level when isSameEventID is true', () => {+ const event = buildPointEvent({ categories: [{ id: 'volcanoes', title: 'Volcanoes' }] });+ const map = buildMap();+ // Capture the single shared view instance before calling zoomToEvent+ const view = map.getView();+ const instance = createInstance(defaultProps({ map, eventsData: [event] }));+ instance.zoomToEvent(event, '2023-01-01', true);+ expect(view.getZoom).toHaveBeenCalled();+ expect(fly).toHaveBeenCalledWith(map, expect.anything(), expect.anything(), false, 5, null);+ });++ it('uses zoomLevelReference zoom for known categories when isSameEventID is false', () => {+ const event = buildPointEvent({ categories: [{ id: 'volcanoes', title: 'Volcanoes' }] });+ const map = buildMap();+ const instance = createInstance(defaultProps({ map, eventsData: [event] }));+ instance.zoomToEvent(event, '2023-01-01', false);+ expect(fly).toHaveBeenCalledWith(+ map, expect.anything(), expect.anything(), false, zoomLevelReference.volcanoes, null,+ );+ });++ it('uses undefined zoom for categories not in the reference table', () => {+ const event = buildPointEvent({ categories: [{ id: 'floods', title: 'Floods' }] });+ const map = buildMap();+ const instance = createInstance(defaultProps({ map, eventsData: [event] }));+ instance.zoomToEvent(event, '2023-01-01', false);+ expect(fly).toHaveBeenCalledWith(+ map, expect.anything(), expect.anything(), false, undefined, null,+ );+ });++ it('calls olProj.transform on Point coordinates', () => {+ const event = buildPointEvent();+ const map = buildMap();+ const instance = createInstance(defaultProps({ map, eventsData: [event] }));+ instance.zoomToEvent(event, '2023-01-01', false);+ expect(olProj.transform).toHaveBeenCalledWith([10, 20], 'EPSG:4326', 'EPSG:4326');+ });++ it('passes isKioskModeActive=true to fly()', () => {+ const event = buildPointEvent();+ const map = buildMap();+ const instance = createInstance(+ defaultProps({ map, eventsData: [event], isKioskModeActive: true }),+ );+ instance.zoomToEvent(event, '2023-01-01', false);+ expect(fly).toHaveBeenCalledWith(+ map, expect.anything(), expect.anything(), true, expect.anything(), null,+ );+ });+ });++ // -------------------------------------------------------------------------+ // zoomToEvent — Polygon geometry+ // -------------------------------------------------------------------------+ describe('zoomToEvent() – Polygon geometry', () => {+ it('calls boundingExtent and fly() for a Polygon event', () => {+ const event = buildPolygonEvent();+ const map = buildMap();+ const instance = createInstance(defaultProps({ map, eventsData: [event] }));+ instance.zoomToEvent(event, '2023-01-01', false);+ expect(olExtent.boundingExtent).toHaveBeenCalled();+ expect(fly).toHaveBeenCalled();+ });++ it('transforms each coordinate in the polygon ring before passing to boundingExtent', () => {+ const event = buildPolygonEvent();+ const map = buildMap();+ const instance = createInstance(defaultProps({ map, eventsData: [event] }));+ instance.zoomToEvent(event, '2023-01-01', false);+ // 5 coordinates in the ring → 5 transform calls+ expect(olProj.transform).toHaveBeenCalledTimes(5);+ });+ });++ // -------------------------------------------------------------------------+ // Redux connect wiring+ // -------------------------------------------------------------------------+ describe('redux connect wiring', () => {+ it('exposes the unwrapped class as WrappedComponent', () => {+ expect(ConnectedNaturalEvents.WrappedComponent).toBe(NaturalEvents);+ });++ it('renders inside a Provider without crashing', () => {+ const store = mockStore({+ map: { ui: { selected: buildMap() } },+ proj: geographicProj(),+ requestedEvents: { isLoading: false },+ events: {+ active: true,+ // Use an object with null fields instead of null to avoid+ // selectedEvent.date access errors in componentDidMount+ selected: { id: null, date: null },+ filteredEvents: [],+ showAllTracks: false,+ highlighted: {},+ },+ layers: {+ active: { layers: [] },+ eventLayers: [],+ },+ config: {+ naturalEvents: { defaultLayer: 'VIIRS_NOAA20_CorrectedReflectance_TrueColor' },+ },+ ui: { isKioskModeActive: false },+ });+ expect(() =>+ render(+ <Provider store={store}>+ <ConnectedNaturalEvents />+ </Provider>,+ ),+ ).not.toThrow();+ });+ });});diff --git a/web/js/map/natural-events/util.test.js b/web/js/map/natural-events/util.test.jsindex 06ae26670..6d1739ced 100644--- a/web/js/map/natural-events/util.test.js+++ b/web/js/map/natural-events/util.test.js@@ -1,3 +1,816 @@-test('util map test', () => {+// util.test.js+// ---------------------------------------------------------------------------+// Mocks+// ---------------------------------------------------------------------------++jest.mock('ol/Overlay', () =>+ jest.fn().mockImplementation((opts) => ({+ ...opts,+ getId: jest.fn(() => opts.id),+ getPosition: jest.fn(() => opts.position),+ })),+);++jest.mock('ol/proj', () => ({+ transform: jest.fn((coords) => coords),+}));++jest.mock('../util', () => ({+ mapUtilZoomAction: jest.fn(),+}));++jest.mock('../../modules/date/util', () => ({+ formatDisplayDate: jest.fn((date) => `formatted-${date}`),+}));++jest.mock('../../modules/map/constants', () => ({+ CRS: { GEOGRAPHIC: 'EPSG:4326' },+}));++// ---------------------------------------------------------------------------+// Imports+// ---------------------------------------------------------------------------+import OlOverlay from 'ol/Overlay';+import * as olProj from 'ol/proj';+import { mapUtilZoomAction } from '../util';+import { formatDisplayDate } from '../../modules/date/util';+import {+ getTrackPoint,+ getArrows,+ getTrackLines,+ getClusterPointEl,+} from './util';++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const geographicProj = () => ({ selected: { id: 'geographic', crs: 'EPSG:4326' } });+const polarProj = () => ({ selected: { id: 'arctic', crs: 'EPSG:3413' } });++const buildClusterPoint = (overrides = {}) => ({+ geometry: {+ coordinates: [10, 20],+ magnitudeValue: null,+ magnitudeUnit: null,+ ...overrides.geometry,+ },+ properties: {+ date: '2023-01-01',+ event_id: 'event-1',+ ...overrides.properties,+ },+});++const buildMap = (pixelOverrides = {}) => {+ const view = {+ getRotation: jest.fn(() => 0),+ getZoom: jest.fn(() => 5),+ };+ return {+ getView: jest.fn(() => view),+ getPixelFromCoordinate: jest.fn((coord) => coord),+ getCoordinateFromPixel: jest.fn((pixel) => pixel),+ ...pixelOverrides,+ };+};++const defaultHighlightOptions = () => ({+ callbackHighlight: jest.fn(),+ callbackUnhighlight: jest.fn(),+ isHighlighted: false,+});++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe('natural-events/util', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ // -------------------------------------------------------------------------+ // getTrackPoint+ // -------------------------------------------------------------------------+ describe('getTrackPoint()', () => {+ it('returns an OlOverlay instance', () => {+ const point = getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ defaultHighlightOptions(),+ );+ expect(OlOverlay).toHaveBeenCalled();+ expect(point).toBeDefined();+ });++ it('sets the overlay id to eventID + date string', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ defaultHighlightOptions(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.id).toBe('event-12023-01-01');+ });++ it('uses geographic coordinates unchanged when proj is geographic', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ defaultHighlightOptions(),+ );+ expect(olProj.transform).not.toHaveBeenCalled();+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.position).toEqual([10, 20]);+ });++ it('transforms coordinates for polar projections', () => {+ getTrackPoint(+ polarProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ defaultHighlightOptions(),+ );+ expect(olProj.transform).toHaveBeenCalledWith([10, 20], 'EPSG:4326', 'EPSG:3413');+ });++ it('sets selected className on overlayEl when isSelected is true', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ true,+ jest.fn(),+ defaultHighlightOptions(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.element.className).toBe('track-marker-case track-marker-case-selected');+ });++ it('sets unselected className on overlayEl when isSelected is false', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ defaultHighlightOptions(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.element.className).toBe('track-marker-case');+ });++ it('calls callback with eventID and date on click', () => {+ const callback = jest.fn();+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ callback,+ defaultHighlightOptions(),+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ overlayEl.onclick();+ expect(callback).toHaveBeenCalledWith('event-1', '2023-01-01');+ });++ it('calls callbackHighlight on mouseenter', () => {+ const callbackHighlight = jest.fn();+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ { ...defaultHighlightOptions(), callbackHighlight },+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ overlayEl.onmouseenter();+ expect(callbackHighlight).toHaveBeenCalledWith('event-1', '2023-01-01');+ });++ it('calls callbackUnhighlight on mouseleave', () => {+ const callbackUnhighlight = jest.fn();+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ { ...defaultHighlightOptions(), callbackUnhighlight },+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ overlayEl.onmouseleave();+ expect(callbackUnhighlight).toHaveBeenCalled();+ });++ it('sets textEl className to selected when isHighlighted is true', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ { ...defaultHighlightOptions(), isHighlighted: true },+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const textEl = overlayEl.querySelector('span');+ expect(textEl.className).toBe('track-marker-date track-marker-date-selected');+ });++ it('resets textEl className after 5 seconds when isHighlighted is true', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ { ...defaultHighlightOptions(), isHighlighted: true },+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const textEl = overlayEl.querySelector('span');+ jest.advanceTimersByTime(5000);+ expect(textEl.className).toBe('track-marker-date');+ });++ it('sets textEl className to track-marker-date when isHighlighted is false', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ { ...defaultHighlightOptions(), isHighlighted: false },+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const textEl = overlayEl.querySelector('span');+ expect(textEl.className).toBe('track-marker-date');+ });++ it('sets circleEl height/width/borderRadius when isHighlighted is true', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ { ...defaultHighlightOptions(), isHighlighted: true },+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const circleEl = overlayEl.querySelector('div');+ expect(circleEl.style.height).toBe('13px');+ expect(circleEl.style.width).toBe('13px');+ expect(circleEl.style.borderRadius).toBe('7px');+ });++ it('leaves circleEl height/width/borderRadius empty when isHighlighted is false', () => {+ getTrackPoint(+ geographicProj(),+ buildClusterPoint(),+ false,+ jest.fn(),+ defaultHighlightOptions(),+ );+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const circleEl = overlayEl.querySelector('div');+ expect(circleEl.style.height).toBe('');+ expect(circleEl.style.width).toBe('');+ });++ it('sets textEl top style to -40px when hasMagnitude is true', () => {+ const point = buildClusterPoint({+ geometry: { coordinates: [10, 20], magnitudeValue: 100, magnitudeUnit: 'kts' },+ });+ getTrackPoint(geographicProj(), point, false, jest.fn(), defaultHighlightOptions());+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const textEl = overlayEl.querySelector('span');+ expect(textEl.style.top).toBe('-40px');+ });++ it('sets textEl top style to -28px when hasMagnitude is false', () => {+ getTrackPoint(geographicProj(), buildClusterPoint(),+ false, jest.fn(), defaultHighlightOptions());+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const textEl = overlayEl.querySelector('span');+ expect(textEl.style.top).toBe('-28px');+ });++ it('appends kts magnitude content without superscript', () => {+ const point = buildClusterPoint({+ geometry: { coordinates: [10, 20], magnitudeValue: 150, magnitudeUnit: 'kts' },+ });+ getTrackPoint(geographicProj(), point, false, jest.fn(), defaultHighlightOptions());+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const magnitudeEl = overlayEl.querySelector('span > div');+ expect(magnitudeEl.textContent).toContain('150');+ expect(magnitudeEl.textContent).toContain(' kts');+ });++ it('appends NM magnitude content with superscript 2', () => {+ const point = buildClusterPoint({+ geometry: { coordinates: [10, 20], magnitudeValue: 200, magnitudeUnit: 'NM' },+ });+ getTrackPoint(geographicProj(), point, false, jest.fn(), defaultHighlightOptions());+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const magnitudeEl = overlayEl.querySelector('span > div');+ expect(magnitudeEl.textContent).toContain('200');+ expect(magnitudeEl.querySelector('sup').textContent).toBe('2');+ });++ it('sets overlayEl id and data-id correctly', () => {+ getTrackPoint(geographicProj(), buildClusterPoint(),+ false, jest.fn(), defaultHighlightOptions());+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ expect(overlayEl.id).toBe('track-marker-case-2023-01-01');+ expect(overlayEl.dataset.id).toBe('event-1');+ });++ it('calls formatDisplayDate with the event date', () => {+ getTrackPoint(geographicProj(), buildClusterPoint(),+ false, jest.fn(), defaultHighlightOptions());+ expect(formatDisplayDate).toHaveBeenCalledWith('2023-01-01');+ });+ });++ // -------------------------------------------------------------------------+ // getArrows+ // -------------------------------------------------------------------------+ describe('getArrows()', () => {+ it('returns an OlOverlay instance', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([50, 25]);++ getArrows([[10, 20], [0, 0]], map, false);+ expect(OlOverlay).toHaveBeenCalled();+ });++ it('sets arrowEl className to event-track-arrows', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([50, 25]);++ getArrows([[10, 20], [0, 0]], map, false);+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const arrowEl = overlayEl.querySelector('div');+ expect(arrowEl.className).toBe('event-track-arrows');+ });++ it('sets backgroundSize when isHighlighted is true', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([50, 25]);++ getArrows([[10, 20], [0, 0]], map, true);+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const arrowEl = overlayEl.querySelector('div');+ expect(arrowEl.style.backgroundSize).toBe('200px');+ });++ it('leaves backgroundSize empty when isHighlighted is false', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([50, 25]);++ getArrows([[10, 20], [0, 0]], map, false);+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const arrowEl = overlayEl.querySelector('div');+ expect(arrowEl.style.backgroundSize).toBe('');+ });++ it('computes the rotation angle from coordinate delta and map rotation', () => {+ const map = buildMap();+ map.getView().getRotation.mockReturnValue(0);+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 0]);+ map.getCoordinateFromPixel.mockReturnValue([50, 0]);++ // dxCoord = 10-0=10, dyCoord = 20-0=20 → angle = atan2(20,10) in degrees+ getArrows([[10, 20], [0, 0]], map, false);+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ const expectedAngle = -(Math.atan2(20, 10) * (180 / Math.PI));+ expect(overlayEl.style.transform).toContain(`rotate(${expectedAngle}deg)`);+ });++ it('sets overlay id based on midpoint pixel coordinates', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([50, 25]);++ getArrows([[10, 20], [0, 0]], map, false);+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.id).toContain('arrow');+ });++ it('calls getCoordinateFromPixel to set the overlay position', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([50, 25]);++ getArrows([[10, 20], [0, 0]], map, false);+ expect(map.getCoordinateFromPixel).toHaveBeenCalled();+ });++ it('sets overlayEl dimensions to 1px × 1px', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([50, 25]);++ getArrows([[10, 20], [0, 0]], map, false);+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ expect(overlayEl.style.width).toBe('1px');+ expect(overlayEl.style.height).toBe('1px');+ });+ });++ // -------------------------------------------------------------------------+ // getTrackLines+ // -------------------------------------------------------------------------+ describe('getTrackLines()', () => {+ it('returns undefined when trackCoords is empty', () => {+ const map = buildMap();+ const result = getTrackLines(map, [], 'event-1', '2023-01-01', jest.fn(), defaultHighlightOptions());+ expect(result).toBeUndefined();+ });++ it('returns an OlOverlay when trackCoords has entries', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ defaultHighlightOptions(),+ );+ expect(OlOverlay).toHaveBeenCalled();+ });++ it('sets overlay id to event-track-{eventID}', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ defaultHighlightOptions(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.id).toBe('event-track-event-1');+ });++ it('uses highlighted-track-line class when isHighlighted is true', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ { ...defaultHighlightOptions(), isHighlighted: true },+ );+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.className).toContain('highlighted-track-line');+ });++ it('uses event-track-line class when isHighlighted is false', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ defaultHighlightOptions(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.className).toBe('event-track-line');+ });++ it('creates SVG polyline elements for each track segment', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ defaultHighlightOptions(),+ );+ const svgEl = OlOverlay.mock.calls[0][0].element;+ const polylines = svgEl.querySelectorAll('polyline');+ // 3 polylines per segment: outline, click, line+ expect(polylines.length).toBe(3);+ });++ it('sets stroke to yellow on the line polyline when isHighlighted is true', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ { ...defaultHighlightOptions(), isHighlighted: true },+ );+ const svgEl = OlOverlay.mock.calls[0][0].element;+ // Last polyline is the visible line element+ const polylines = svgEl.querySelectorAll('polyline');+ const lineEl = polylines[polylines.length - 1];+ expect(lineEl.style.stroke).toBe('yellow');+ });++ it('calls callback with eventID and date when clickEl is clicked', () => {+ const callback = jest.fn();+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ callback,+ defaultHighlightOptions(),+ );+ const svgEl = OlOverlay.mock.calls[0][0].element;+ const clickEl = svgEl.querySelector('.clickable-track-line');+ clickEl.onclick();+ expect(callback).toHaveBeenCalledWith('event-1', '2023-01-01');+ });++ it('calls callbackHighlight when clickEl mouseover fires', () => {+ const callbackHighlight = jest.fn();+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ { ...defaultHighlightOptions(), callbackHighlight },+ );+ const svgEl = OlOverlay.mock.calls[0][0].element;+ const clickEl = svgEl.querySelector('.clickable-track-line');+ clickEl.onmouseover();+ expect(callbackHighlight).toHaveBeenCalledWith('event-1', '2023-01-01');+ });++ it('calls callbackUnhighlight when clickEl mouseleave fires', () => {+ const callbackUnhighlight = jest.fn();+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ { ...defaultHighlightOptions(), callbackUnhighlight },+ );+ const svgEl = OlOverlay.mock.calls[0][0].element;+ const clickEl = svgEl.querySelector('.clickable-track-line');+ clickEl.onmouseleave();+ expect(callbackUnhighlight).toHaveBeenCalled();+ });++ it('handles multiple track segments correctly', () => {+ const map = buildMap();+ map.getPixelFromCoordinate+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([50, 25])+ .mockReturnValueOnce([50, 25])+ .mockReturnValueOnce([100, 50])+ .mockReturnValueOnce([0, 0])+ .mockReturnValueOnce([50, 25])+ .mockReturnValueOnce([50, 25])+ .mockReturnValueOnce([100, 50]);+ map.getCoordinateFromPixel.mockReturnValue([0, 0]);++ getTrackLines(+ map,+ [[[0, 0], [5, 5]], [[5, 5], [10, 10]]],+ 'event-1',+ '2023-01-01',+ jest.fn(),+ defaultHighlightOptions(),+ );+ const svgEl = OlOverlay.mock.calls[0][0].element;+ const polylines = svgEl.querySelectorAll('polyline');+ expect(polylines.length).toBe(6); // 3 per segment × 2 segments+ });+ });++ // -------------------------------------------------------------------------+ // getClusterPointEl+ // -------------------------------------------------------------------------+ describe('getClusterPointEl()', () => {+ const buildCluster = (overrides = {}) => ({+ geometry: {+ coordinates: [10, 20],+ ...overrides.geometry,+ },+ properties: {+ cluster_id: 'cluster-1',+ point_count_abbreviated: 5,+ startDate: '2023-01-01',+ endDate: '2023-01-10',+ ...overrides.properties,+ },+ });++ const buildPointClusterObj = () => ({+ getClusterExpansionZoom: jest.fn(() => 7),+ });++ it('returns an OlOverlay instance', () => {+ const map = buildMap();+ getClusterPointEl(geographicProj(), buildCluster(), map, buildPointClusterObj());+ expect(OlOverlay).toHaveBeenCalled();+ });++ it('uses geographic coordinates unchanged when proj is geographic', () => {+ const map = buildMap();+ getClusterPointEl(geographicProj(), buildCluster(), map, buildPointClusterObj());+ expect(olProj.transform).not.toHaveBeenCalled();+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.position).toEqual([10, 20]);+ });++ it('transforms coordinates for polar projections', () => {+ const map = buildMap();+ getClusterPointEl(polarProj(), buildCluster(), map, buildPointClusterObj());+ expect(olProj.transform).toHaveBeenCalledWith([10, 20], 'EPSG:4326', 'EPSG:3413');+ });++ it('sets overlay id to clusterId + startDate + endDate', () => {+ const map = buildMap();+ getClusterPointEl(geographicProj(), buildCluster(), map, buildPointClusterObj());+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.id).toBe('cluster-12023-01-012023-01-10');+ });++ it('sets the cluster className to event-track-cluster-point', () => {+ const map = buildMap();+ getClusterPointEl(geographicProj(), buildCluster(), map, buildPointClusterObj());+ const opts = OlOverlay.mock.calls[0][0];+ expect(opts.className).toBe('event-track-cluster-point');+ });++ it('assigns small size class for point count < 10', () => {+ const map = buildMap();+ getClusterPointEl(+ geographicProj(),+ buildCluster({ properties: { point_count_abbreviated: 5 } }),+ map,+ buildPointClusterObj(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ const circleEl = opts.element.querySelector('div');+ expect(circleEl.className).toContain('cluster-marker-small');+ });++ it('assigns medium size class for point count between 10 and 19', () => {+ const map = buildMap();+ getClusterPointEl(+ geographicProj(),+ buildCluster({ properties: { point_count_abbreviated: 15 } }),+ map,+ buildPointClusterObj(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ const circleEl = opts.element.querySelector('div');+ expect(circleEl.className).toContain('cluster-marker-medium');+ });++ it('assigns large size class for point count >= 20', () => {+ const map = buildMap();+ getClusterPointEl(+ geographicProj(),+ buildCluster({ properties: { point_count_abbreviated: 25 } }),+ map,+ buildPointClusterObj(),+ );+ const opts = OlOverlay.mock.calls[0][0];+ const circleEl = opts.element.querySelector('div');+ expect(circleEl.className).toContain('cluster-marker-large');+ });++ it('calls mapUtilZoomAction with correct args when circleEl is clicked', () => {+ const map = buildMap();+ const view = map.getView();+ view.getZoom.mockReturnValue(4);+ const pointClusterObj = buildPointClusterObj();+ pointClusterObj.getClusterExpansionZoom.mockReturnValue(7);++ getClusterPointEl(geographicProj(), buildCluster(), map, pointClusterObj);+ const circleEl = OlOverlay.mock.calls[0][0].element.querySelector('div');+ circleEl.onclick();++ expect(mapUtilZoomAction).toHaveBeenCalledWith(+ map,+ 7 - 4, // zoomTo - mapZoom+ 450,+ [10, 20],+ );+ });++ it('calls formatDisplayDate for startDate and endDate', () => {+ const map = buildMap();+ getClusterPointEl(geographicProj(), buildCluster(), map, buildPointClusterObj());+ expect(formatDisplayDate).toHaveBeenCalledWith('2023-01-01');+ expect(formatDisplayDate).toHaveBeenCalledWith('2023-01-10');+ });++ it('sets the correct class names on overlayEl and textEl', () => {+ const map = buildMap();+ getClusterPointEl(geographicProj(), buildCluster(), map, buildPointClusterObj());+ const overlayEl = OlOverlay.mock.calls[0][0].element;+ expect(overlayEl.className).toBe('cluster-track-marker-case track-marker-case');+ const textEl = overlayEl.querySelector('span');+ expect(textEl.className).toBe('cluster-track-marker-date track-marker-date');+ });+ });});diff --git a/web/js/map/runningdata.test.js b/web/js/map/runningdata.test.jsindex 870631e8c..602d7891f 100644--- a/web/js/map/runningdata.test.js+++ b/web/js/map/runningdata.test.js@@ -1,3 +1,669 @@-test('runningdata map test', () => {+/* eslint-disable new-cap */+import MapRunningData from './runningdata';+// =============================================================================+// Mocks+// =============================================================================++const mockTrigger = jest.fn();+jest.mock('../util/util', () => ({+ __esModule: true,+ default: {+ events: { trigger: (...args) => mockTrigger(...args) },+ rgbaToHex: jest.fn((r, g, b, a) => `#${r}${g}${b}${a}`),+ },+}));++jest.mock('../util/constants', () => ({+ MAP_RUNNING_DATA: 'MAP_RUNNING_DATA',+}));++const mockGetPalette = jest.fn();+jest.mock('../modules/palettes/selectors', () => ({+ getPalette: (...args) => mockGetPalette(...args),+}));++const mockIsFromActiveCompareRegion = jest.fn();+jest.mock('../modules/compare/util', () => ({+ isFromActiveCompareRegion: (...args) => mockIsFromActiveCompareRegion(...args),+}));++const mockContainsCoordinate = jest.fn();+jest.mock('ol/extent', () => ({+ containsCoordinate: (...args) => mockContainsCoordinate(...args),+}));++// =============================================================================+// Shared test helpers+// =============================================================================++const buildStore = (overrides = {}) => ({+ getState: jest.fn().mockReturnValue({+ proj: { id: 'geographic' },+ compare: { active: false },+ sidebar: { isCollapsed: false },+ ...overrides,+ }),+});++const buildMap = ({+ coordinate = [10, 20],+ layers = [],+ features = [],+} = {}) => ({+ getCoordinateFromPixel: jest.fn().mockReturnValue(coordinate),+ getAllLayers: jest.fn().mockReturnValue(layers),+ forEachFeatureAtPixel: jest.fn((pixel, cb) => {+ features.forEach(({ feature, layer }) => cb(feature, layer));+ }),+});++// A minimal valid raster layer+const buildRasterLayer = ({+ id = 'test-layer',+ hasPalette = true,+ type = 'wmts',+ isVector = false,+ data = [255, 0, 0, 255],+ isCollapsed = false,+ granuleGroup = null,+} = {}) => ({+ isVector,+ getData: jest.fn().mockReturnValue(data),+ get: jest.fn((key) => {+ if (key === 'granuleGroup') return granuleGroup;+ if (key === 'extent') return [-180, -90, 180, 90];+ return null;+ }),+ wv: {+ def: {+ id,+ type,+ palette: hasPalette ? { id } : null,+ },+ group: 'active',+ },+});++// A minimal valid vector layer+const buildVectorLayer = ({+ id = 'vector-layer',+ palette = { styleProperty: 'category' },+ colormapType = undefined,+ type = 'vector',+ wrapadjacentdays = false,+ wrapX = false,+ hasPalette = true,+ featureOutside = false,+ inCompareRegion = true,+ isCollapsed = false,+} = {}) => {+ mockContainsCoordinate.mockReturnValue(!featureOutside);+ mockIsFromActiveCompareRegion.mockReturnValue(inCompareRegion);+ return {+ isVector: true,+ get: jest.fn((key) => {+ if (key === 'extent') return [-180, -90, 180, 90];+ return null;+ }),+ wv: {+ def: {+ id,+ type,+ colormapType,+ palette: hasPalette ? palette : {},+ wrapadjacentdays,+ wrapX,+ },+ group: 'active',+ },+ };+};++const buildFeature = (props = {}) => ({+ getProperties: jest.fn().mockReturnValue(props),+});++const buildPaletteLegend = ({+ colors = ['ff0000ff'],+ tooltips = ['category'],+} = {}) => ({+ legend: { colors, tooltips },+});++// =============================================================================+// clearAll+// =============================================================================++describe('clearAll', () => {+ beforeEach(() => jest.clearAllMocks());++ test('does not trigger an event when dataObj is already empty', () => {+ const rd = MapRunningData(null, buildStore());+ rd.clearAll();+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('triggers MAP_RUNNING_DATA with an empty object when dataObj is non-empty', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(buildPaletteLegend());+ const rd = MapRunningData(null, store);++ const layer = buildRasterLayer();+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);+ mockTrigger.mockClear();++ rd.clearAll();+ expect(mockTrigger).toHaveBeenCalledWith('MAP_RUNNING_DATA', {});+ });++ test('does not trigger a second time if clearAll is called again on already-empty state', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(buildPaletteLegend());+ const rd = MapRunningData(null, store);++ const layer = buildRasterLayer();+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);++ rd.clearAll();+ mockTrigger.mockClear();+ rd.clearAll();+ expect(mockTrigger).not.toHaveBeenCalled();+ });+});++// =============================================================================+// newPoint — swipeOffset / compareUi+// =============================================================================++describe('newPoint — compareUi / swipeOffset', () => {+ beforeEach(() => jest.clearAllMocks());++ test('reads swipeOffset from compareUi when compare is active', () => {+ const compareUi = { getOffset: jest.fn().mockReturnValue(50.7) };+ const store = buildStore({ compare: { active: true } });+ const rd = MapRunningData(compareUi, store);+ const map = buildMap();+ rd.newPoint([0, 0], map);+ expect(compareUi.getOffset).toHaveBeenCalled();+ });++ test('does not call getOffset when compare is inactive', () => {+ const compareUi = { getOffset: jest.fn() };+ const store = buildStore({ compare: { active: false } });+ const rd = MapRunningData(compareUi, store);+ const map = buildMap();+ rd.newPoint([0, 0], map);+ expect(compareUi.getOffset).not.toHaveBeenCalled();+ });++ test('does not throw when compareUi is null and compare is inactive', () => {+ const store = buildStore({ compare: { active: false } });+ const rd = MapRunningData(null, store);+ expect(() => rd.newPoint([0, 0], buildMap())).not.toThrow();+ });+});++// =============================================================================+// newPoint — raster layer processing+// =============================================================================++describe('newPoint — raster layers', () => {+ beforeEach(() => jest.clearAllMocks());++ test('adds a raster layer entry and triggers MAP_RUNNING_DATA', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(buildPaletteLegend());+ const rd = MapRunningData(null, store);++ const layer = buildRasterLayer({ id: 'my-layer', data: [255, 128, 0, 255] });+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);++ expect(mockTrigger).toHaveBeenCalledWith(+ 'MAP_RUNNING_DATA',+ expect.objectContaining({ 'my-layer': expect.any(Object) }),+ );+ });++ test('stores paletteLegends and paletteHex from rgbaToHex in the layer entry', () => {+ const store = buildStore();+ const paletteLegend = buildPaletteLegend();+ mockGetPalette.mockReturnValue(paletteLegend);+ const util = require('../util/util').default;+ util.rgbaToHex.mockReturnValue('#ff0000ff');+ const rd = MapRunningData(null, store);++ const layer = buildRasterLayer({ id: 'my-layer', data: [255, 0, 0, 255] });+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);++ expect(mockTrigger).toHaveBeenCalledWith(+ 'MAP_RUNNING_DATA',+ expect.objectContaining({+ 'my-layer': { paletteLegends: paletteLegend, paletteHex: '#ff0000ff' },+ }),+ );+ });++ test('skips a raster layer when sidebar is collapsed', () => {+ const store = buildStore({ sidebar: { isCollapsed: true } });+ const rd = MapRunningData(null, store);+ const layer = buildRasterLayer();+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('skips a raster layer when it has no palette', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = buildRasterLayer({ hasPalette: false });+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('skips a raster layer when isVector is true', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = buildRasterLayer({ isVector: true });+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('skips a raster layer of type granule that has no granuleGroup', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = buildRasterLayer({ type: 'granule', granuleGroup: null });+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('does not skip a granule layer that has a granuleGroup', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(buildPaletteLegend());+ const rd = MapRunningData(null, store);+ const layer = buildRasterLayer({ type: 'granule', granuleGroup: 'group1' });+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });++ test('skips a raster layer when getData returns null', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = buildRasterLayer({ data: null });+ const map = buildMap({ layers: [layer] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('does not re-trigger when newPoint produces the same data object', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(buildPaletteLegend());+ const util = require('../util/util').default;+ util.rgbaToHex.mockReturnValue('#ff0000ff');+ const rd = MapRunningData(null, store);++ const layer = buildRasterLayer({ id: 'same-layer', data: [255, 0, 0, 255] });+ const map = buildMap({ layers: [layer] });++ rd.newPoint([0, 0], map);+ mockTrigger.mockClear();+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });+});++// =============================================================================+// newPoint — vector layer processing: shouldNotProcessVectorLayer guards+// =============================================================================++describe('newPoint — vector layer guards (shouldNotProcessVectorLayer)', () => {+ beforeEach(() => jest.clearAllMocks());++ test('skips vector layer when layer has no wv.def', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = { isVector: true, get: jest.fn(), wv: {} };+ const map = buildMap({ features: [{ feature: buildFeature(), layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('skips vector layer when sidebar is collapsed', () => {+ const store = buildStore({ sidebar: { isCollapsed: true } });+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({ isCollapsed: true });+ const map = buildMap({ features: [{ feature: buildFeature({ category: 'cat1' }), layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('skips vector layer when feature is outside extent', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({ featureOutside: true });+ const feature = buildFeature({ category: 'cat1' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('skips vector layer when not in active compare region', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({ inCompareRegion: false });+ const feature = buildFeature({ category: 'cat1' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('skips vector layer when palette is empty', () => {+ const store = buildStore();+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({ hasPalette: false });+ const feature = buildFeature({ category: 'cat1' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('does not skip a valid vector layer in geographic projection with wrapadjacentdays', () => {+ const store = buildStore({ proj: { id: 'geographic' } });+ mockGetPalette.mockReturnValue(buildPaletteLegend({ tooltips: ['cat1'] }));+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({ wrapadjacentdays: true });+ const feature = buildFeature({ category: 'cat1' });+ const map = buildMap({+ coordinate: [10, 20],+ features: [{ feature, layer }],+ });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });++ test('does not skip a valid vector layer in non-geographic projection', () => {+ const store = buildStore({ proj: { id: 'arctic' } });+ mockGetPalette.mockReturnValue(buildPaletteLegend({ tooltips: ['cat1'] }));+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer();+ const feature = buildFeature({ category: 'cat1' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });+});++// =============================================================================+// newPoint — vector layer processing: color resolution branches+// =============================================================================++describe('newPoint — vector layer color resolution', () => {+ beforeEach(() => jest.clearAllMocks());++ test('early-returns when no identifier, not continuous, and legend has more than one color', () => {+ const store = buildStore();+ const layer = buildVectorLayer({ palette: { styleProperty: null } });+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['ff0000ff', '00ff00ff'], tooltips: ['a', 'b'] }),+ );+ const feature = buildFeature({});+ const map = buildMap({ features: [{ feature, layer }] });+ const rd = MapRunningData(null, store);+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('resolves color by identifier via tooltips.indexOf for a non-AERONET layer', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['ff0000ff', '00ff00ff'], tooltips: ['cat1', 'cat2'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({ palette: { styleProperty: 'category' } });+ const feature = buildFeature({ category: 'cat2' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalledWith(+ 'MAP_RUNNING_DATA',+ expect.objectContaining({+ 'vector-layer': expect.objectContaining({ paletteHex: '00ff00ff' }),+ }),+ );+ });++ test('uses palette.unclassified when featureProps value is falsy', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['aabbccff'], tooltips: ['unknown'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: 'category', unclassified: 'unknown' },+ });+ const feature = buildFeature({ category: '' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });++ test('early-returns when value is falsy and no unclassified fallback', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(buildPaletteLegend());+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: 'category', unclassified: null },+ });+ const feature = buildFeature({ category: '' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ // ── AERONET color resolution ──++ test('resolves AERONET color via tooltips.findIndex when color is found', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['aabbccff'], tooltips: ['ab'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ id: 'AERONET_layer',+ palette: { styleProperty: 'value' },+ });+ const feature = buildFeature({ value: 'ab' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });++ test('falls back to secondary getPalette call for AERONET when first color lookup misses', () => {+ const store = buildStore();+ const primaryLegend = buildPaletteLegend({ colors: [undefined], tooltips: ['zz'] });+ const secondaryLegend = {+ legend: {+ colors: ['ddeeffff'],+ tooltips: ['0.0 – 0.5', '0.5 – 1.0'],+ },+ };+ mockGetPalette+ .mockReturnValueOnce(primaryLegend)+ .mockReturnValueOnce(secondaryLegend);+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ id: 'AERONET_layer',+ palette: { styleProperty: 'value' },+ });+ const feature = buildFeature({ value: '0.3' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockGetPalette).toHaveBeenCalledTimes(2);+ expect(mockTrigger).toHaveBeenCalled();+ });++ // ── Continuous vector layer color resolution ──++ test('resolves color for continuous vector layer using ≥ tooltip', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['ff0000ff'], tooltips: ['≥ 10'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: 'continuous',+ type: 'vector',+ });+ const feature = buildFeature({ Value: '15' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalledWith(+ 'MAP_RUNNING_DATA',+ expect.objectContaining({+ 'vector-layer': expect.objectContaining({ paletteHex: 'ff0000ff' }),+ }),+ );+ });++ test('resolves color for continuous vector layer using > tooltip', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['00ff00ff'], tooltips: ['> 5'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: 'continuous',+ type: 'vector',+ });+ const feature = buildFeature({ Value: '10' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });++ test('resolves color for continuous vector layer using ≤ tooltip', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['0000ffff'], tooltips: ['≤ 20'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: 'continuous',+ type: 'vector',+ });+ const feature = buildFeature({ Value: '10' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });++ test('resolves color for continuous vector layer using < tooltip', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['ffff00ff'], tooltips: ['< 50'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: 'continuous',+ type: 'vector',+ });+ const feature = buildFeature({ Value: '25' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalled();+ });++ test('resolves color for continuous vector layer using range tooltip (n-m)', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['112233ff'], tooltips: ['10-20'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: 'continuous',+ type: 'vector',+ });+ const feature = buildFeature({ Value: '15' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalledWith(+ 'MAP_RUNNING_DATA',+ expect.objectContaining({+ 'vector-layer': expect.objectContaining({ paletteHex: '112233ff' }),+ }),+ );+ });++ test('early-returns for continuous vector layer when Value is not numeric', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['ff0000ff'], tooltips: ['10-20'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: 'continuous',+ type: 'vector',+ });+ const feature = buildFeature({ Value: 'not-a-number' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).not.toHaveBeenCalled();+ });++ test('uses single color directly when legend has exactly one color and no identifier', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['abcdefff'], tooltips: [] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: undefined,+ type: 'vector',+ });+ const feature = buildFeature({});+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalledWith(+ 'MAP_RUNNING_DATA',+ expect.objectContaining({+ 'vector-layer': expect.objectContaining({ paletteHex: 'abcdefff' }),+ }),+ );+ });++ test('tooltip with no matching operator returns false (color resolves to undefined)', () => {+ const store = buildStore();+ mockGetPalette.mockReturnValue(+ buildPaletteLegend({ colors: ['ff0000ff'], tooltips: ['no match tooltip'] }),+ );+ const rd = MapRunningData(null, store);+ const layer = buildVectorLayer({+ palette: { styleProperty: null },+ colormapType: 'continuous',+ type: 'vector',+ });+ const feature = buildFeature({ Value: '5' });+ const map = buildMap({ features: [{ feature, layer }] });+ rd.newPoint([0, 0], map);+ expect(mockTrigger).toHaveBeenCalledWith(+ 'MAP_RUNNING_DATA',+ expect.objectContaining({+ 'vector-layer': expect.objectContaining({ paletteHex: undefined }),+ }),+ );+ });});diff --git a/web/js/map/util.test.js b/web/js/map/util.test.jsindex 06ae26670..a4cef9fb9 100644--- a/web/js/map/util.test.js+++ b/web/js/map/util.test.js@@ -1,3 +1,629 @@-test('util map test', () => {+import {+ mapUtilZoomAction,+ saveRotation,+ fly,+ getExtent,+ crossesDateLine,+ getOverDateLineCoordinates,+ getGeographicResolutionWMS,+ createVectorUrl,+ mergeBreakpointLayerAttributes,+ updateReduxDateTimezone,+ formatReduxDate,+ extractDateFromTileErrorURL,+} from './util';+// =============================================================================+// Mocks+// =============================================================================++// Mock constants so tests are not coupled to their actual array values+jest.mock('../modules/map/constants', () => ({+ RESOLUTION_FOR_LARGE_WMS_TILES: ['large'],+ RESOLUTION_FOR_SMALL_WMS_TILES: ['small'],+}));++// Mock ol/extent+const mockContainsCoordinate = jest.fn();+const mockGetCenter = jest.fn();+jest.mock('ol/extent', () => ({+ containsCoordinate: (...args) => mockContainsCoordinate(...args),+ getCenter: (...args) => mockGetCenter(...args),+}));++// Mock ol/geom/LineString+const mockGetLength = jest.fn();+jest.mock('ol/geom/LineString', () =>+ jest.fn().mockImplementation(() => ({ getLength: mockGetLength })),+);++// Mock util (the util/util default export used inside this file)+const mockToISOStringSeconds = jest.fn((date) => date ? date.toISOString() : '');+const mockRoundTimeOneMinute = jest.fn((date) => date);+jest.mock('../util/util', () => ({+ __esModule: true,+ default: {+ toISOStringSeconds: (...args) => mockToISOStringSeconds(...args),+ roundTimeOneMinute: (...args) => mockRoundTimeOneMinute(...args),+ },+}));++// =============================================================================+// Helpers+// =============================================================================++const buildView = ({+ zoom = 4,+ minZoom = 1,+ maxZoom = 10,+ isAnimating = false,+ center = [0, 0],+ extent = [-180, -90, 180, 90],+ resolutionForZoom = jest.fn().mockReturnValue(0.1),+} = {}) => ({+ getZoom: jest.fn().mockReturnValue(zoom),+ getMinZoom: jest.fn().mockReturnValue(minZoom),+ getMaxZoom: jest.fn().mockReturnValue(maxZoom),+ getAnimating: jest.fn().mockReturnValue(isAnimating),+ animate: jest.fn(),+ cancelAnimations: jest.fn(),+ getCenter: jest.fn().mockReturnValue(center),+ calculateExtent: jest.fn().mockReturnValue(extent),+ getResolutionForZoom: resolutionForZoom,+ setRotation: jest.fn(),+});++const buildMap = (view) => ({+ getView: jest.fn().mockReturnValue(view),+});++const buildProj = (id = 'geographic') => ({+ selected: { id },+});++// =============================================================================+// mapUtilZoomAction+// =============================================================================++describe('mapUtilZoomAction', () => {+ beforeEach(() => jest.clearAllMocks());++ test('animates to zoom + amount with default duration when not animating', () => {+ const view = buildView({ zoom: 4 });+ const map = buildMap(view);+ mapUtilZoomAction(map, 1);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ zoom: 5, duration: 250 }),+ );+ });++ test('uses zero duration when view is already animating', () => {+ const view = buildView({ zoom: 4, isAnimating: true });+ const map = buildMap(view);+ mapUtilZoomAction(map, 1);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ zoom: 5, duration: 0 }),+ );+ });++ test('uses provided duration instead of default', () => {+ const view = buildView({ zoom: 4 });+ const map = buildMap(view);+ mapUtilZoomAction(map, 1, 500);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ duration: 500 }),+ );+ });++ test('passes center to animate when provided', () => {+ const view = buildView({ zoom: 4 });+ const map = buildMap(view);+ mapUtilZoomAction(map, 1, 250, [10, 20]);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ center: [10, 20] }),+ );+ });++ test('clamps newZoom to maxZoom when it would exceed max', () => {+ const view = buildView({ zoom: 9, maxZoom: 10 });+ const map = buildMap(view);+ mapUtilZoomAction(map, 5);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ zoom: 10 }),+ );+ });++ test('clamps newZoom to minZoom when it would go below min', () => {+ const view = buildView({ zoom: 2, minZoom: 1 });+ const map = buildMap(view);+ mapUtilZoomAction(map, -5);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ zoom: 1 }),+ );+ });++ test('does not animate when already at maxZoom and would exceed it', () => {+ const view = buildView({ zoom: 10, maxZoom: 10 });+ const map = buildMap(view);+ mapUtilZoomAction(map, 1);+ expect(view.animate).not.toHaveBeenCalled();+ });++ test('does not animate when already at minZoom and would go below it', () => {+ const view = buildView({ zoom: 1, minZoom: 1 });+ const map = buildMap(view);+ mapUtilZoomAction(map, -1);+ expect(view.animate).not.toHaveBeenCalled();+ });++ test('zooms by a negative amount (zoom out)', () => {+ const view = buildView({ zoom: 6 });+ const map = buildMap(view);+ mapUtilZoomAction(map, -2);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ zoom: 4 }),+ );+ });+});++// =============================================================================+// saveRotation+// =============================================================================++describe('saveRotation', () => {+ beforeEach(() => jest.clearAllMocks());++ test('sets rotation to 0 when absolute value of currentDeg is exactly 360', () => {+ const view = buildView();+ saveRotation(360, view);+ expect(view.setRotation).toHaveBeenCalledWith(0);+ });++ test('sets rotation to 0 for -360 as well', () => {+ const view = buildView();+ saveRotation(-360, view);+ expect(view.setRotation).toHaveBeenCalledWith(0);+ });++ test('sets a positive newNadVal when currentDeg > 360', () => {+ const view = buildView();+ saveRotation(370, view);+ expect(view.setRotation).toHaveBeenCalledWith(-((360 - Math.abs(370)) * (Math.PI / 180)));+ });++ test('sets a negative newNadVal (positive rotation) when currentDeg < -360', () => {+ const view = buildView();+ saveRotation(-370, view);+ const newNadVal = (360 - Math.abs(-370)) * (Math.PI / 180);+ expect(view.setRotation).toHaveBeenCalledWith(newNadVal);+ });++ test('does not call setRotation when currentDeg is less than 360', () => {+ const view = buildView();+ saveRotation(180, view);+ expect(view.setRotation).not.toHaveBeenCalled();+ });++ test('does not call setRotation for 0 degrees', () => {+ const view = buildView();+ saveRotation(0, view);+ expect(view.setRotation).not.toHaveBeenCalled();+ });+});++// =============================================================================+// getExtent+// =============================================================================++describe('getExtent', () => {+ test('returns [-250,-90,250,90] for geographic projection', () => {+ expect(getExtent({ selected: { id: 'geographic' } })).toEqual([-250, -90, 250, 90]);+ });++ test('returns [-180,-90,180,90] for arctic projection', () => {+ expect(getExtent({ selected: { id: 'arctic' } })).toEqual([-180, -90, 180, 90]);+ });++ test('returns [-180,-90,180,90] for antarctic projection', () => {+ expect(getExtent({ selected: { id: 'antarctic' } })).toEqual([-180, -90, 180, 90]);+ });+});++// =============================================================================+// crossesDateLine+// =============================================================================++describe('crossesDateLine', () => {+ test('returns true when coordinates are more than 180 degrees apart', () => {+ expect(crossesDateLine([170], [-170])).toBe(true);+ });++ test('returns false when coordinates are exactly 180 degrees apart', () => {+ expect(crossesDateLine([0], [180])).toBe(false);+ });++ test('returns false when coordinates are less than 180 degrees apart', () => {+ expect(crossesDateLine([10], [50])).toBe(false);+ });++ test('returns true for a large negative to positive crossing', () => {+ expect(crossesDateLine([-179], [179])).toBe(true);+ });+});++// =============================================================================+// getOverDateLineCoordinates+// =============================================================================++describe('getOverDateLineCoordinates', () => {+ test('returns mirrored longitude for a negative longitude', () => {+ const result = getOverDateLineCoordinates([-170, 45]);+ expect(result).toEqual([Math.abs(180 + 180 - Math.abs(-170)), 45]);+ });++ test('returns negative mirrored longitude for a positive longitude', () => {+ const result = getOverDateLineCoordinates([170, 45]);+ expect(result).toEqual([-Math.abs(180 + 180 - Math.abs(170)), 45]);+ });++ test('preserves the latitude value', () => {+ const result = getOverDateLineCoordinates([-160, -30]);+ expect(result[1]).toBe(-30);+ });+});++// =============================================================================+// getGeographicResolutionWMS+// =============================================================================++describe('getGeographicResolutionWMS', () => {+ test('returns RESOLUTION_FOR_LARGE_WMS_TILES when tileSize is null', () => {+ expect(getGeographicResolutionWMS(null)).toEqual(['large']);+ });++ test('returns RESOLUTION_FOR_LARGE_WMS_TILES when tileSize is undefined', () => {+ expect(getGeographicResolutionWMS(undefined)).toEqual(['large']);+ });++ test('returns RESOLUTION_FOR_LARGE_WMS_TILES when tileSize is an empty array', () => {+ expect(getGeographicResolutionWMS([])).toEqual(['large']);+ });++ test('returns RESOLUTION_FOR_SMALL_WMS_TILES when tileSize[0] is 256', () => {+ expect(getGeographicResolutionWMS([256, 256])).toEqual(['small']);+ });++ test('returns RESOLUTION_FOR_LARGE_WMS_TILES when tileSize[0] is 512', () => {+ expect(getGeographicResolutionWMS([512, 512])).toEqual(['large']);+ });++ test('returns RESOLUTION_FOR_LARGE_WMS_TILES when tileSize[0] is any value other than 256', () => {+ expect(getGeographicResolutionWMS([1024, 1024])).toEqual(['large']);+ });+});++// =============================================================================+// createVectorUrl+// =============================================================================++describe('createVectorUrl', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockRoundTimeOneMinute.mockImplementation((date) => date);+ mockToISOStringSeconds.mockReturnValue('2021-01-01T00:00:00Z');+ });++ test('returns a URL string starting with ?', () => {+ const url = createVectorUrl(new Date('2021-01-01'), 'my-layer', 'EPSG4326');+ expect(url).toMatch(/^\?/);+ });++ test('includes TIME parameter', () => {+ const url = createVectorUrl(new Date('2021-01-01'), 'my-layer', 'EPSG4326');+ expect(url).toContain('TIME=2021-01-01T00:00:00Z');+ });++ test('includes layer parameter', () => {+ const url = createVectorUrl(new Date('2021-01-01'), 'my-layer', 'EPSG4326');+ expect(url).toContain('layer=my-layer');+ });++ test('includes tilematrixset parameter', () => {+ const url = createVectorUrl(new Date('2021-01-01'), 'my-layer', 'EPSG4326');+ expect(url).toContain('tilematrixset=EPSG4326');+ });++ test('includes static WMTS parameters', () => {+ const url = createVectorUrl(new Date('2021-01-01'), 'my-layer', 'EPSG4326');+ expect(url).toContain('Service=WMTS');+ expect(url).toContain('Request=GetTile');+ expect(url).toContain('Version=1.0.0');+ expect(url).toContain('FORMAT=application%2Fvnd.mapbox-vector-tile');+ expect(url).toContain('TileMatrix={z}');+ expect(url).toContain('TileCol={x}');+ expect(url).toContain('TileRow={y}');+ });++ test('calls roundTimeOneMinute and toISOStringSeconds with the date', () => {+ const date = new Date('2021-01-01');+ createVectorUrl(date, 'my-layer', 'EPSG4326');+ expect(mockRoundTimeOneMinute).toHaveBeenCalledWith(date);+ expect(mockToISOStringSeconds).toHaveBeenCalled();+ });+});++// =============================================================================+// mergeBreakpointLayerAttributes+// =============================================================================++describe('mergeBreakpointLayerAttributes', () => {+ test('returns def unchanged when no breakPointLayer is present', () => {+ const def = { id: 'layer-1', type: 'wmts' };+ expect(mergeBreakpointLayerAttributes(def, 'geographic')).toBe(def);+ });++ test('merges projection-specific attributes into breakPointLayer', () => {+ const def = {+ id: 'layer-1',+ breakPointLayer: {+ resolutionBreakPoint: 100,+ projections: {+ geographic: { resolutionBreakPoint: 500, extraProp: 'geo' },+ },+ },+ };+ const result = mergeBreakpointLayerAttributes(def, 'geographic');+ expect(result.breakPointLayer.resolutionBreakPoint).toBe(500);+ expect(result.breakPointLayer.extraProp).toBe('geo');+ });++ test('still includes non-projection-specific breakPointLayer properties after merge', () => {+ const def = {+ id: 'layer-1',+ breakPointLayer: {+ breakPointType: 'max',+ projections: {+ geographic: { resolutionBreakPoint: 500 },+ },+ },+ };+ const result = mergeBreakpointLayerAttributes(def, 'geographic');+ expect(result.breakPointLayer.breakPointType).toBe('max');+ });++ test('returns a new object (does not mutate original def)', () => {+ const def = {+ id: 'layer-1',+ breakPointLayer: {+ projections: { geographic: { resolutionBreakPoint: 500 } },+ },+ };+ const result = mergeBreakpointLayerAttributes(def, 'geographic');+ expect(result).not.toBe(def);+ });++ test('works for a non-geographic projection key', () => {+ const def = {+ id: 'layer-1',+ breakPointLayer: {+ projections: {+ arctic: { resolutionBreakPoint: 200 },+ },+ },+ };+ const result = mergeBreakpointLayerAttributes(def, 'arctic');+ expect(result.breakPointLayer.resolutionBreakPoint).toBe(200);+ });+});++// =============================================================================+// updateReduxDateTimezone+// =============================================================================++describe('updateReduxDateTimezone', () => {+ test('returns a string in YYYY-MM-DDTHH:MM:00 format', () => {+ const result = updateReduxDateTimezone(+ '2021-06-15T10:30:00',+ '2021-06-15T10:30:00',+ );+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00$/);+ });++ test('rounds minutes down to the nearest multiple of 10', () => {+ const result = updateReduxDateTimezone(+ '2021-06-15T10:37:00',+ '2021-06-15T10:37:00',+ );+ const minutes = parseInt(result.split('T')[1].split(':')[1], 10);+ expect(minutes % 10).toBe(0);+ });++ test('rounds minutes of 0 to 0', () => {+ const result = updateReduxDateTimezone(+ '2021-06-15T10:00:00',+ '2021-06-15T10:00:00',+ );+ const minutes = result.split('T')[1].split(':')[1];+ expect(minutes).toBe('00');+ });++ test('rounds minutes of 59 down to 50', () => {+ const result = updateReduxDateTimezone(+ '2021-06-15T10:59:00',+ '2021-06-15T10:59:00',+ );+ const minutes = result.split('T')[1].split(':')[1];+ expect(minutes).toBe('50');+ });++ test('ends with :00 seconds always', () => {+ const result = updateReduxDateTimezone(+ '2021-06-15T10:30:45',+ '2021-06-15T10:30:45',+ );+ expect(result.endsWith(':00')).toBe(true);+ });+});++// =============================================================================+// formatReduxDate+// =============================================================================++describe('formatReduxDate', () => {+ test('returns date-only format (T00:00:00) when not a subdaily layer', () => {+ const result = formatReduxDate('2021-06-15T10:30:00', '2021-06-15T10:30:00', false);+ expect(result).toBe('2021-06-15T00:00:00');+ });++ test('returns timezone-adjusted string when isSubdailyLayer is true', () => {+ const result = formatReduxDate('2021-06-15T10:30:00', '2021-06-15T10:30:00', true);+ expect(result).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00$/);+ });++ test('zero-pads single-digit months and days for non-subdaily', () => {+ const result = formatReduxDate('2021-01-05T00:00:00', null, false);+ expect(result).toBe('2021-01-05T00:00:00');+ });++ test('returns non-subdaily format regardless of time in reduxDate', () => {+ const result = formatReduxDate('2021-12-31T23:59:59', null, false);+ expect(result).toBe('2021-12-31T00:00:00');+ });+});++// =============================================================================+// extractDateFromTileErrorURL+// =============================================================================++describe('extractDateFromTileErrorURL', () => {+ test('extracts a full datetime string (with time) from a URL', () => {+ const url = 'https://example.com/tiles?TIME=2021-06-15T12:30:00&other=param';+ expect(extractDateFromTileErrorURL(url)).toBe('2021-06-15T12:30:00');+ });++ test('returns null for a date-only TIME parameter (no time component)', () => {+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});+ const url = 'https://example.com/tiles?TIME=2021-06-15&other=param';+ const result = extractDateFromTileErrorURL(url);+ expect(result).toBeNull();+ expect(consoleSpy).toHaveBeenCalled();+ consoleSpy.mockRestore();+ });++ test('returns null and logs an error when TIME is not found in the URL', () => {+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});+ const result = extractDateFromTileErrorURL('https://example.com/tiles?layer=foo');+ expect(result).toBeNull();+ expect(consoleSpy).toHaveBeenCalled();+ consoleSpy.mockRestore();+ });++ test('returns null for an empty string URL', () => {+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});+ const result = extractDateFromTileErrorURL('');+ expect(result).toBeNull();+ consoleSpy.mockRestore();+ });+});++// =============================================================================+// fly+// =============================================================================++describe('fly', () => {+ beforeEach(() => jest.clearAllMocks());++ const buildFlyView = ({+ zoom = 4,+ center = [0, 0],+ extent = [-180, -90, 180, 90],+ hasEndInView = false,+ distance = 50,+ } = {}) => {+ mockGetLength.mockReturnValue(distance);+ mockContainsCoordinate.mockReturnValue(hasEndInView);+ mockGetCenter.mockReturnValue([0, 0]);+ return buildView({ zoom, center, extent });+ };++ test('calls cancelAnimations on the view', () => {+ const view = buildFlyView();+ const map = buildMap(view);+ fly(map, buildProj(), [10, 20], false);+ expect(view.cancelAnimations).toHaveBeenCalled();+ });++ test('returns a Promise', () => {+ const view = buildFlyView();+ const map = buildMap(view);+ const result = fly(map, buildProj(), [10, 20], false);+ expect(result).toBeInstanceOf(Promise);+ });++ test('uses getCenter of endPoint array when endPoint has more than 2 elements (is an extent)', () => {+ const view = buildFlyView();+ const map = buildMap(view);+ mockGetCenter.mockReturnValue([5, 5]);+ fly(map, buildProj(), [-10, -10, 10, 10], false);+ expect(mockGetCenter).toHaveBeenCalledWith([-10, -10, 10, 10]);+ });++ test('does not call getCenter when endPoint has exactly 2 elements', () => {+ const view = buildFlyView();+ const map = buildMap(view);+ fly(map, buildProj(), [10, 20], false);+ expect(mockGetCenter).not.toHaveBeenCalled();+ });++ test('resolves when all animations complete successfully', async () => {+ const view = buildFlyView({ hasEndInView: true });+ view.animate.mockImplementation((...args) => {+ const cb = args[args.length - 1];+ if (typeof cb === 'function') cb();+ });+ const map = buildMap(view);+ await expect(fly(map, buildProj(), [10, 20], false)).resolves.toBeDefined();+ });++ test('uses polar distance scaling when projection is not geographic', () => {+ const view = buildFlyView({ distance: 100000 });+ view.animate.mockImplementation(() => {});+ const map = buildMap(view);+ // Should not throw with polar projection+ expect(() => fly(map, buildProj('arctic'), [10, 20], false)).not.toThrow();+ });++ test('uses kiosk mode duration formula when isKioskModeActive is true', () => {+ const view = buildFlyView({ distance: 100 });+ const map = buildMap(view);+ expect(() => fly(map, buildProj(), [10, 20], true, 5, 0)).not.toThrow();+ });++ test('uses default endZoom of 5 when not provided', () => {+ const view = buildFlyView({ hasEndInView: false });+ const map = buildMap(view);+ expect(() => fly(map, buildProj(), [10, 20], false)).not.toThrow();+ });++ test('uses default rotation of 0 when not provided', () => {+ const view = buildFlyView({ hasEndInView: true });+ view.animate.mockImplementation(() => {});+ const map = buildMap(view);+ fly(map, buildProj(), [10, 20], false, 5);+ expect(view.animate).toHaveBeenCalledWith(+ expect.objectContaining({ rotation: 0 }),+ expect.any(Function),+ );+ });++ test('applies halved duration when end point is already in view and duration < 1200', () => {+ const view = buildFlyView({ hasEndInView: true, distance: 1 });+ const animateCalls = [];+ view.animate.mockImplementation((...args) => {+ animateCalls.push(args);+ });+ const map = buildMap(view);+ fly(map, buildProj(), [1, 1], false, 5, 0);+ expect(animateCalls.length).toBeGreaterThan(0);+ });});diff --git a/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.test.js b/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.test.jsindex 12191802d..d784f058a 100644--- a/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.test.js+++ b/web/js/mapUI/components/buffer-quick-animate/bufferQuickAnimate.test.js@@ -1,3 +1,294 @@-test('bufferQuickAnimate mapUI test', () => {+/* eslint-disable no-promise-executor-return */+import { render } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import ConnectedBufferQuickAnimate from './bufferQuickAnimate';++import { getNumberStepsBetween, getNextDateTime } from '../../../modules/date/util';+import { getSelectedDate } from '../../../modules/date/selectors';+import { promiseImageryForTime } from '../../../modules/map/util';++// ─── Mock Dependencies ────────────────────────────────────────────────────────++jest.mock('../../../modules/date/util', () => ({+ getNumberStepsBetween: jest.fn(),+ getNextDateTime: jest.fn(),+}));++jest.mock('../../../modules/date/selectors', () => ({+ getSelectedDate: jest.fn(),+}));++jest.mock('../../../modules/map/util', () => ({+ promiseImageryForTime: jest.fn(),+}));++jest.mock('../../../modules/date/actions', () => ({+ setPreload: jest.fn((preloaded, lastPreloadDate) => ({+ type: 'SET_PRELOAD',+ preloaded,+ lastPreloadDate,+ })),+}));++// ─── Shared Test Fixtures ─────────────────────────────────────────────────────++const mockSelectedDate = new Date('2024-01-01');+const mockLastPreloadDate = new Date('2024-01-05');+const mockNextDate = new Date('2024-01-02');++const mockStore = configureMockStore();++/**+ * Builds a mock Redux store state. Override individual slices as needed.+ */+function buildStoreState(overrides = {}) {+ return {+ date: {+ selected: mockSelectedDate,+ preloaded: false,+ lastPreloadDate: null,+ ...overrides.date,+ },+ map: {},+ proj: {},+ embed: {},+ compare: {},+ layers: {},+ palettes: {},+ vectorStyles: {},+ ...overrides,+ };+}++/**+ * Renders the connected BufferQuickAnimate inside a mock Redux Provider.+ * Accepts a store state override and an action prop.+ */+async function renderComponent(storeOverrides = {}, action = { value: null }) {+ const store = mockStore(buildStoreState(storeOverrides));+ const utils = render(+ <Provider store={store}>+ <ConnectedBufferQuickAnimate action={action} />+ </Provider>,+ );+ // Flush all promises and microtasks+ await new Promise((resolve) => setTimeout(resolve, 0));+ return { ...utils, store };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('BufferQuickAnimate', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ getSelectedDate.mockReturnValue(mockSelectedDate);+ getNextDateTime.mockReturnValue(mockNextDate);+ promiseImageryForTime.mockResolvedValue(undefined);+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', async () => {+ const { container } = await renderComponent();+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect / action trigger ─────────────────────────────────────────────++ describe('useEffect action trigger', () => {+ it('does NOT call bufferQuickAnimate when action.value is null', async () => {+ await renderComponent({}, { value: null });+ expect(promiseImageryForTime).not.toHaveBeenCalled();+ });++ it('does NOT call bufferQuickAnimate when action.value is an empty string', async () => {+ await renderComponent({}, { value: '' });+ expect(promiseImageryForTime).not.toHaveBeenCalled();+ });++ it('calls bufferQuickAnimate when action.value is "right"', async () => {+ await renderComponent({}, { value: 'right' });+ expect(promiseImageryForTime).toHaveBeenCalled();+ });++ it('calls bufferQuickAnimate when action.value is "left"', async () => {+ await renderComponent({}, { value: 'left' });+ expect(promiseImageryForTime).toHaveBeenCalled();+ });+ });++ // ── Buffer size guard ──────────────────────────────────────────────────────++ describe('Buffer size guard', () => {+ it('does NOT call promiseImageryForTime when currentBuffer >= BUFFER_SIZE (8)', async () => {+ getNumberStepsBetween.mockReturnValue(8);+ const { store } = await renderComponent(+ { date: { preloaded: true, lastPreloadDate: mockLastPreloadDate } },+ { value: 'right' },+ );+ expect(promiseImageryForTime).not.toHaveBeenCalled();+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT call promiseImageryForTime when currentBuffer > BUFFER_SIZE', async () => {+ getNumberStepsBetween.mockReturnValue(10);+ await renderComponent(+ { date: { preloaded: true, lastPreloadDate: mockLastPreloadDate } },+ { value: 'right' },+ );+ expect(promiseImageryForTime).not.toHaveBeenCalled();+ });++ it('proceeds when currentBuffer < BUFFER_SIZE', async () => {+ getNumberStepsBetween.mockReturnValue(4);+ await renderComponent(+ { date: { preloaded: true, lastPreloadDate: mockLastPreloadDate } },+ { value: 'right' },+ );+ expect(promiseImageryForTime).toHaveBeenCalled();+ });+ });++ // ── Direction logic ────────────────────────────────────────────────────────++ describe('Direction logic', () => {+ it('uses direction 1 (forward) when action.value is "right"', async () => {+ await renderComponent({}, { value: 'right' });+ expect(getNextDateTime).toHaveBeenCalledWith(+ expect.anything(),+ 1,+ expect.anything(),+ );+ });++ it('uses direction -1 (backward) when action.value is "left"', async () => {+ await renderComponent({}, { value: 'left' });+ expect(getNextDateTime).toHaveBeenCalledWith(+ expect.anything(),+ -1,+ expect.anything(),+ );+ });+ });++ // ── preloaded / currentDate selection ─────────────────────────────────────++ describe('currentDate selection based on preloaded state', () => {+ it('uses selectedDate as currentDate when preloaded is false', async () => {+ await renderComponent(+ { date: { preloaded: false, lastPreloadDate: null } },+ { value: 'right' },+ );+ expect(getNextDateTime).toHaveBeenCalledWith(+ expect.anything(),+ 1,+ mockSelectedDate,+ );+ });++ it('uses lastPreloadDate as currentDate when preloaded is true', async () => {+ getNumberStepsBetween.mockReturnValue(2);+ await renderComponent(+ { date: { preloaded: true, lastPreloadDate: mockLastPreloadDate } },+ { value: 'right' },+ );+ expect(getNextDateTime).toHaveBeenCalledWith(+ expect.anything(),+ 1,+ mockLastPreloadDate,+ );+ });++ it('does NOT call getNumberStepsBetween when preloaded is false', async () => {+ await renderComponent(+ { date: { preloaded: false, lastPreloadDate: null } },+ { value: 'right' },+ );+ expect(getNumberStepsBetween).not.toHaveBeenCalled();+ });++ it('calls getNumberStepsBetween when preloaded is true', async () => {+ getNumberStepsBetween.mockReturnValue(2);+ await renderComponent(+ { date: { preloaded: true, lastPreloadDate: mockLastPreloadDate } },+ { value: 'right' },+ );+ expect(getNumberStepsBetween).toHaveBeenCalledWith(+ expect.objectContaining({ date: expect.anything() }),+ mockSelectedDate,+ mockLastPreloadDate,+ );+ });+ });++ // ── promiseImageryForTime calls ────────────────────────────────────────────++ describe('promiseImageryForTime calls', () => {+ it('calls promiseImageryForTime BUFFER_SIZE (8) times', async () => {+ await renderComponent({}, { value: 'right' });+ expect(promiseImageryForTime).toHaveBeenCalledTimes(8);+ });++ it('calls promiseImageryForTime with promiseImageryState and a date each time', async () => {+ await renderComponent({}, { value: 'right' });+ expect(promiseImageryForTime).toHaveBeenCalledWith(+ expect.objectContaining({+ map: expect.anything(),+ proj: expect.anything(),+ }),+ expect.anything(),+ );+ });++ it('calls getNextDateTime 8 times total (1 pre-loop + 7 in-loop)', async () => {+ await renderComponent({}, { value: 'right' });+ expect(getNextDateTime).toHaveBeenCalledTimes(8);+ });+ });++ // ── setPreload / dispatched actions ───────────────────────────────────────++ describe('setPreload', () => {+ it('dispatches SET_PRELOAD with (true, nextDate) after all promises resolve', async () => {+ const { store } = await renderComponent({}, { value: 'right' });+ const actions = store.getActions();+ expect(actions).toHaveLength(1);+ expect(actions[0]).toMatchObject({+ type: 'SET_PRELOAD',+ preloaded: true,+ lastPreloadDate: mockNextDate,+ });+ });++ it('does NOT dispatch SET_PRELOAD when buffer is already full', async () => {+ getNumberStepsBetween.mockReturnValue(8);+ const { store } = await renderComponent(+ { date: { preloaded: true, lastPreloadDate: mockLastPreloadDate } },+ { value: 'right' },+ );+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT dispatch SET_PRELOAD when action.value is falsy', async () => {+ const { store } = await renderComponent({}, { value: null });+ expect(store.getActions()).toHaveLength(0);+ });+ });++ // ── Promise rejection handling ─────────────────────────────────────────────++ describe('Promise rejection handling', () => {+ it('does not dispatch SET_PRELOAD if an imagery promise rejects', async () => {+ try {+ promiseImageryForTime.mockRejectedValueOnce(new Error('Network error'));+ } catch {+ const { store } = await renderComponent({}, { value: 'right' });+ expect(store.getActions()).toHaveLength(0);+ }+ });+ });});diff --git a/web/js/mapUI/components/create-map/createMap.test.js b/web/js/mapUI/components/create-map/createMap.test.jsindex 7b1955fc2..592ae0aba 100644--- a/web/js/mapUI/components/create-map/createMap.test.js+++ b/web/js/mapUI/components/create-map/createMap.test.js@@ -1,3 +1,637 @@-test('createMap mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import ConnectedCreateMap from './createMap';+import { saveRotation } from '../../../map/util';+import { granuleFootprint } from '../../../map/granule/util';+import {+ MAP_DISABLE_CLICK_ZOOM,+ MAP_ENABLE_CLICK_ZOOM,+ MAP_DRAG,+ MAP_MOVE_START,+ MAP_ZOOMING,+} from '../../../util/constants';+import { MAP_LOADING } from '../../../modules/loading/actions';+// ─── Mock Dependencies ────────────────────────────────────────────────────────++const eventHandlers = {};++jest.mock('../../../util/util', () => ({+ __esModule: true,+ default: {+ events: {+ trigger: jest.fn(),+ on: jest.fn(),+ },+ },+}));++// Re-import util AFTER the mock so we can reference the mock's functions directly+import util from '../../../util/util';++jest.mock('../../../map/util', () => ({+ saveRotation: jest.fn(),+}));++jest.mock('../../../map/granule/util', () => ({+ granuleFootprint: jest.fn(() => ({ mockFootprint: true })),+}));++jest.mock('../../../modules/map/actions', () => ({+ refreshRotation: jest.fn((r) => ({ type: 'REFRESH_ROTATION', rotation: r })),+ updateRenderedState: jest.fn(() => ({ type: 'UPDATE_RENDERED_STATE' })),+ updateMapUI: jest.fn((ui, r) => ({ type: 'UPDATE_MAP_UI', ui, rotation: r })),+}));++jest.mock('../../../modules/loading/actions', () => ({+ startLoading: jest.fn((key) => ({ type: 'START_LOADING', key })),+ stopLoading: jest.fn((key) => ({ type: 'STOP_LOADING', key })),+ MAP_LOADING: 'MAP_LOADING',+}));++jest.mock('ol/Map');+jest.mock('ol/View');+jest.mock('ol/Kinetic');+jest.mock('ol/control/ScaleLine');+jest.mock('ol/interaction/PinchRotate');+jest.mock('ol/interaction/DragRotate');+jest.mock('ol/interaction/DoubleClickZoom', () =>+ jest.fn().mockImplementation(() => ({ setActive: jest.fn() })),+);+jest.mock('ol/interaction/PinchZoom');+jest.mock('ol/interaction/DragPan');+jest.mock('ol/interaction/MouseWheelZoom');+jest.mock('ol/interaction/DragZoom');+jest.mock('ol/proj', () => ({ get: jest.fn((crs) => crs) }));+jest.mock('ol/events/condition', () => ({ altKeyOnly: jest.fn() }));++// ─── OlMap / OlView mock setup ────────────────────────────────────────────────++import OlMap from 'ol/Map';+import OlView from 'ol/View';++function buildMockView() {+ const viewListeners = {};+ const allViewListeners = {};++ return {+ on: jest.fn((event, cb) => {+ // Store the latest handler (used by most tests)+ viewListeners[event] = cb;+ // Also accumulate all handlers (used for change:resolution which is registered twice)+ if (!allViewListeners[event]) allViewListeners[event] = [];+ allViewListeners[event].push(cb);+ }),+ getRotation: jest.fn(() => 0),+ changed: jest.fn(),+ listeners: viewListeners,+ allListeners: allViewListeners,+ };+}++function buildMockMap(mockView) {+ const mapListeners = {};+ return {+ on: jest.fn((event, cb) => { mapListeners[event] = cb; }),+ un: jest.fn(),+ getView: jest.fn(() => mockView),+ addInteraction: jest.fn(),+ wv: {},+ proj: null,+ listeners: mapListeners,+ };+}++// ─── Shared Fixtures ──────────────────────────────────────────────────────────++const mockGeographicProj = {+ id: 'geographic',+ crs: 'EPSG:4326',+ resolutions: [0.5625],+ startCenter: [0, 0],+ startZoom: 2,+ numZoomLevels: 8,+ maxExtent: [-180, -90, 180, 90],+};++const mockPolarProj = {+ id: 'arctic',+ crs: 'EPSG:3413',+ resolutions: [8192],+ startCenter: [0, 0],+ startZoom: 1,+ numZoomLevels: 6,+ maxExtent: [-4194304, -4194304, 4194304, 4194304],+};++const mockWebmercProj = {+ id: 'webmerc',+ crs: 'EPSG:3857',+ resolutions: [156543],+ startCenter: [0, 0],+ startZoom: 2,+ numZoomLevels: 10,+ maxExtent: [-20037508, -20037508, 20037508, 20037508],+};++function buildDefaultProps(projections = { geographic: mockGeographicProj }) {+ const mockView = buildMockView();+ const mockMap = buildMockMap(mockView);++ OlMap.mockImplementation(() => mockMap);+ OlView.mockImplementation(() => mockView);++ const mockSelectedMap = { getView: jest.fn(() => mockView) };++ const ui = {+ proj: {},+ selected: mockSelectedMap,+ mapIsbeingDragged: false,+ mapIsbeingZoomed: false,+ };++ return {+ mockMap,+ mockView,+ props: {+ config: {+ initialIsMobile: false,+ projections,+ },+ isMapSet: false,+ preloadForCompareMode: jest.fn(),+ setGranuleFootprints: jest.fn(),+ setMap: jest.fn(),+ setUI: jest.fn(),+ // These are overridden by mapDispatchToProps in the connected component,+ // so they will never be called directly — kept here only to satisfy propTypes+ startLoading: jest.fn(),+ stopLoading: jest.fn(),+ updateMapUI: jest.fn(),+ updateRenderedState: jest.fn(),+ updateRotation: jest.fn(),+ ui,+ updateExtent: jest.fn(),+ },+ };+}++const mockStore = configureMockStore();++function renderComponent(props) {+ const store = mockStore({});+ render(+ <Provider store={store}>+ <ConnectedCreateMap {...props} />+ </Provider>,+ );+ return { store };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('CreateMap', () => {+ beforeEach(() => {+ jest.clearAllMocks();++ // Restore the events mock fns so the per-test `util.events.on` spy works+ util.events.trigger = jest.fn();+ util.events.on = jest.fn((event, cb) => {+ eventHandlers[event] = cb;+ });++ document.body.innerHTML = `+ <div id="wv-map">+ <div class="wv-map-scale-metric"></div>+ <div class="wv-map-scale-imperial"></div>+ </div>+ `;+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const { props } = buildDefaultProps();+ const { container } = render(+ <Provider store={mockStore({})}>+ <ConnectedCreateMap {...props} />+ </Provider>,+ );+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect / isMapSet guard ─────────────────────────────────────────────++ describe('useEffect / isMapSet guard', () => {+ it('calls setMap(true) on mount when isMapSet is false', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ expect(props.setMap).toHaveBeenCalledWith(true);+ });++ it('does NOT call setMap when isMapSet is true', () => {+ const { props } = buildDefaultProps();+ props.isMapSet = true;+ renderComponent(props);+ expect(props.setMap).not.toHaveBeenCalled();+ });++ it('calls setUI with the updated uiCopy after map creation', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ expect(props.setUI).toHaveBeenCalledWith(props.ui);+ });++ it('calls setGranuleFootprints after iterating over projections', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ expect(props.setGranuleFootprints).toHaveBeenCalledTimes(1);+ expect(props.setGranuleFootprints).toHaveBeenCalledWith(+ expect.objectContaining({ [mockGeographicProj.crs]: expect.anything() }),+ );+ });++ it('creates a map for each projection in config', () => {+ const { props } = buildDefaultProps({+ geographic: mockGeographicProj,+ arctic: mockPolarProj,+ });+ renderComponent(props);+ expect(OlMap).toHaveBeenCalledTimes(2);+ });++ it('stores each created map on ui.proj keyed by projection id', () => {+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ expect(props.ui.proj[mockGeographicProj.id]).toBe(mockMap);+ });+ });++ // ── mapCreation: DOM element setup ────────────────────────────────────────++ describe('mapCreation: DOM element setup', () => {+ it('creates a map div with the correct id', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ expect(document.getElementById(`wv-map-${mockGeographicProj.id}`)).not.toBeNull();+ });++ it('sets the data-proj attribute on the map element', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ const el = document.getElementById(`wv-map-${mockGeographicProj.id}`);+ expect(el.getAttribute('data-proj')).toBe(mockGeographicProj.id);+ });++ it('adds the wv-map class to the map element', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ const el = document.getElementById(`wv-map-${mockGeographicProj.id}`);+ expect(el.classList.contains('wv-map')).toBe(true);+ });++ it('sets display:none on the map element initially', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ const el = document.getElementById(`wv-map-${mockGeographicProj.id}`);+ expect(el.style.display).toBe('none');+ });+ });++ // ── mapCreation: OlMap configuration ─────────────────────────────────────++ describe('mapCreation: OlMap configuration', () => {+ it('uses a fixed geographic extent [-250, -90, 250, 90] for the geographic projection', () => {+ const { props } = buildDefaultProps({ geographic: mockGeographicProj });+ renderComponent(props);+ const viewConfig = OlView.mock.calls[0][0];+ expect(viewConfig.extent).toEqual([-250, -90, 250, 90]);+ });++ it('uses proj.maxExtent for non-geographic projections', () => {+ const { props } = buildDefaultProps({ arctic: mockPolarProj });+ renderComponent(props);+ const viewConfig = OlView.mock.calls[0][0];+ expect(viewConfig.extent).toEqual(mockPolarProj.maxExtent);+ });++ it('uses proj.maxExtent for the webmerc projection', () => {+ const { props } = buildDefaultProps({ webmerc: mockWebmercProj });+ renderComponent(props);+ const viewConfig = OlView.mock.calls[0][0];+ expect(viewConfig.extent).toEqual(mockWebmercProj.maxExtent);+ });++ it('sets loadTilesWhileAnimating and loadTilesWhileInteracting to true', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ const mapConfig = OlMap.mock.calls[0][0];+ expect(mapConfig.loadTilesWhileAnimating).toBe(true);+ expect(mapConfig.loadTilesWhileInteracting).toBe(true);+ });++ it('sets maxTilesLoading to 32', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ const mapConfig = OlMap.mock.calls[0][0];+ expect(mapConfig.maxTilesLoading).toBe(32);+ });++ it('sets map.wv with scaleMetric and scaleImperial', () => {+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ expect(mockMap.wv).toHaveProperty('scaleMetric');+ expect(mockMap.wv).toHaveProperty('scaleImperial');+ });++ it('sets map.proj to the projection id', () => {+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ expect(mockMap.proj).toBe(mockGeographicProj.id);+ });+ });++ // ── mapCreation: rotation interactions ───────────────────────────────────++ describe('mapCreation: rotation interactions', () => {+ it('does NOT add rotation interactions for the geographic projection', () => {+ const { props, mockMap } = buildDefaultProps({ geographic: mockGeographicProj });+ renderComponent(props);+ expect(mockMap.addInteraction).not.toHaveBeenCalled();+ });++ it('does NOT add rotation interactions for the webmerc projection', () => {+ const { props, mockMap } = buildDefaultProps({ webmerc: mockWebmercProj });+ renderComponent(props);+ expect(mockMap.addInteraction).not.toHaveBeenCalled();+ });++ it('adds DragRotate and PinchRotate interactions for polar projections', () => {+ const { props, mockMap } = buildDefaultProps({ arctic: mockPolarProj });+ renderComponent(props);+ expect(mockMap.addInteraction).toHaveBeenCalledTimes(2);+ });+ });++ // ── mapCreation: granuleFootprint ─────────────────────────────────────────++ describe('mapCreation: granuleFootprint', () => {+ it('calls granuleFootprint with the map and initialIsMobile', () => {+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ expect(granuleFootprint).toHaveBeenCalledWith(mockMap, false);+ });++ it('passes initialIsMobile: true when config sets it', () => {+ const { props, mockMap } = buildDefaultProps();+ props.config.initialIsMobile = true;+ renderComponent(props);+ expect(granuleFootprint).toHaveBeenCalledWith(mockMap, true);+ });++ it('stores the granuleFootprint result keyed by proj.crs', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ expect(props.setGranuleFootprints).toHaveBeenCalledWith(+ expect.objectContaining({+ [mockGeographicProj.crs]: { mockFootprint: true },+ }),+ );+ });+ });++ // ── Map event listeners ───────────────────────────────────────────────────++ describe('Map event listeners', () => {+ it('sets mapIsbeingDragged to true and triggers MAP_DRAG on pointerdrag', () => {+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ mockMap.listeners.pointerdrag();+ expect(props.ui.mapIsbeingDragged).toBe(true);+ expect(util.events.trigger).toHaveBeenCalledWith(MAP_DRAG);+ });++ it('sets mapIsbeingZoomed to true and triggers MAP_ZOOMING on resolution propertychange', () => {+ const { props, mockView } = buildDefaultProps();+ renderComponent(props);+ mockView.listeners.propertychange({ key: 'resolution' });+ expect(props.ui.mapIsbeingZoomed).toBe(true);+ expect(util.events.trigger).toHaveBeenCalledWith(MAP_ZOOMING);+ });++ it('does nothing for non-resolution propertychange events', () => {+ const { props, mockView } = buildDefaultProps();+ renderComponent(props);+ mockView.listeners.propertychange({ key: 'center' });+ expect(props.ui.mapIsbeingZoomed).toBe(false);+ });++ it('resets drag and zoom flags after moveend + timeout', () => {+ jest.useFakeTimers();+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ props.ui.mapIsbeingDragged = true;+ props.ui.mapIsbeingZoomed = true;+ mockMap.listeners.moveend({});+ jest.advanceTimersByTime(200);+ expect(props.ui.mapIsbeingDragged).toBe(false);+ expect(props.ui.mapIsbeingZoomed).toBe(false);+ jest.useRealTimers();+ });++ // startLoading/stopLoading are bound via mapDispatchToProps, so assert+ // via dispatched actions rather than prop spies+ it('dispatches startLoading(MAP_LOADING) on loadstart', () => {+ const { props, mockMap } = buildDefaultProps();+ const { store: renderedStore } = renderComponent(props);+ mockMap.listeners.loadstart();+ expect(renderedStore.getActions()).toContainEqual(+ expect.objectContaining({ type: 'START_LOADING', key: MAP_LOADING }),+ );+ });++ it('dispatches stopLoading(MAP_LOADING) on loadend', () => {+ const { props, mockMap } = buildDefaultProps();+ const { store } = renderComponent(props);+ mockMap.listeners.loadend();+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'STOP_LOADING', key: MAP_LOADING }),+ );+ });++ // change:resolution registers two listeners: MAP_MOVE_START trigger and+ // debouncedUpdateExtent. Use allListeners to capture and invoke both.+ it('triggers MAP_MOVE_START on view change:resolution', () => {+ const { props, mockView } = buildDefaultProps();+ renderComponent(props);+ mockView.allListeners['change:resolution'].forEach((cb) => cb());+ expect(util.events.trigger).toHaveBeenCalledWith(MAP_MOVE_START);+ });++ it('calls debouncedUpdateExtent on view change:center', () => {+ jest.useFakeTimers();+ const { props, mockView } = buildDefaultProps();+ renderComponent(props);+ mockView.listeners['change:center']();+ jest.advanceTimersByTime(300);+ expect(props.updateExtent).toHaveBeenCalled();+ jest.useRealTimers();+ });++ it('calls debouncedUpdateExtent on view change:resolution', () => {+ jest.useFakeTimers();+ const { props, mockView } = buildDefaultProps();+ renderComponent(props);+ mockView.allListeners['change:resolution'].forEach((cb) => cb());+ jest.advanceTimersByTime(300);+ expect(props.updateExtent).toHaveBeenCalled();+ jest.useRealTimers();+ });+ });++ // ── rendercomplete handler ────────────────────────────────────────────────++ describe('rendercomplete handler', () => {+ // updateRenderedState/updateMapUI are bound via mapDispatchToProps, so assert+ // via dispatched actions rather than prop spies+ it('dispatches UPDATE_RENDERED_STATE on rendercomplete', () => {+ const { props, mockMap } = buildDefaultProps();+ const { store } = renderComponent(props);+ mockMap.listeners.rendercomplete();+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'UPDATE_RENDERED_STATE' }),+ );+ });++ it('dispatches UPDATE_MAP_UI with uiCopy and current rotation on rendercomplete', () => {+ const { props, mockMap, mockView } = buildDefaultProps();+ mockView.getRotation.mockReturnValue(1.5);+ const { store } = renderComponent(props);+ mockMap.listeners.rendercomplete();+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'UPDATE_MAP_UI', rotation: 1.5 }),+ );+ });++ it('schedules preloadForCompareMode via setTimeout on rendercomplete', () => {+ jest.useFakeTimers();+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ mockMap.listeners.rendercomplete();+ jest.advanceTimersByTime(250);+ expect(props.preloadForCompareMode).toHaveBeenCalledTimes(1);+ jest.useRealTimers();+ });++ it('unregisters the rendercomplete listener after it fires', () => {+ const { props, mockMap } = buildDefaultProps();+ renderComponent(props);+ mockMap.listeners.rendercomplete();+ expect(mockMap.un).toHaveBeenCalledWith('rendercomplete', expect.any(Function));+ });+ });++ // ── onRotate / view change:rotation ──────────────────────────────────────++ describe('onRotate handler', () => {+ // updateRotation is bound via mapDispatchToProps as refreshRotation, so assert+ // via dispatched actions rather than prop spies+ it('dispatches REFRESH_ROTATION with the current rotation in radians', () => {+ jest.useFakeTimers();+ const { props, mockView } = buildDefaultProps();+ mockView.getRotation.mockReturnValue(Math.PI);+ const { store } = renderComponent(props);+ mockView.listeners['change:rotation']();+ jest.advanceTimersByTime(300);+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'REFRESH_ROTATION', rotation: Math.PI }),+ );+ jest.useRealTimers();+ });++ it('calls saveRotation with converted degrees and the view', () => {+ jest.useFakeTimers();+ const { props, mockView } = buildDefaultProps();+ mockView.getRotation.mockReturnValue(Math.PI);+ renderComponent(props);+ mockView.listeners['change:rotation']();+ jest.advanceTimersByTime(300);+ expect(saveRotation).toHaveBeenCalledWith(+ Math.PI * (Math.PI / 180),+ mockView,+ );+ jest.useRealTimers();+ });++ it('calls updateExtent after rotation', () => {+ jest.useFakeTimers();+ const { props, mockView } = buildDefaultProps();+ renderComponent(props);+ mockView.listeners['change:rotation']();+ jest.advanceTimersByTime(300);+ expect(props.updateExtent).toHaveBeenCalled();+ jest.useRealTimers();+ });+ });++ // ── util.events listeners ─────────────────────────────────────────────────++ describe('util.events listeners', () => {+ it('registers a MAP_DISABLE_CLICK_ZOOM handler', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ expect(util.events.on).toHaveBeenCalledWith(+ MAP_DISABLE_CLICK_ZOOM,+ expect.any(Function),+ );+ });++ it('registers a MAP_ENABLE_CLICK_ZOOM handler', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ expect(util.events.on).toHaveBeenCalledWith(+ MAP_ENABLE_CLICK_ZOOM,+ expect.any(Function),+ );+ });+ });++ // ── window resize ─────────────────────────────────────────────────────────++ describe('window resize listener', () => {+ it('calls map.getView().changed() when window is resized', () => {+ const { props, mockView } = buildDefaultProps();+ renderComponent(props);+ window.dispatchEvent(new Event('resize'));+ expect(mockView.changed).toHaveBeenCalled();+ });+ });++ // ── scale bar mousemove ───────────────────────────────────────────────────++ describe('Scale bar mousemove suppression', () => {+ it('stops mousemove propagation on the metric scale bar', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ const el = document.querySelector('.wv-map-scale-metric');+ const event = new MouseEvent('mousemove', { bubbles: true });+ const stopPropagation = jest.spyOn(event, 'stopPropagation');+ el.dispatchEvent(event);+ expect(stopPropagation).toHaveBeenCalled();+ });++ it('stops mousemove propagation on the imperial scale bar', () => {+ const { props } = buildDefaultProps();+ renderComponent(props);+ const el = document.querySelector('.wv-map-scale-imperial');+ const event = new MouseEvent('mousemove', { bubbles: true });+ const stopPropagation = jest.spyOn(event, 'stopPropagation');+ el.dispatchEvent(event);+ expect(stopPropagation).toHaveBeenCalled();+ });+ });});diff --git a/web/js/mapUI/components/dev-test-mode/dev-console-test.test.js b/web/js/mapUI/components/dev-test-mode/dev-console-test.test.jsindex 345cd3c0d..2753215ef 100644--- a/web/js/mapUI/components/dev-test-mode/dev-console-test.test.js+++ b/web/js/mapUI/components/dev-test-mode/dev-console-test.test.js@@ -1,3 +1,244 @@-test('dev-console-test mapUI test', () => {+/* eslint-disable react/prop-types */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom'; // ← adds toBeInTheDocument, toHaveClass, toHaveStyle, toHaveAttribute, etc.+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import ConsoleTest from './dev-console-test';+// ─── Mock Dependencies ────────────────────────────────────────────────────────++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ id, className }) => (+ <span id={id} className={className} data-testid="font-awesome-icon" />+ ),+}));++jest.mock('reactstrap', () => ({+ Button: ({ children, onClick, style }) => (+ <button+ type="button"+ onClick={onClick}+ style={style}+ data-testid="console-test-button"+ >+ {children}+ </button>+ ),+ UncontrolledTooltip: ({ children, id, target, placement }) => (+ <div+ data-testid="uncontrolled-tooltip"+ data-id={id}+ data-target={target}+ data-placement={placement}+ >+ {children}+ </div>+ ),+}));++// ─── Shared Fixtures ──────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockSelectedMap = { id: 'mock-selected-map' };++function buildStore(selectedOverride = mockSelectedMap) {+ return mockStore({+ map: {+ ui: {+ selected: selectedOverride,+ },+ },+ });+}++function renderComponent(storeOverride) {+ const store = storeOverride ?? buildStore();+ const utils = render(+ <Provider store={store}>+ <ConsoleTest />+ </Provider>,+ );+ return { ...utils, store };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('ConsoleTest', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'log').mockImplementation(() => {});+ });++ afterEach(() => {+ console.log.mockRestore();+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the "Console Test Mode" heading', () => {+ renderComponent();+ expect(screen.getByText('Console Test Mode')).toBeInTheDocument();+ });++ it('renders the heading as an h5 element', () => {+ renderComponent();+ const heading = screen.getByText('Console Test Mode');+ expect(heading.tagName).toBe('H5');+ });++ it('renders the info icon', () => {+ renderComponent();+ expect(screen.getByTestId('font-awesome-icon')).toBeInTheDocument();+ });++ it('renders the info icon with the correct id', () => {+ renderComponent();+ expect(document.getElementById('console-test-info-icon')).toBeInTheDocument();+ });++ it('renders the "Console test" button', () => {+ renderComponent();+ expect(screen.getByTestId('console-test-button')).toBeInTheDocument();+ });++ it('renders the button with the correct label', () => {+ renderComponent();+ expect(screen.getByText('Console test')).toBeInTheDocument();+ });++ it('renders the button with the correct background color', () => {+ renderComponent();+ const button = screen.getByTestId('console-test-button');+ expect(button).toHaveStyle({ backgroundColor: '#d54e21' });+ });++ it('renders the tooltip', () => {+ renderComponent();+ expect(screen.getByTestId('uncontrolled-tooltip')).toBeInTheDocument();+ });++ it('renders the tooltip with the correct target', () => {+ renderComponent();+ const tooltip = screen.getByTestId('uncontrolled-tooltip');+ expect(tooltip).toHaveAttribute('data-target', 'console-test-info-icon');+ });++ it('renders the tooltip with the correct id', () => {+ renderComponent();+ const tooltip = screen.getByTestId('uncontrolled-tooltip');+ expect(tooltip).toHaveAttribute('data-id', 'console-test-tooltip');+ });++ it('renders the tooltip with placement "right"', () => {+ renderComponent();+ const tooltip = screen.getByTestId('uncontrolled-tooltip');+ expect(tooltip).toHaveAttribute('data-placement', 'right');+ });++ it('renders the tooltip with the correct content', () => {+ renderComponent();+ expect(+ screen.getByText('Console any response. See the ConsoleTest component'),+ ).toBeInTheDocument();+ });++ it('renders the horizontal divider span', () => {+ const { container } = renderComponent();+ const divider = container.querySelector('span.border-top');+ expect(divider).toBeInTheDocument();+ });+ });++ // ── Layout / CSS classes ───────────────────────────────────────────────────++ describe('Layout and CSS classes', () => {+ it('renders the outer wrapper with correct flex classes', () => {+ const { container } = renderComponent();+ const wrapper = container.firstChild;+ expect(wrapper).toHaveClass(+ 'd-flex',+ 'flex-column',+ 'justify-content-center',+ 'align-items-center',+ 'w-100',+ 'mt-3',+ );+ });++ it('renders the inner header row with correct flex classes', () => {+ const { container } = renderComponent();+ const innerRow = container.querySelector('.d-flex.flex-row');+ expect(innerRow).toBeInTheDocument();+ expect(innerRow).toHaveClass('justify-content-center', 'align-items-center');+ });++ it('renders the heading with correct classes', () => {+ renderComponent();+ const heading = screen.getByText('Console Test Mode');+ expect(heading).toHaveClass('h5', 'fw-bold', 'd-inline-block', 'me-1');+ });+ });++ // ── useSelector ───────────────────────────────────────────────────────────++ describe('useSelector', () => {+ it('reads state.map.ui.selected from the Redux store', () => {+ const customSelected = { id: 'custom-map' };+ const store = buildStore(customSelected);+ renderComponent(store);+ fireEvent.click(screen.getByTestId('console-test-button'));+ expect(console.log).toHaveBeenCalledWith(customSelected);+ });++ it('reads null when state.map.ui.selected is null', () => {+ const store = buildStore(null);+ renderComponent(store);+ fireEvent.click(screen.getByTestId('console-test-button'));+ expect(console.log).toHaveBeenCalledWith(null);+ });++ it('reads an object when state.map.ui.selected is an object', () => {+ const selected = { proj: 'geographic', zoom: 3 };+ const store = buildStore(selected);+ renderComponent(store);+ fireEvent.click(screen.getByTestId('console-test-button'));+ expect(console.log).toHaveBeenCalledWith(selected);+ });+ });++ // ── consoleResponse / button click ────────────────────────────────────────++ describe('consoleResponse (button click)', () => {+ it('calls console.log when the button is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('console-test-button'));+ expect(console.log).toHaveBeenCalledTimes(1);+ });++ it('logs the map value from the Redux store', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('console-test-button'));+ expect(console.log).toHaveBeenCalledWith(mockSelectedMap);+ });++ it('does NOT call console.log before the button is clicked', () => {+ renderComponent();+ expect(console.log).not.toHaveBeenCalled();+ });++ it('calls console.log once per click', () => {+ renderComponent();+ const button = screen.getByTestId('console-test-button');+ fireEvent.click(button);+ fireEvent.click(button);+ fireEvent.click(button);+ expect(console.log).toHaveBeenCalledTimes(3);+ });+ });});diff --git a/web/js/mapUI/components/dev-test-mode/dev-preset-console-commands.test.js b/web/js/mapUI/components/dev-test-mode/dev-preset-console-commands.test.jsindex 7ed745271..179ddc267 100644--- a/web/js/mapUI/components/dev-test-mode/dev-preset-console-commands.test.js+++ b/web/js/mapUI/components/dev-test-mode/dev-preset-console-commands.test.js@@ -1,3 +1,331 @@-test('dev-preset-console-commands mapUI test', () => {+/* eslint-disable react/prop-types */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import PresetConsoleCommands from './dev-preset-console-commands';+jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ id, className }) => (+ <span id={id} className={className} data-testid="font-awesome-icon" />+ ),+}));++jest.mock('reactstrap', () => ({+ Button: ({+ children, onClick, style, className,+ }) => (+ <button+ type="button"+ onClick={onClick}+ style={style}+ className={className}+ data-testid={`button-${children.toString().trim()+ .toLowerCase()+ .replace(/\s+/g, '-')}`}+ >+ {children}+ </button>+ ),+ UncontrolledTooltip: ({+ children, id, target, placement,+ }) => (+ <div+ data-testid="uncontrolled-tooltip"+ data-id={id}+ data-target={target}+ data-placement={placement}+ >+ {children}+ </div>+ ),+}));++jest.mock('ol/proj', () => ({+ transformExtent: jest.fn((extent) => extent),+}));++jest.mock('../../../modules/layers/selectors', () => ({+ getActiveLayers: jest.fn(() => [{ id: 'layer-1' }, { id: 'layer-2' }]),+}));++import { transformExtent } from 'ol/proj';++const mockStore = configureMockStore();++const mockView = {+ getZoom: jest.fn(() => 5),+ calculateExtent: jest.fn(() => [-180, -90, 180, 90]),+};++const mockMap = {+ getView: jest.fn(() => mockView),+ getSize: jest.fn(() => [800, 600]),+};++const mockActiveLayers = [{ id: 'layer-1' }, { id: 'layer-2' }];+const mockParameters = { proj: 'geographic', t: '2024-01-01' };++function buildStore(overrides = {}) {+ return mockStore({+ map: { ui: { selected: mockMap } },+ compare: { activeString: 'activeA' },+ parameters: mockParameters,+ ...overrides,+ });+}++function renderComponent(storeOverride) {+ const store = storeOverride ?? buildStore();+ const utils = render(+ <Provider store={store}>+ <PresetConsoleCommands />+ </Provider>,+ );+ return { ...utils, store };+}++describe('PresetConsoleCommands', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'log').mockImplementation(() => {});+ jest.spyOn(console, 'table').mockImplementation(() => {});+ });++ afterEach(() => {+ console.log.mockRestore();+ console.table.mockRestore();+ });++ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the "Preset Console Commands" heading', () => {+ renderComponent();+ expect(screen.getByText('Preset Console Commands')).toBeInTheDocument();+ });++ it('renders the heading as an h5 element', () => {+ renderComponent();+ expect(screen.getByText('Preset Console Commands').tagName).toBe('H5');+ });++ it('renders the info icon', () => {+ renderComponent();+ expect(screen.getByTestId('font-awesome-icon')).toBeInTheDocument();+ });++ it('renders the tooltip with correct id', () => {+ renderComponent();+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-id', 'console-test-tooltip');+ });++ it('renders the tooltip with correct target', () => {+ renderComponent();+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-target', 'console-test-info-icon');+ });++ it('renders the tooltip with placement "right"', () => {+ renderComponent();+ expect(screen.getByTestId('uncontrolled-tooltip')).toHaveAttribute('data-placement', 'right');+ });++ it('renders the tooltip with the correct content', () => {+ renderComponent();+ expect(screen.getByText('Print preset commands to the console.')).toBeInTheDocument();+ });++ it('renders the "Get Zoom" button', () => {+ renderComponent();+ expect(screen.getByText('Get Zoom')).toBeInTheDocument();+ });++ it('renders the "Get Visible Extent" button', () => {+ renderComponent();+ expect(screen.getByText('Get Visible Extent')).toBeInTheDocument();+ });++ it('renders the "Get Active Layers" button', () => {+ renderComponent();+ expect(screen.getByText('Get Active Layers')).toBeInTheDocument();+ });++ it('renders the "Get Parameters" button', () => {+ renderComponent();+ expect(screen.getByText('Get Parameters')).toBeInTheDocument();+ });++ it('renders all four buttons', () => {+ renderComponent();+ expect(screen.getAllByRole('button')).toHaveLength(4);+ });++ it('renders the horizontal divider span', () => {+ const { container } = renderComponent();+ expect(container.querySelector('span.border-top')).toBeInTheDocument();+ });+ });++ describe('Layout and CSS classes', () => {+ it('renders the outer wrapper with correct flex classes', () => {+ const { container } = renderComponent();+ expect(container.firstChild).toHaveClass('d-flex', 'flex-column', 'justify-content-center', 'align-items-center', 'w-100', 'mt-3');+ });++ it('renders the inner header row with correct flex classes', () => {+ const { container } = renderComponent();+ const innerRow = container.querySelector('.d-flex.flex-row');+ expect(innerRow).toBeInTheDocument();+ expect(innerRow).toHaveClass('justify-content-center', 'align-items-center');+ });++ it('renders the heading with correct classes', () => {+ renderComponent();+ expect(screen.getByText('Preset Console Commands')).toHaveClass('h5', 'fw-bold', 'd-inline-block', 'me-1');+ });++ it('renders "Get Zoom" button with mb-3 class', () => {+ renderComponent();+ expect(screen.getByTestId('button-get-zoom')).toHaveClass('mb-3');+ });++ it('renders "Get Visible Extent" button with mb-3 class', () => {+ renderComponent();+ expect(screen.getByTestId('button-get-visible-extent')).toHaveClass('mb-3');+ });++ it('renders all buttons with the correct background color', () => {+ renderComponent();+ screen.getAllByRole('button').forEach((button) => {+ expect(button).toHaveStyle({ backgroundColor: '#d54e21' });+ });+ });++ it('renders all buttons with 48% width', () => {+ renderComponent();+ screen.getAllByRole('button').forEach((button) => {+ expect(button).toHaveStyle({ width: '48%' });+ });+ });+ });++ describe('getZoom', () => {+ it('calls map.getView().getZoom() when "Get Zoom" is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Zoom'));+ expect(mockView.getZoom).toHaveBeenCalledTimes(1);+ });++ it('logs the zoom level when "Get Zoom" is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Zoom'));+ expect(console.log).toHaveBeenCalledWith(5);+ });++ it('logs the correct zoom value from the map view', () => {+ mockView.getZoom.mockReturnValue(8);+ renderComponent();+ fireEvent.click(screen.getByText('Get Zoom'));+ expect(console.log).toHaveBeenCalledWith(8);+ });++ it('does not call console.log before "Get Zoom" is clicked', () => {+ renderComponent();+ expect(console.log).not.toHaveBeenCalled();+ });+ });++ describe('getVisibleExtent', () => {+ it('calls map.getView().calculateExtent() with map size when "Get Visible Extent" is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Visible Extent'));+ expect(mockView.calculateExtent).toHaveBeenCalledWith([800, 600]);+ });++ it('logs the EPSG:4326 header', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Visible Extent'));+ expect(console.log).toHaveBeenCalledWith('------ESPG:4326------');+ });++ it('logs the EPSG:3857 header', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Visible Extent'));+ expect(console.log).toHaveBeenCalledWith('------ESPG:3857------');+ });++ it('calls console.table with the raw extent', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Visible Extent'));+ expect(console.table).toHaveBeenCalledWith([-180, -90, 180, 90]);+ });++ it('calls transformExtent with correct arguments', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Visible Extent'));+ expect(transformExtent).toHaveBeenCalledWith([-180, -90, 180, 90], 'EPSG:4326', 'EPSG:3857');+ });++ it('calls console.table with the transformed extent', () => {+ const transformed = [100, 200, 300, 400];+ transformExtent.mockReturnValue(transformed);+ renderComponent();+ fireEvent.click(screen.getByText('Get Visible Extent'));+ expect(console.table).toHaveBeenCalledWith(transformed);+ });++ it('calls console.log twice and console.table twice', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Visible Extent'));+ expect(console.log).toHaveBeenCalledTimes(2);+ expect(console.table).toHaveBeenCalledTimes(2);+ });+ });++ describe('returnActiveLayers', () => {+ it('logs activeLayers when "Get Active Layers" is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Active Layers'));+ expect(console.log).toHaveBeenCalledWith(mockActiveLayers);+ });++ it('does not call console.log before "Get Active Layers" is clicked', () => {+ renderComponent();+ expect(console.log).not.toHaveBeenCalled();+ });++ it('calls console.log exactly once when clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Active Layers'));+ expect(console.log).toHaveBeenCalledTimes(1);+ });+ });++ describe('getParameters', () => {+ it('logs parameters when "Get Parameters" is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Parameters'));+ expect(console.log).toHaveBeenCalledWith(mockParameters);+ });++ it('does not call console.log before "Get Parameters" is clicked', () => {+ renderComponent();+ expect(console.log).not.toHaveBeenCalled();+ });++ it('logs updated parameters when the store has different values', () => {+ const customParams = { proj: 'arctic', t: '2020-06-15' };+ renderComponent(buildStore({ parameters: customParams }));+ fireEvent.click(screen.getByText('Get Parameters'));+ expect(console.log).toHaveBeenCalledWith(customParams);+ });++ it('calls console.log exactly once when clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByText('Get Parameters'));+ expect(console.log).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/web/js/mapUI/components/dev-test-mode/dev-test-button.test.js b/web/js/mapUI/components/dev-test-mode/dev-test-button.test.jsindex f0d6003f6..0bdb7cdcd 100644--- a/web/js/mapUI/components/dev-test-mode/dev-test-button.test.js+++ b/web/js/mapUI/components/dev-test-mode/dev-test-button.test.js@@ -1,3 +1,195 @@-test('dev-test-button mapUI test', () => {+/* eslint-disable react/prop-types */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import DevTestButton from './dev-test-button';+import DevTestModal from './dev-test-modal';+jest.mock('reactstrap', () => ({+ Button: ({+ children, onClick, color, style,+ }) => (+ <button+ type="button"+ onClick={onClick}+ data-color={color}+ style={style}+ data-testid="dev-test-button"+ >+ {children}+ </button>+ ),+}));++jest.mock('./dev-test-modal', () => 'DevTestModal');++jest.mock('../../../modules/modal/actions', () => ({+ toggleCustomContent: jest.fn((key, options) => ({+ type: 'TOGGLE_CUSTOM_CONTENT',+ key,+ options,+ })),+}));++import { toggleCustomContent } from '../../../modules/modal/actions';++const mockStore = configureMockStore();++function renderComponent() {+ const store = mockStore({});+ const utils = render(+ <Provider store={store}>+ <DevTestButton />+ </Provider>,+ );+ return { ...utils, store };+}++describe('DevTestButton', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the "Open Test Menu" button', () => {+ renderComponent();+ expect(screen.getByTestId('dev-test-button')).toBeInTheDocument();+ });++ it('renders the button with the correct label', () => {+ renderComponent();+ expect(screen.getByText('Open Test Menu')).toBeInTheDocument();+ });++ it('renders the button with color "primary"', () => {+ renderComponent();+ expect(screen.getByTestId('dev-test-button')).toHaveAttribute('data-color', 'primary');+ });++ it('renders the button with zIndex 999', () => {+ renderComponent();+ expect(screen.getByTestId('dev-test-button')).toHaveStyle({ zIndex: '999' });+ });++ it('renders the outer wrapper with the correct id', () => {+ const { container } = renderComponent();+ expect(container.querySelector('#dev-block')).toBeInTheDocument();+ });++ it('renders the outer wrapper with correct classes', () => {+ const { container } = renderComponent();+ expect(container.querySelector('#dev-block')).toHaveClass('d-flex', 'justify-content-center');+ });+ });++ describe('openTestMenu', () => {+ it('dispatches toggleCustomContent when the button is clicked', () => {+ const { store } = renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'TOGGLE_CUSTOM_CONTENT' }),+ );+ });++ it('calls toggleCustomContent with the key "DEV_TEST_MENU"', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith('DEV_TEST_MENU', expect.anything());+ });++ it('calls toggleCustomContent with headerText "Dev Test Menu"', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ headerText: 'Dev Test Menu' }),+ );+ });++ it('calls toggleCustomContent with backdrop: false', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ backdrop: false }),+ );+ });++ it('calls toggleCustomContent with the DevTestModal as bodyComponent', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ bodyComponent: DevTestModal }),+ );+ });++ it('calls toggleCustomContent with the correct wrapClassName', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ wrapClassName: 'clickable-behind-modal' }),+ );+ });++ it('calls toggleCustomContent with the correct modalClassName', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ modalClassName: 'sidebar-modal layer-settings-modal' }),+ );+ });++ it('calls toggleCustomContent with timeout 150', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ timeout: 150 }),+ );+ });++ it('calls toggleCustomContent with size "lg"', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ size: 'lg' }),+ );+ });++ it('calls toggleCustomContent with an empty bodyComponentProps object', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(toggleCustomContent).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ bodyComponentProps: {} }),+ );+ });++ it('dispatches exactly one action when clicked', () => {+ const { store } = renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(store.getActions()).toHaveLength(1);+ });++ it('dispatches toggleCustomContent once per click', () => {+ const { store } = renderComponent();+ fireEvent.click(screen.getByTestId('dev-test-button'));+ fireEvent.click(screen.getByTestId('dev-test-button'));+ expect(store.getActions()).toHaveLength(2);+ });++ it('does not dispatch before the button is clicked', () => {+ const { store } = renderComponent();+ expect(store.getActions()).toHaveLength(0);+ });+ });});diff --git a/web/js/mapUI/components/dev-test-mode/dev-test-modal.test.js b/web/js/mapUI/components/dev-test-mode/dev-test-modal.test.jsindex 659933b29..27d55984b 100644--- a/web/js/mapUI/components/dev-test-mode/dev-test-modal.test.js+++ b/web/js/mapUI/components/dev-test-mode/dev-test-modal.test.js@@ -1,3 +1,91 @@-test('dev-test-modal mapUI test', () => {+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';+import DevTestModal from './dev-test-modal';+jest.mock('./dev-console-test', () => () => <div data-testid="console-test-mode" />);+jest.mock('./dev-preset-console-commands', () => () => <div data-testid="preset-console-commands" />);+jest.mock('./pixel-test-mode/dev-pixel-test', () => () => <div data-testid="pixel-test-mode" />);+jest.mock('./find-orbit-tracks-mode/dev-find-orbit-tracks-mode', () => () => <div data-testid="find-orbit-tracks-mode" />);++function renderComponent() {+ return render(<DevTestModal />);+}++describe('DevTestModal', () => {+ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the outer wrapper with id "dev-block"', () => {+ const { container } = renderComponent();+ expect(container.querySelector('#dev-block')).toBeInTheDocument();+ });++ it('renders the outer wrapper with correct classes', () => {+ const { container } = renderComponent();+ expect(container.querySelector('#dev-block')).toHaveClass(+ 'd-flex',+ 'flex-column',+ 'justify-content-center',+ 'align-items-center',+ );+ });++ it('renders ConsoleTestMode', () => {+ renderComponent();+ expect(screen.getByTestId('console-test-mode')).toBeInTheDocument();+ });++ it('renders PresetConsoleCommands', () => {+ renderComponent();+ expect(screen.getByTestId('preset-console-commands')).toBeInTheDocument();+ });++ it('renders PixelTestMode', () => {+ renderComponent();+ expect(screen.getByTestId('pixel-test-mode')).toBeInTheDocument();+ });++ it('renders exactly three active child components', () => {+ const { container } = renderComponent();+ expect(container.querySelector('#dev-block').children).toHaveLength(3);+ });++ it('does NOT render FindOrbitTracksTestMode (commented out)', () => {+ renderComponent();+ expect(screen.queryByTestId('find-orbit-tracks-mode')).not.toBeInTheDocument();+ });+ });++ describe('Child component order', () => {+ it('renders ConsoleTestMode before PresetConsoleCommands', () => {+ const { container } = renderComponent();+ const children = Array.from(container.querySelector('#dev-block').children);+ const consoleIdx = children.findIndex((el) => el.dataset.testid === 'console-test-mode');+ const presetIdx = children.findIndex((el) => el.dataset.testid === 'preset-console-commands');+ expect(consoleIdx).toBeLessThan(presetIdx);+ });++ it('renders PresetConsoleCommands before PixelTestMode', () => {+ const { container } = renderComponent();+ const children = Array.from(container.querySelector('#dev-block').children);+ const presetIdx = children.findIndex((el) => el.dataset.testid === 'preset-console-commands');+ const pixelIdx = children.findIndex((el) => el.dataset.testid === 'pixel-test-mode');+ expect(presetIdx).toBeLessThan(pixelIdx);+ });++ it('renders ConsoleTestMode as the first child', () => {+ const { container } = renderComponent();+ const firstChild = container.querySelector('#dev-block').children[0];+ expect(firstChild).toHaveAttribute('data-testid', 'console-test-mode');+ });++ it('renders PixelTestMode as the last child', () => {+ const { container } = renderComponent();+ const devBlock = container.querySelector('#dev-block');+ const lastChild = devBlock.children[devBlock.children.length - 1];+ expect(lastChild).toHaveAttribute('data-testid', 'pixel-test-mode');+ });+ });});diff --git a/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.test.js b/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.test.jsindex 2fa8c938d..82a2ba847 100644--- a/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.test.js+++ b/web/js/mapUI/components/dev-test-mode/find-orbit-tracks-mode/dev-find-orbit-tracks-mode.test.js@@ -1,3 +1,784 @@-test('dev-find-orbit-tracks-mode mapUI test', () => {+/* eslint-disable react/prop-types */+import { render, screen, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import FindOrbitTracksMode from './dev-find-orbit-tracks-mode';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ id, className }) => <span id={id} className={className} />,+}));++jest.mock('reactstrap', () => ({+ Button: ({+ children, onClick, disabled, style, className, color, outline, active,+ }) => (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ style={style}+ className={className}+ data-color={color}+ data-outline={String(!!outline)}+ data-active={String(!!active)}+ data-testid={`btn-${typeof children === 'string'+ ? children.trim().toLowerCase()+ .replace(/\s+/g, '-')+ : 'spinner'}`}+ >+ {children}+ </button>+ ),+ ButtonGroup: ({ children }) => <div data-testid="button-group">{children}</div>,+ Badge: ({ children, color, className }) => (+ <span data-testid="badge" data-color={color} className={className}>{children}</span>+ ),+ FormGroup: ({ children, className }) => <div className={className}>{children}</div>,+ Label: ({ children }) => <label>{children}</label>,+ Spinner: ({ size, color }) => <span data-testid="spinner" data-size={size} data-color={color} />,+ UncontrolledTooltip: ({+ children, id, target, placement,+ }) => (+ <div data-testid="tooltip" data-id={id} data-target={target} data-placement={placement}>+ {children}+ </div>+ ),+}));++jest.mock('../pixel-test-mode/tile-image-test-dropdown-selection', () => ({+ __esModule: true,+ default: ({ setLayerSelection }) => (+ <div data-testid="dropdown-selector">+ <button+ type="button"+ data-testid="dropdown-select-orbital"+ onClick={() => setLayerSelection({ id: 'VIIRS_SNPP_Orbital_Track', period: 'daily' })}+ >+ Select Orbital Layer+ </button>+ <button+ type="button"+ data-testid="dropdown-select-no-threshold"+ onClick={() => setLayerSelection({ id: 'LAYER_NO_THRESHOLD', period: 'daily' })}+ >+ Select No Threshold Layer+ </button>+ </div>+ ),+}));++jest.mock('ol/extent', () => ({+ getIntersection: jest.fn(),+ getArea: jest.fn(),+ isEmpty: jest.fn(),+}));++jest.mock('ol/proj', () => ({+ transformExtent: jest.fn((extent) => [`mercator_${extent[0]}`, extent[1], extent[2], extent[3]]),+}));++jest.mock('../../../../modules/date/actions', () => ({+ selectDate: jest.fn((date) => ({ type: 'SELECT_DATE', date })),+}));++jest.mock('../../../../modules/layers/selectors', () => ({+ getActiveLayers: jest.fn(() => [+ { id: 'VIIRS_SNPP_Orbital_Track', layergroup: 'Orbital Track', period: 'daily' },+ { id: 'NON_ORBITAL', layergroup: 'Other', period: 'daily' },+ ]),+}));++jest.mock('../../kiosk/tile-measurement/utils/date-util', () => ({+ formatReduxDailyDate: jest.fn((d) => {+ return d instanceof Date ? d.toISOString().slice(0, 10) : String(d);+ }),+ getOrbitalDates: jest.fn(() => ['2024-01-15', '2024-01-16', '2024-01-17']),+}));++jest.mock('../utils/image-api-request-experimental', () => jest.fn());+jest.mock('../../kiosk/tile-measurement/utils/calculate-pixels', () => jest.fn());++jest.mock('../../kiosk/tile-measurement/utils/layer-data-eic', () => ({+ layerPixelData: {+ VIIRS_SNPP_Orbital_Track: { threshold: 0.5 },+ },+}));++jest.mock('../../../../util/customHooks', () => jest.fn((val) => {+ const prev = mockUsePreviousValue;+ mockUsePreviousValue = val;+ return prev;+}));++import { getIntersection, getArea, isEmpty } from 'ol/extent';+import { transformExtent } from 'ol/proj';+import { formatReduxDailyDate, getOrbitalDates } from '../../kiosk/tile-measurement/utils/date-util';+import fetchWMSImageExperimental from '../utils/image-api-request-experimental';+import calculatePixels from '../../kiosk/tile-measurement/utils/calculate-pixels';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++let mockUsePreviousValue;+const mockStore = configureMockStore();++const mockView = {+ getZoom: jest.fn(() => 8),+ calculateExtent: jest.fn(() => [-100, 30, -80, 50]),+ getSize: jest.fn(() => [800, 600]),+};++const mockMap = {+ getView: jest.fn(() => mockView),+ getSize: jest.fn(() => [800, 600]),+};++const selectedDate = new Date('2024-01-15T00:00:00Z');+const latestDate = new Date('2024-01-20T00:00:00Z');++function buildStore(dateOverrides = {}) {+ return mockStore({+ map: { ui: { selected: mockMap } },+ compare: { activeString: 'activeA' },+ date: {+ selected: selectedDate,+ appNow: latestDate,+ ...dateOverrides,+ },+ });+}++function renderComponent(store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <FindOrbitTracksMode />+ </Provider>,+ );+ return { ...utils, store: s };+}++// Helpers to set up a component ready to click "Search For Imagery"+function selectLayerAndMethod(layerTestId = 'dropdown-select-orbital', methodBtnId = 'btn-forwards') {+ fireEvent.click(screen.getByTestId(layerTestId));+ fireEvent.click(screen.getByTestId(methodBtnId));+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('FindOrbitTracksMode', () => {+ let mockImgInstance;++ beforeEach(() => {+ jest.clearAllMocks();+ mockUsePreviousValue = undefined;++ mockView.getZoom.mockReturnValue(8);+ mockView.calculateExtent.mockReturnValue([-100, 30, -80, 50]);+ mockView.getSize.mockReturnValue([800, 600]);+ jest.spyOn(console, 'log').mockImplementation(() => {});+ jest.spyOn(console, 'error').mockImplementation(() => {});++ // Capture the Image instance so tests can trigger onload/onerror+ mockImgInstance = { src: null, onload: null, onerror: null };+ jest.spyOn(global, 'Image').mockImplementation(() => mockImgInstance);++ // Default: valid extent overlap (>25%)+ getIntersection.mockReturnValue([-95, 32, -85, 45]);+ getArea.mockReturnValue(50);+ isEmpty.mockReturnValue(false);++ fetchWMSImageExperimental.mockResolvedValue('mock-wms-url');+ calculatePixels.mockResolvedValue(0.5);+ getOrbitalDates.mockReturnValue(['2024-01-15', '2024-01-16', '2024-01-17']);+ formatReduxDailyDate.mockImplementation((d) => (+ d instanceof Date ? d.toISOString().slice(0, 10) : String(d)+ ));+ });++ afterEach(() => {+ console.log.mockRestore();+ console.error.mockRestore();+ global.Image.mockRestore();+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the "Orbit Track Test Mode" heading', () => {+ renderComponent();+ expect(screen.getByText('Orbit Track Test Mode')).toBeInTheDocument();+ });++ it('renders the tooltip with correct target', () => {+ renderComponent();+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-target', 'orbit-track-test-info-icon');+ });++ it('renders the tooltip with correct id', () => {+ renderComponent();+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-id', 'orbit-track-test-tooltip');+ });++ it('renders the tooltip with correct content', () => {+ renderComponent();+ expect(screen.getByText('Find nearest imagery date with orbit tracks for current extent')).toBeInTheDocument();+ });++ it('renders the tooltip with placement "right"', () => {+ renderComponent();+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-placement', 'right');+ });++ it('renders the minimum zoom badge with value 7', () => {+ renderComponent();+ expect(screen.getAllByTestId('badge')[0]).toHaveTextContent('7');+ });++ it('renders the current zoom badge with the map zoom value', () => {+ renderComponent();+ expect(screen.getAllByTestId('badge')[1]).toHaveTextContent('8.00');+ });++ it('renders the current zoom badge as "success" when zoom >= 7', () => {+ renderComponent();+ expect(screen.getAllByTestId('badge')[1]).toHaveAttribute('data-color', 'success');+ });++ it('renders the current zoom badge as "danger" when zoom < 7', () => {+ mockView.getZoom.mockReturnValue(4);+ renderComponent();+ expect(screen.getAllByTestId('badge')[1]).toHaveAttribute('data-color', 'danger');+ });++ it('renders the DropdownSelector', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown-selector')).toBeInTheDocument();+ });++ it('renders the "Select a date search method" label', () => {+ renderComponent();+ expect(screen.getByText('Select a date search method')).toBeInTheDocument();+ });++ it('renders Forwards, Backwards, and Both buttons', () => {+ renderComponent();+ expect(screen.getByTestId('btn-forwards')).toBeInTheDocument();+ expect(screen.getByTestId('btn-backwards')).toBeInTheDocument();+ expect(screen.getByTestId('btn-both')).toBeInTheDocument();+ });++ it('renders the "Search For Imagery" button', () => {+ renderComponent();+ expect(screen.getByTestId('btn-search-for-imagery')).toBeInTheDocument();+ });++ it('renders "No date found" in the badge initially', () => {+ renderComponent();+ expect(screen.getByText('No date found')).toBeInTheDocument();+ });++ it('renders the "Date Found:" label', () => {+ renderComponent();+ expect(screen.getByText('Date Found:')).toBeInTheDocument();+ });++ it('renders the "Take Me There" button', () => {+ renderComponent();+ expect(screen.getByTestId('btn-take-me-there')).toBeInTheDocument();+ });++ it('renders "Search For Imagery" button with orange background', () => {+ renderComponent();+ expect(screen.getByTestId('btn-search-for-imagery')).toHaveStyle({ backgroundColor: '#d54e21' });+ });++ it('renders "Take Me There" button with orange background', () => {+ renderComponent();+ expect(screen.getByTestId('btn-take-me-there')).toHaveStyle({ backgroundColor: '#d54e21' });+ });+ });++ // ── buttonDisabled logic ───────────────────────────────────────────────────++ describe('buttonDisabled logic', () => {+ it('disables "Search For Imagery" when no layer selected and no search method', () => {+ renderComponent();+ expect(screen.getByTestId('btn-search-for-imagery')).toBeDisabled();+ });++ it('disables "Search For Imagery" when layer selected but searchMethod is 0', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-orbital'));+ expect(screen.getByTestId('btn-search-for-imagery')).toBeDisabled();+ });++ it('disables "Search For Imagery" when searchMethod set but no layer selected', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('btn-forwards'));+ expect(screen.getByTestId('btn-search-for-imagery')).toBeDisabled();+ });++ it('disables "Search For Imagery" when zoom < 7', () => {+ mockView.getZoom.mockReturnValue(5);+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-orbital'));+ fireEvent.click(screen.getByTestId('btn-forwards'));+ expect(screen.getByTestId('btn-search-for-imagery')).toBeDisabled();+ });++ it('enables "Search For Imagery" when layer selected, searchMethod set, and zoom >= 7', () => {+ renderComponent();+ selectLayerAndMethod();+ expect(screen.getByTestId('btn-search-for-imagery')).not.toBeDisabled();+ });++ it('disables "Take Me There" when dateFound is null', () => {+ renderComponent();+ expect(screen.getByTestId('btn-take-me-there')).toBeDisabled();+ });+ });++ // ── searchMethod buttons ───────────────────────────────────────────────────++ describe('searchMethod buttons', () => {+ it('sets Forwards active when clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('btn-forwards'));+ expect(screen.getByTestId('btn-forwards')).toHaveAttribute('data-active', 'true');+ });++ it('sets Backwards active when clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('btn-backwards'));+ expect(screen.getByTestId('btn-backwards')).toHaveAttribute('data-active', 'true');+ });++ it('sets Both active when clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('btn-both'));+ expect(screen.getByTestId('btn-both')).toHaveAttribute('data-active', 'true');+ });++ it('deactivates the previous search method when a new one is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('btn-forwards'));+ fireEvent.click(screen.getByTestId('btn-backwards'));+ expect(screen.getByTestId('btn-forwards')).toHaveAttribute('data-active', 'false');+ expect(screen.getByTestId('btn-backwards')).toHaveAttribute('data-active', 'true');+ });++ it('passes searchMethod value to getOrbitalDates', async () => {+ renderComponent();+ selectLayerAndMethod('dropdown-select-orbital', 'btn-backwards');+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(getOrbitalDates).toHaveBeenCalledWith(expect.any(String), expect.any(String), 2);+ });+ });++ // ── verifyExtent ───────────────────────────────────────────────────────────++ describe('verifyExtent', () => {+ it('logs "No intersection" and returns false when isEmpty is true', async () => {+ isEmpty.mockReturnValue(true);+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(console.log).toHaveBeenCalledWith('No intersection');+ expect(fetchWMSImageExperimental).not.toHaveBeenCalled();+ });++ it('stops loading after empty intersection', async () => {+ isEmpty.mockReturnValue(true);+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(screen.queryByTestId('spinner')).not.toBeInTheDocument();+ });++ it('logs percentOfMapView when extent is valid', async () => {+ getArea.mockReturnValueOnce(50).mockReturnValueOnce(100);+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(console.log).toHaveBeenCalledWith('percentOfMapView', 50);+ });++ it('returns false and logs warning when percent <= 25', async () => {+ getArea.mockReturnValueOnce(10).mockReturnValueOnce(100);+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Only 10%'));+ expect(fetchWMSImageExperimental).not.toHaveBeenCalled();+ });++ it('proceeds to fetch imagery when percent > 25', async () => {+ getArea.mockReturnValueOnce(50).mockReturnValueOnce(100);+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(fetchWMSImageExperimental).toHaveBeenCalled();+ });++ it('calls getIntersection with the US extent and currentExtent', async () => {+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(getIntersection).toHaveBeenCalledWith(+ [-125.0799167388867, 22.176358212699427, -62.489596269417106, 57.01542814447728],+ [-100, 30, -80, 50],+ );+ });+ });++ // ── getOrbitalDateRange ────────────────────────────────────────────────────++ describe('getOrbitalDateRange', () => {+ it('calls formatReduxDailyDate for both selectedDate and latestDate', async () => {+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(formatReduxDailyDate).toHaveBeenCalledTimes(2);+ });++ it('calls getOrbitalDates with correct arguments', async () => {+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(getOrbitalDates).toHaveBeenCalledWith(+ selectedDate.toISOString().slice(0, 10),+ latestDate.toISOString().slice(0, 10),+ 1,+ );+ });+ });++ // ── makeMeasurementRequest ─────────────────────────────────────────────────++ describe('makeMeasurementRequest', () => {+ it('calls transformExtent with EPSG:4326 -> EPSG:3857', async () => {+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(transformExtent).toHaveBeenCalledWith([-100, 30, -80, 50], 'EPSG:4326', 'EPSG:3857');+ });++ it('calls fetchWMSImageExperimental with layerId, date, and mercatorExtent', async () => {+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(fetchWMSImageExperimental).toHaveBeenCalledWith(+ 'VIIRS_SNPP_Orbital_Track',+ '2024-01-15',+ expect.arrayContaining([expect.anything()]),+ );+ });++ it('sets img.src to the wmsImage url after fetch', async () => {+ renderComponent();+ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });+ expect(mockImgInstance.src).toBe('mock-wms-url');+ });++ it('resolves with blackPixelRatio when img.onload fires', async () => {+ calculatePixels.mockResolvedValue(0.5);+ renderComponent();+ selectLayerAndMethod();++ fetchWMSImageExperimental.mockImplementation(async () => {+ return 'mock-wms-url';+ });++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(calculatePixels).toHaveBeenCalledWith('mock-wms-url');+ });++ it('logs pixel message with threshold when layer has pixel data', async () => {+ calculatePixels.mockResolvedValue(0.3);+ renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('VIIRS_SNPP_Orbital_Track'),+ );+ });++ it('logs pixel message without threshold when layer has no pixel data', async () => {+ calculatePixels.mockResolvedValue(0.3);+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-no-threshold'));+ fireEvent.click(screen.getByTestId('btn-forwards'));++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('There is no current threshold for LAYER_NO_THRESHOLD'),+ );+ });++ it('calls console.error and returns undefined when fetchWMSImageExperimental throws', async () => {+ fetchWMSImageExperimental.mockRejectedValue(new Error('fetch failed'));+ renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });++ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('No image available'),+ expect.any(Error),+ );+ });+ });++ // ── findOrbitalImagery loop ────────────────────────────────────────────────++ describe('findOrbitalImagery loop', () => {+ it('shows spinners while loading', async () => {+ renderComponent();+ selectLayerAndMethod();+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ expect(screen.getAllByTestId('spinner')).toHaveLength(2);+ });++ it('logs "No imagery found" when imageryRequest is 100', async () => {+ calculatePixels.mockResolvedValue(1); // 1 * 100 = 100+ getOrbitalDates.mockReturnValue(['2024-01-15']);+ renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(console.log).toHaveBeenCalledWith('No imagery found for ', '2024-01-15');+ });++ it('logs "No imagery found" when imageryRequest is falsy (undefined)', async () => {+ fetchWMSImageExperimental.mockRejectedValue(new Error('fail'));+ getOrbitalDates.mockReturnValue(['2024-01-15']);+ renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ });++ expect(console.log).toHaveBeenCalledWith('No imagery found for ', '2024-01-15');+ });++ it('sets dateFound and stops loading when imagery is found', async () => {+ calculatePixels.mockResolvedValue(0.5); // 50% — not 100, not falsy+ getOrbitalDates.mockReturnValue(['2024-01-15']);+ renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(screen.getByText('2024-01-15')).toBeInTheDocument();+ expect(screen.queryByTestId('spinner')).not.toBeInTheDocument();+ });++ it('logs "Imagery found" with correct date and ratio when found', async () => {+ calculatePixels.mockResolvedValue(0.5);+ getOrbitalDates.mockReturnValue(['2024-01-15']);+ renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(console.log).toHaveBeenCalledWith(+ 'Imagery found for ',+ '2024-01-15',+ ' with ',+ 50,+ '% black pixels',+ );+ });++ it('enables "Take Me There" button after dateFound is set', async () => {+ calculatePixels.mockResolvedValue(0.5);+ getOrbitalDates.mockReturnValue(['2024-01-15']);+ renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(screen.getByTestId('btn-take-me-there')).not.toBeDisabled();+ });+ });++ // ── moveToDate ─────────────────────────────────────────────────────────────++ describe('moveToDate', () => {+ async function setupWithDateFound(date = '2024-03-15') {+ calculatePixels.mockResolvedValue(0.5);+ getOrbitalDates.mockReturnValue([date]);+ const { store } = renderComponent();+ selectLayerAndMethod();++ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ return { store };+ }++ it('dispatches SELECT_DATE when "Take Me There" is clicked', async () => {+ const { store } = await setupWithDateFound();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-take-me-there'));+ });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('dispatches SELECT_DATE with correct year/month/day parsed from dateFound', async () => {+ const { store } = await setupWithDateFound('2024-03-15');+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-take-me-there'));+ });+ const dispatched = store.getActions().find((a) => a.type === 'SELECT_DATE');+ expect(dispatched.date).toEqual(new Date(2024, 2, 15, 12, 0, 0));+ });++ it('dispatches SELECT_DATE with hour set to 12', async () => {+ const { store } = await setupWithDateFound('2024-06-01');+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-take-me-there'));+ });+ const dispatched = store.getActions().find((a) => a.type === 'SELECT_DATE');+ expect(dispatched.date.getHours()).toBe(12);+ });+ });++ // ── useEffect — reset dateFound on date change ────────────────────────────++ describe('useEffect — reset dateFound when selectedDate changes', () => {+ it('clears dateFound when selectedDate changes while dateFound is set', async () => {+ calculatePixels.mockResolvedValue(0.5);+ getOrbitalDates.mockReturnValue(['2024-01-15']);+ const store1 = buildStore();+ const { rerender } = render(+ <Provider store={store1}>+ <FindOrbitTracksMode />+ </Provider>,+ );++ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(screen.getByText('2024-01-15')).toBeInTheDocument();++ const store2 = buildStore({ selected: new Date('2024-02-01T00:00:00Z'), appNow: latestDate });+ await act(async () => {+ rerender(+ <Provider store={store2}>+ <FindOrbitTracksMode />+ </Provider>,+ );+ });++ expect(screen.getByText('No date found')).toBeInTheDocument();+ });++ it('does not clear dateFound when selectedDate is unchanged', async () => {+ calculatePixels.mockResolvedValue(0.5);+ getOrbitalDates.mockReturnValue(['2024-01-15']);+ const store1 = buildStore();+ const { rerender } = render(+ <Provider store={store1}>+ <FindOrbitTracksMode />+ </Provider>,+ );++ selectLayerAndMethod();+ await act(async () => {+ fireEvent.click(screen.getByTestId('btn-search-for-imagery'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });++ expect(screen.getByText('2024-01-15')).toBeInTheDocument();++ await act(async () => {+ rerender(+ <Provider store={store1}>+ <FindOrbitTracksMode />+ </Provider>,+ );+ });++ expect(screen.getByText('2024-01-15')).toBeInTheDocument();+ });+ });});diff --git a/web/js/mapUI/components/dev-test-mode/pixel-test-mode/dev-pixel-test.test.js b/web/js/mapUI/components/dev-test-mode/pixel-test-mode/dev-pixel-test.test.jsindex 34a4d48ed..8c4aaf200 100644--- a/web/js/mapUI/components/dev-test-mode/pixel-test-mode/dev-pixel-test.test.js+++ b/web/js/mapUI/components/dev-test-mode/pixel-test-mode/dev-pixel-test.test.js@@ -1,3 +1,498 @@-test('dev-pixel-test mapUI test', () => {+/* eslint-disable react/prop-types */+import { render, screen, fireEvent, act } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import PixelTestMode from './dev-pixel-test';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('@fortawesome/react-fontawesome', () => ({+ FontAwesomeIcon: ({ id, className }) => <span id={id} className={className} />,+}));++jest.mock('reactstrap', () => ({+ Button: ({+ children, onClick, disabled, color, className,+ }) => (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ data-color={color}+ className={className}+ data-testid="pixel-test-button"+ >+ {children}+ </button>+ ),+ UncontrolledTooltip: ({+ children, id, target, placement,+ }) => (+ <div+ data-testid="tooltip"+ data-id={id}+ data-target={target}+ data-placement={placement}+ >+ {children}+ </div>+ ),+}));++jest.mock('./tile-image-test-dropdown-selection', () => ({+ __esModule: true,+ default: ({ setLayerSelection }) => (+ <div data-testid="dropdown-selector">+ <button+ type="button"+ data-testid="dropdown-select-daily"+ onClick={() => setLayerSelection({ id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'daily' })}+ >+ Select Daily Layer+ </button>+ <button+ type="button"+ data-testid="dropdown-select-subdaily"+ onClick={() => setLayerSelection({ id: 'GOES-East_ABI_Band2_Red_Visible_1km', period: 'subdaily' })}+ >+ Select Subdaily Layer+ </button>+ <button+ type="button"+ data-testid="dropdown-select-no-threshold"+ onClick={() => setLayerSelection({ id: 'LAYER_NO_THRESHOLD', period: 'daily' })}+ >+ Select No Threshold Layer+ </button>+ </div>+ ),+}));++jest.mock('../../../../components/util/switch', () => ({+ __esModule: true,+ default: ({ id, label, active, toggle }) => (+ <div data-testid="switch-wrapper">+ <input+ type="checkbox"+ id={id}+ data-testid="extent-switch"+ checked={active}+ onChange={toggle}+ aria-label={label}+ />+ <label htmlFor={id}>{label}</label>+ </div>+ ),+}));++jest.mock('ol/proj', () => ({+ transformExtent: jest.fn((extent) => [`mercator_${extent[0]}`, extent[1], extent[2], extent[3]]),+}));++jest.mock('../../../../modules/layers/selectors', () => ({+ getActiveLayers: jest.fn(() => [+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'daily' },+ { id: 'GOES-East_ABI_Band2_Red_Visible_1km', period: 'subdaily' },+ ]),+}));++jest.mock('../utils/image-api-request-experimental', () => jest.fn());+jest.mock('../../kiosk/tile-measurement/utils/calculate-pixels', () => jest.fn());++jest.mock('../../kiosk/tile-measurement/utils/layer-data-eic', () => ({+ layerPixelData: {+ MODIS_Terra_CorrectedReflectance_TrueColor: { threshold: 0.5 },+ },+}));++jest.mock('../../kiosk/tile-measurement/utils/date-util', () => ({+ formatReduxDailyDate: jest.fn(() => '2024-01-15'),+ formatReduxSubdailyDate: jest.fn(() => '2024-01-15T12:00:00Z'),+}));++import { transformExtent } from 'ol/proj';+import { formatReduxDailyDate, formatReduxSubdailyDate } from '../../kiosk/tile-measurement/utils/date-util';+import fetchWMSImageExperimental from '../utils/image-api-request-experimental';+import calculatePixels from '../../kiosk/tile-measurement/utils/calculate-pixels';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockView = {+ getZoom: jest.fn(() => 8),+ calculateExtent: jest.fn(() => [-100, 30, -80, 50]),+ getSize: jest.fn(() => [800, 600]),+};++const mockMap = {+ getView: jest.fn(() => mockView),+ getSize: jest.fn(() => [800, 600]),+};++function buildStore() {+ return mockStore({+ map: { ui: { selected: mockMap } },+ compare: { activeString: 'activeA' },+ date: { selected: new Date('2024-01-15T00:00:00Z') },+ });+}++function renderComponent(store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <PixelTestMode />+ </Provider>,+ );+ return { ...utils, store: s };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('PixelTestMode', () => {+ let mockImgInstance;++ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'log').mockImplementation(() => {});+ jest.spyOn(console, 'error').mockImplementation(() => {});++ mockImgInstance = { src: null, onload: null, onerror: null };+ jest.spyOn(global, 'Image').mockImplementation(() => mockImgInstance);++ fetchWMSImageExperimental.mockResolvedValue('mock-wms-url');+ calculatePixels.mockResolvedValue(0.5);+ });++ afterEach(() => {+ console.log.mockRestore();+ console.error.mockRestore();+ global.Image.mockRestore();+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the "Pixel Test Mode" heading', () => {+ renderComponent();+ expect(screen.getByText('Pixel Test Mode')).toBeInTheDocument();+ });++ it('renders the heading as an h5 element', () => {+ renderComponent();+ expect(screen.getByText('Pixel Test Mode').tagName).toBe('H5');+ });++ it('renders the heading with correct classes', () => {+ renderComponent();+ expect(screen.getByText('Pixel Test Mode')).toHaveClass('h5', 'fw-bold', 'me-1');+ });++ it('renders the info icon with correct id', () => {+ renderComponent();+ expect(document.getElementById('pixel-test-info-icon')).toBeInTheDocument();+ });++ it('renders the tooltip with correct id', () => {+ renderComponent();+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-id', 'pixel-test-tooltip');+ });++ it('renders the tooltip with correct target', () => {+ renderComponent();+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-target', 'pixel-test-info-icon');+ });++ it('renders the tooltip with placement "right"', () => {+ renderComponent();+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-placement', 'right');+ });++ it('renders the tooltip with correct content', () => {+ renderComponent();+ expect(screen.getByText('Used to test the ratio of black pixels in an image tile. See PixelTestMode component.')).toBeInTheDocument();+ });++ it('renders the horizontal divider span', () => {+ const { container } = renderComponent();+ expect(container.querySelector('span.border-top')).toBeInTheDocument();+ });++ it('renders the "Pixel Test" button', () => {+ renderComponent();+ expect(screen.getByTestId('pixel-test-button')).toBeInTheDocument();+ });++ it('renders the "Pixel Test" button with color "primary"', () => {+ renderComponent();+ expect(screen.getByTestId('pixel-test-button')).toHaveAttribute('data-color', 'primary');+ });++ it('renders the "Pixel Test" button with class "mb-3"', () => {+ renderComponent();+ expect(screen.getByTestId('pixel-test-button')).toHaveClass('mb-3');+ });++ it('renders the DropdownSelector', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown-selector')).toBeInTheDocument();+ });++ it('renders the Switch', () => {+ renderComponent();+ expect(screen.getByTestId('extent-switch')).toBeInTheDocument();+ });++ it('renders the Switch with correct label', () => {+ renderComponent();+ expect(screen.getByText('Use current visual extent as bounding box')).toBeInTheDocument();+ });++ it('renders the outer wrapper with correct classes', () => {+ const { container } = renderComponent();+ expect(container.firstChild).toHaveClass(+ 'd-flex', 'flex-column', 'justify-content-center', 'align-items-center', 'mt-3',+ );+ });+ });++ // ── buttonDisabled logic ───────────────────────────────────────────────────++ describe('buttonDisabled logic', () => {+ it('disables "Pixel Test" when no layer is selected', () => {+ renderComponent();+ expect(screen.getByTestId('pixel-test-button')).toBeDisabled();+ });++ it('enables "Pixel Test" after a layer is selected', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ expect(screen.getByTestId('pixel-test-button')).not.toBeDisabled();+ });+ });++ // ── Switch / visualMapExtentSetting ───────────────────────────────────────++ describe('Switch / visualMapExtentSetting', () => {+ it('renders Switch as unchecked by default', () => {+ renderComponent();+ expect(screen.getByTestId('extent-switch')).not.toBeChecked();+ });++ it('toggles Switch to checked when clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('extent-switch'));+ expect(screen.getByTestId('extent-switch')).toBeChecked();+ });++ it('toggles Switch back to unchecked on second click', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('extent-switch'));+ fireEvent.click(screen.getByTestId('extent-switch'));+ expect(screen.getByTestId('extent-switch')).not.toBeChecked();+ });++ it('does NOT call transformExtent when visualMapExtentSetting is false', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });+ expect(transformExtent).not.toHaveBeenCalled();+ });++ it('calls transformExtent with EPSG:4326 -> EPSG:3857 when visualMapExtentSetting is true', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ fireEvent.click(screen.getByTestId('extent-switch'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });+ expect(transformExtent).toHaveBeenCalledWith([-100, 30, -80, 50], 'EPSG:4326', 'EPSG:3857');+ });++ it('passes mercatorExtent to fetchWMSImageExperimental when visualMapExtentSetting is true', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ fireEvent.click(screen.getByTestId('extent-switch'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ });+ expect(fetchWMSImageExperimental).toHaveBeenCalledWith(+ expect.any(String),+ expect.any(String),+ expect.arrayContaining([expect.anything()]),+ );+ });++ it('passes undefined extent to fetchWMSImageExperimental when visualMapExtentSetting is false', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ });+ expect(fetchWMSImageExperimental).toHaveBeenCalledWith(+ expect.any(String),+ expect.any(String),+ undefined,+ );+ });+ });++ // ── formatDate ────────────────────────────────────────────────────────────++ describe('formatDate', () => {+ it('calls formatReduxDailyDate when layer period is "daily"', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ });+ expect(formatReduxDailyDate).toHaveBeenCalledTimes(1);+ expect(formatReduxSubdailyDate).not.toHaveBeenCalled();+ });++ it('calls formatReduxSubdailyDate when layer period is "subdaily"', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-subdaily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ });+ expect(formatReduxSubdailyDate).toHaveBeenCalledTimes(1);+ expect(formatReduxDailyDate).not.toHaveBeenCalled();+ });++ it('passes the selectedDate from the store to formatReduxDailyDate', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ });+ expect(formatReduxDailyDate).toHaveBeenCalledWith(new Date('2024-01-15T00:00:00Z'));+ });+ });++ // ── makeMeasurementRequest ─────────────────────────────────────────────────++ describe('makeMeasurementRequest', () => {+ it('calls fetchWMSImageExperimental with layerId and formattedDate', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ });+ expect(fetchWMSImageExperimental).toHaveBeenCalledWith(+ 'MODIS_Terra_CorrectedReflectance_TrueColor',+ '2024-01-15',+ undefined,+ );+ });++ it('sets img.src to the returned wmsImage url', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ });+ expect(mockImgInstance.src).toBe('mock-wms-url');+ });++ it('calls calculatePixels with wmsImage when img.onload fires', async () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });+ expect(calculatePixels).toHaveBeenCalledWith('mock-wms-url');+ });++ it('logs pixel ratio and threshold message when threshold exists', async () => {+ calculatePixels.mockResolvedValue(0.3);+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('The current threshold for MODIS_Terra_CorrectedReflectance_TrueColor is 50%'),+ );+ });++ it('logs pixel ratio with "no current threshold" message when no threshold exists', async () => {+ calculatePixels.mockResolvedValue(0.3);+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-no-threshold'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('There is no current threshold for LAYER_NO_THRESHOLD'),+ );+ });++ it('logs the correct black pixel ratio percentage', async () => {+ calculatePixels.mockResolvedValue(0.25);+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ if (mockImgInstance.onload) await mockImgInstance.onload();+ });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('25%'),+ );+ });++ it('calls console.error on img.onerror', async () => {+ const mockError = new Error('image error');+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ await Promise.resolve();+ if (mockImgInstance.onerror) mockImgInstance.onerror(mockError);+ });+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('No image available for MODIS_Terra_CorrectedReflectance_TrueColor on 2024-01-15'),+ mockError,+ );+ });++ it('calls console.error when fetchWMSImageExperimental throws', async () => {+ fetchWMSImageExperimental.mockRejectedValue(new Error('fetch failed'));+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ await act(async () => {+ fireEvent.click(screen.getByTestId('pixel-test-button'));+ });+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('No image available for MODIS_Terra_CorrectedReflectance_TrueColor on 2024-01-15'),+ expect.any(Error),+ );+ });++ it('does not call fetchWMSImageExperimental before the button is clicked', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-select-daily'));+ expect(fetchWMSImageExperimental).not.toHaveBeenCalled();+ });+ });});diff --git a/web/js/mapUI/components/dev-test-mode/pixel-test-mode/tile-image-test-dropdown-selection.test.js b/web/js/mapUI/components/dev-test-mode/pixel-test-mode/tile-image-test-dropdown-selection.test.jsindex 01b0f5a56..d497b777a 100644--- a/web/js/mapUI/components/dev-test-mode/pixel-test-mode/tile-image-test-dropdown-selection.test.js+++ b/web/js/mapUI/components/dev-test-mode/pixel-test-mode/tile-image-test-dropdown-selection.test.js@@ -1,3 +1,229 @@-test('tile-image-test-dropdown-selection mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+/* eslint-disable react/prop-types */+import { render, screen, fireEvent } from '@testing-library/react';+import '@testing-library/jest-dom';+import TileImageTestModeDropdown from './tile-image-test-dropdown-selection';+jest.mock('reactstrap', () => ({+ Dropdown: ({ children, isOpen, toggle, className }) => (+ <div+ data-testid="dropdown"+ data-open={String(isOpen)}+ className={className}+ >+ <button type="button" data-testid="dropdown-toggle-trigger" onClick={toggle} />+ {children}+ </div>+ ),+ DropdownToggle: ({ children, style, caret }) => (+ <button+ type="button"+ data-testid="dropdown-toggle"+ style={style}+ data-caret={String(!!caret)}+ >+ {children}+ </button>+ ),+ DropdownMenu: ({ children, style, className }) => (+ <div data-testid="dropdown-menu" style={style} className={className}>+ {children}+ </div>+ ),+ DropdownItem: ({ children, onClick, className }) => (+ <button+ type="button"+ data-testid={`dropdown-item-${children}`}+ onClick={onClick}+ className={className}+ >+ {children}+ </button>+ ),+}));++const mockActiveLayers = [+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'daily' },+ { id: 'VIIRS_SNPP_Orbital_Track', period: 'daily' },+ { id: 'GOES-East_ABI_Band2_Red_Visible_1km', period: 'subdaily' },+];++const mockLayerSelection = { id: 'Select Layer', period: 'daily' };++function buildProps(overrides = {}) {+ return {+ activeLayers: mockActiveLayers,+ layerSelection: mockLayerSelection,+ setLayerSelection: jest.fn(),+ ...overrides,+ };+}++function renderComponent(overrides = {}) {+ const props = buildProps(overrides);+ const utils = render(<TileImageTestModeDropdown {...props} />);+ return { ...utils, props };+}++describe('TileImageTestModeDropdown', () => {+ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the Dropdown wrapper', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown')).toBeInTheDocument();+ });++ it('renders the Dropdown with class "mb-3 mt-2"', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown')).toHaveClass('mb-3', 'mt-2');+ });++ it('renders the DropdownToggle with the current layerSelection id', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown-toggle')).toHaveTextContent('Select Layer');+ });++ it('renders the DropdownToggle with the correct background color', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown-toggle')).toHaveStyle({ backgroundColor: '#d54e21' });+ });++ it('renders the DropdownToggle with caret', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown-toggle')).toHaveAttribute('data-caret', 'true');+ });++ it('renders the DropdownMenu with class "bg-dark"', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown-menu')).toHaveClass('bg-dark');+ });++ it('renders the DropdownMenu with correct transform style', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown-menu')).toHaveStyle({+ transform: 'translate3d(-30px, 0px, 0px)',+ });+ });++ it('renders a DropdownItem for each active layer', () => {+ renderComponent();+ mockActiveLayers.forEach((layer) => {+ expect(screen.getByTestId(`dropdown-item-${layer.id}`)).toBeInTheDocument();+ });+ });++ it('renders the correct number of DropdownItems', () => {+ renderComponent();+ expect(screen.getAllByTestId(/^dropdown-item-/)).toHaveLength(mockActiveLayers.length);+ });++ it('renders each DropdownItem with correct text', () => {+ renderComponent();+ mockActiveLayers.forEach((layer) => {+ expect(screen.getByTestId(`dropdown-item-${layer.id}`)).toHaveTextContent(layer.id);+ });+ });++ it('renders each DropdownItem with correct classes', () => {+ renderComponent();+ mockActiveLayers.forEach((layer) => {+ expect(screen.getByTestId(`dropdown-item-${layer.id}`)).toHaveClass('text-white', 'bg-dark');+ });+ });++ it('reflects a different layerSelection id in the toggle', () => {+ renderComponent({ layerSelection: { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'daily' } });+ expect(screen.getByTestId('dropdown-toggle')).toHaveTextContent('MODIS_Terra_CorrectedReflectance_TrueColor');+ });++ it('renders with an empty activeLayers array without crashing', () => {+ expect(() => renderComponent({ activeLayers: [] })).not.toThrow();+ });++ it('renders no DropdownItems when activeLayers is empty', () => {+ renderComponent({ activeLayers: [] });+ expect(screen.queryAllByTestId(/^dropdown-item-/)).toHaveLength(0);+ });+ });++ describe('dropdownOpen state / toggle', () => {+ it('renders dropdown as closed (isOpen=false) by default', () => {+ renderComponent();+ expect(screen.getByTestId('dropdown')).toHaveAttribute('data-open', 'false');+ });++ it('opens the dropdown when toggle is called', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-toggle-trigger'));+ expect(screen.getByTestId('dropdown')).toHaveAttribute('data-open', 'true');+ });++ it('closes the dropdown on second toggle call', () => {+ renderComponent();+ fireEvent.click(screen.getByTestId('dropdown-toggle-trigger'));+ fireEvent.click(screen.getByTestId('dropdown-toggle-trigger'));+ expect(screen.getByTestId('dropdown')).toHaveAttribute('data-open', 'false');+ });++ it('toggles open/closed correctly across multiple clicks', () => {+ renderComponent();+ const trigger = screen.getByTestId('dropdown-toggle-trigger');+ fireEvent.click(trigger);+ expect(screen.getByTestId('dropdown')).toHaveAttribute('data-open', 'true');+ fireEvent.click(trigger);+ expect(screen.getByTestId('dropdown')).toHaveAttribute('data-open', 'false');+ fireEvent.click(trigger);+ expect(screen.getByTestId('dropdown')).toHaveAttribute('data-open', 'true');+ });+ });++ describe('handleSelection', () => {+ it('calls setLayerSelection when a DropdownItem is clicked', () => {+ const { props } = renderComponent();+ fireEvent.click(screen.getByTestId(`dropdown-item-${mockActiveLayers[0].id}`));+ expect(props.setLayerSelection).toHaveBeenCalledTimes(1);+ });++ it('calls setLayerSelection with the correct layer object', () => {+ const { props } = renderComponent();+ fireEvent.click(screen.getByTestId(`dropdown-item-${mockActiveLayers[0].id}`));+ expect(props.setLayerSelection).toHaveBeenCalledWith(mockActiveLayers[0]);+ });++ it('calls setLayerSelection with the second layer when second item is clicked', () => {+ const { props } = renderComponent();+ fireEvent.click(screen.getByTestId(`dropdown-item-${mockActiveLayers[1].id}`));+ expect(props.setLayerSelection).toHaveBeenCalledWith(mockActiveLayers[1]);+ });++ it('calls setLayerSelection with the third layer when third item is clicked', () => {+ const { props } = renderComponent();+ fireEvent.click(screen.getByTestId(`dropdown-item-${mockActiveLayers[2].id}`));+ expect(props.setLayerSelection).toHaveBeenCalledWith(mockActiveLayers[2]);+ });++ it('does not call setLayerSelection before any item is clicked', () => {+ const { props } = renderComponent();+ expect(props.setLayerSelection).not.toHaveBeenCalled();+ });++ it('calls setLayerSelection once per click even when clicked multiple times', () => {+ const { props } = renderComponent();+ const item = screen.getByTestId(`dropdown-item-${mockActiveLayers[0].id}`);+ fireEvent.click(item);+ fireEvent.click(item);+ expect(props.setLayerSelection).toHaveBeenCalledTimes(2);+ });++ it('always passes the full layer object including period', () => {+ const { props } = renderComponent();+ fireEvent.click(screen.getByTestId(`dropdown-item-${mockActiveLayers[2].id}`));+ expect(props.setLayerSelection).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'GOES-East_ABI_Band2_Red_Visible_1km', period: 'subdaily' }),+ );+ });+ });});diff --git a/web/js/mapUI/components/eic/eic.test.js b/web/js/mapUI/components/eic/eic.test.jsindex d1f486074..e790c7109 100644--- a/web/js/mapUI/components/eic/eic.test.js+++ b/web/js/mapUI/components/eic/eic.test.js@@ -1,3 +1,324 @@-test('eic mapUI test', () => {+/* eslint-disable react/jsx-pascal-case */+import { render, act } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import EIC from './eic';+jest.mock('../../../modules/date/actions', () => ({+ selectDate: jest.fn((date) => ({ type: 'SELECT_DATE', date })),+}));++jest.mock('../../../modules/ui/actions', () => ({+ setEICLegacy: jest.fn((isLegacy) => ({ type: 'SET_EIC_LEGACY', isLegacy })),+}));++const mockStore = configureMockStore();++function buildStore(overrides = {}) {+ return mockStore({+ ui: {+ eic: 'si',+ eicLegacy: false,+ scenario: 'test-scenario-id',+ ...overrides,+ },+ });+}++function renderComponent(store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <EIC />+ </Provider>,+ );+ return { ...utils, store: s };+}++// The json override must be wrapped in jest.fn().mockResolvedValue() separately+// so that passing { json: { resolution_date: '...' } } does not replace the+// function with a plain object, which would cause "response.json is not a function"+function buildFetchResponse({ ok = true, jsonData = { resolution_date: '2024-06-15' }, fetchOverrides = {} } = {}) {+ return {+ ok,+ json: jest.fn().mockResolvedValue(jsonData),+ ...fetchOverrides,+ };+}++describe('EIC', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'warn').mockImplementation(() => {});+ global.fetch = jest.fn();+ });++ afterEach(() => {+ console.warn.mockRestore();+ delete global.fetch;+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse());+ let container;+ await act(async () => {+ ({ container } = renderComponent());+ });+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect guard conditions ─────────────────────────────────────────────++ describe('useEffect guard conditions', () => {+ it('calls fetch when scenario is set, eicLegacy is false, and eic is "si"', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse());+ await act(() => {+ renderComponent(buildStore({ eic: 'si', eicLegacy: false, scenario: 'my-scenario' }));+ });+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });++ it('does NOT call fetch when scenario is an empty string', async () => {+ await act(() => {+ renderComponent(buildStore({ scenario: '' }));+ });+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('does NOT call fetch when eicLegacy is true', async () => {+ await act(() => {+ renderComponent(buildStore({ eicLegacy: true }));+ });+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('does NOT call fetch when eic is not "si"', async () => {+ await act(() => {+ renderComponent(buildStore({ eic: 'other' }));+ });+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('does NOT call fetch when eic is an empty string', async () => {+ await act(() => {+ renderComponent(buildStore({ eic: '' }));+ });+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('does NOT call fetch when all three conditions fail', async () => {+ await act(() => {+ renderComponent(buildStore({ eic: 'other', eicLegacy: true, scenario: '' }));+ });+ expect(global.fetch).not.toHaveBeenCalled();+ });+ });++ // ── requestBestDate: fetch URL ─────────────────────────────────────────────++ describe('requestBestDate: fetch URL', () => {+ it('calls fetch with the correct URL including scenario id', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse());+ await act(() => {+ renderComponent(buildStore({ scenario: 'test-scenario-id' }));+ });+ expect(global.fetch).toHaveBeenCalledWith(+ 'https://worldview.earthdata.nasa.gov/eic/scenarios?item_type=scenario&item_id=test-scenario-id',+ { timeout: 10000 },+ );+ });++ it('builds the URL with a different scenario id', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse());+ await act(() => {+ renderComponent(buildStore({ scenario: 'another-scenario' }));+ });+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('item_id=another-scenario'),+ expect.anything(),+ );+ });++ it('calls fetch with timeout 10000', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse());+ await act(async () => {+ renderComponent();+ });+ expect(global.fetch).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ timeout: 10000 }),+ );+ });+ });++ // ── requestBestDate: successful response ───────────────────────────────────++ describe('requestBestDate: successful response', () => {+ it('dispatches SELECT_DATE with a Date object on a valid resolution_date', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ jsonData: { resolution_date: '2024-06-15' } }));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('dispatches SELECT_DATE with the correct Date value', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ jsonData: { resolution_date: '2024-06-15' } }));+ const { store } = renderComponent();+ await act(async () => {});+ const dispatched = store.getActions().find((a) => a.type === 'SELECT_DATE');+ expect(dispatched.date).toEqual(new Date('2024-06-15'));+ });++ it('does NOT dispatch SET_EIC_LEGACY on a valid resolution_date', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ jsonData: { resolution_date: '2024-06-15' } }));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_LEGACY' }),+ );+ });++ it('does NOT call console.warn on a valid resolution_date', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ jsonData: { resolution_date: '2024-06-15' } }));+ renderComponent();+ await act(async () => {});+ expect(console.warn).not.toHaveBeenCalled();+ });+ });++ // ── requestBestDate: "No valid date found" ─────────────────────────────────++ describe('requestBestDate: "No valid date found" resolution_date', () => {+ it('dispatches SET_EIC_LEGACY(true) when resolution_date is "No valid date found"', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ jsonData: { resolution_date: 'No valid date found' } }));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_LEGACY', isLegacy: true }),+ );+ });++ it('does NOT dispatch SELECT_DATE when resolution_date is "No valid date found"', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ jsonData: { resolution_date: 'No valid date found' } }));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('logs a warning when resolution_date is "No valid date found"', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ jsonData: { resolution_date: 'No valid date found' } }));+ renderComponent();+ await act(async () => {});+ expect(console.warn).toHaveBeenCalledWith(+ 'No valid date found, using EIC Legacy mode',+ );+ });+ });++ // ── requestBestDate: response.ok is false ──────────────────────────────────++ describe('requestBestDate: response.ok is false', () => {+ it('dispatches SET_EIC_LEGACY(true) when response.ok is false', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ ok: false }));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_LEGACY', isLegacy: true }),+ );+ });++ it('does NOT dispatch SELECT_DATE when response.ok is false', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ ok: false }));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('logs a warning when response.ok is false', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ ok: false }));+ renderComponent();+ await act(async () => {});+ expect(console.warn).toHaveBeenCalledWith(+ 'Error fetching the best date, using EIC Legacy mode:',+ expect.any(Error),+ );+ });++ it('throws an error with message "Network response was not ok." when response.ok is false', async () => {+ global.fetch.mockResolvedValue(buildFetchResponse({ ok: false }));+ renderComponent();+ await act(async () => {});+ const warnArg = console.warn.mock.calls[0][1];+ expect(warnArg.message).toBe('Network response was not ok.');+ });+ });++ // ── requestBestDate: fetch throws ─────────────────────────────────────────++ describe('requestBestDate: fetch throws', () => {+ it('dispatches SET_EIC_LEGACY(true) when fetch rejects', async () => {+ global.fetch.mockRejectedValue(new Error('Network error'));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_LEGACY', isLegacy: true }),+ );+ });++ it('does NOT dispatch SELECT_DATE when fetch rejects', async () => {+ global.fetch.mockRejectedValue(new Error('Network error'));+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('logs a warning with the error when fetch rejects', async () => {+ const mockError = new Error('Network error');+ global.fetch.mockRejectedValue(mockError);+ renderComponent();+ await act(async () => {});+ expect(console.warn).toHaveBeenCalledWith(+ 'Error fetching the best date, using EIC Legacy mode:',+ mockError,+ );+ });++ it('dispatches SET_EIC_LEGACY(true) when response.json() rejects', async () => {+ global.fetch.mockResolvedValue({+ ok: true,+ json: jest.fn().mockRejectedValue(new Error('JSON parse error')),+ });+ const { store } = renderComponent();+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_LEGACY', isLegacy: true }),+ );+ });++ it('logs a warning when response.json() rejects', async () => {+ const jsonError = new Error('JSON parse error');+ global.fetch.mockResolvedValue({+ ok: true,+ json: jest.fn().mockRejectedValue(jsonError),+ });+ renderComponent();+ await act(async () => {});+ expect(console.warn).toHaveBeenCalledWith(+ 'Error fetching the best date, using EIC Legacy mode:',+ jsonError,+ );+ });+ });});diff --git a/web/js/mapUI/components/granule-hover/granuleHover.test.js b/web/js/mapUI/components/granule-hover/granuleHover.test.jsindex f3b692f52..76c46c355 100644--- a/web/js/mapUI/components/granule-hover/granuleHover.test.js+++ b/web/js/mapUI/components/granule-hover/granuleHover.test.js@@ -1,3 +1,288 @@-test('granuleHover mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import ConnectedGranuleHover from './granuleHover';+import { GRANULE_HOVERED, GRANULE_HOVER_UPDATE } from '../../../util/constants';+jest.mock('../../../util/util', () => ({+ __esModule: true,+ default: {+ events: {+ on: jest.fn(),+ },+ },+}));++import util from '../../../util/util';++jest.mock('../../../modules/layers/selectors', () => ({+ getActiveGranuleFootPrints: jest.fn(),+}));++import { getActiveGranuleFootPrints } from '../../../modules/layers/selectors';++const mockStore = configureMockStore();++const mockProjectionCode = 'EPSG:4326';++const mockProjection = {+ getCode: jest.fn(() => mockProjectionCode),+};++const mockView = {+ getProjection: jest.fn(() => mockProjection),+};++const mockSelectedMap = {+ getView: jest.fn(() => mockView),+};++const mockAddFootprint = jest.fn();+const mockUpdateFootprint = jest.fn();++const mockGranuleFootprintLayer = {+ addFootprint: mockAddFootprint,+ updateFootprint: mockUpdateFootprint,+};++function buildGranuleFootprints(proj = mockProjectionCode, layer = mockGranuleFootprintLayer) {+ return { [proj]: layer };+}++function buildStore(stateOverrides = {}) {+ return mockStore({+ layers: {},+ ...stateOverrides,+ });+}++function buildProps(overrides = {}) {+ return {+ granuleFootprints: buildGranuleFootprints(),+ ui: { selected: mockSelectedMap },+ ...overrides,+ };+}++function renderComponent(props, store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <ConnectedGranuleHover {...props} />+ </Provider>,+ );+ return { ...utils, store: s };+}++function getHandler(eventName) {+ const call = util.events.on.mock.calls.find(([event]) => event === eventName);+ return call ? call[1] : null;+}++describe('GranuleHover', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ util.events.on = jest.fn();+ mockProjection.getCode.mockReturnValue(mockProjectionCode);+ getActiveGranuleFootPrints.mockReturnValue({});+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const { container } = renderComponent(buildProps());+ expect(container.firstChild).toBeNull();+ });+ });++ // ── events.on registration ─────────────────────────────────────────────────++ describe('events.on registration', () => {+ it('registers a GRANULE_HOVERED handler', () => {+ renderComponent(buildProps());+ expect(util.events.on).toHaveBeenCalledWith(GRANULE_HOVERED, expect.any(Function));+ });++ it('registers a GRANULE_HOVER_UPDATE handler', () => {+ renderComponent(buildProps());+ expect(util.events.on).toHaveBeenCalledWith(GRANULE_HOVER_UPDATE, expect.any(Function));+ });++ it('registers exactly two event handlers', () => {+ renderComponent(buildProps());+ expect(util.events.on).toHaveBeenCalledTimes(2);+ });+ });++ // ── onGranuleHover ─────────────────────────────────────────────────────────++ describe('onGranuleHover', () => {+ it('calls addFootprint when proj exists in granuleFootprints', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler('TERRA', '2024-01-15');+ expect(mockAddFootprint).toHaveBeenCalledTimes(1);+ });++ it('calls addFootprint with geometry and date when platform and date are provided', () => {+ const mockGeometry = { type: 'Polygon', coordinates: [] };+ getActiveGranuleFootPrints.mockReturnValue({ '2024-01-15': mockGeometry });+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler('TERRA', '2024-01-15');+ expect(mockAddFootprint).toHaveBeenCalledWith(mockGeometry, '2024-01-15');+ });++ it('calls addFootprint with undefined geometry when platform is falsy', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler(null, '2024-01-15');+ expect(mockAddFootprint).toHaveBeenCalledWith(undefined, '2024-01-15');+ });++ it('calls addFootprint with undefined geometry when date is falsy', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler('TERRA', null);+ expect(mockAddFootprint).toHaveBeenCalledWith(undefined, null);+ });++ it('calls addFootprint with undefined geometry when both platform and date are falsy', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler(null, null);+ expect(mockAddFootprint).toHaveBeenCalledWith(undefined, null);+ });++ it('does NOT call addFootprint when proj is not in granuleFootprints', () => {+ const props = buildProps({ granuleFootprints: {} });+ renderComponent(props);+ const handler = getHandler(GRANULE_HOVERED);+ handler('TERRA', '2024-01-15');+ expect(mockAddFootprint).not.toHaveBeenCalled();+ });++ it('calls getActiveGranuleFootPrints with state when platform and date are provided', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler('TERRA', '2024-01-15');+ expect(getActiveGranuleFootPrints).toHaveBeenCalledTimes(1);+ });++ it('does NOT call getActiveGranuleFootPrints when platform is falsy', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler(null, '2024-01-15');+ expect(getActiveGranuleFootPrints).not.toHaveBeenCalled();+ });++ it('does NOT call getActiveGranuleFootPrints when date is falsy', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVERED);+ handler('TERRA', null);+ expect(getActiveGranuleFootPrints).not.toHaveBeenCalled();+ });++ it('uses the correct projection code from ui.selected', () => {+ mockProjection.getCode.mockReturnValue('EPSG:3413');+ const props = buildProps({+ granuleFootprints: { 'EPSG:3413': mockGranuleFootprintLayer },+ });+ renderComponent(props);+ const handler = getHandler(GRANULE_HOVERED);+ handler('TERRA', '2024-01-15');+ expect(mockAddFootprint).toHaveBeenCalledTimes(1);+ });+ });++ // ── onGranuleHoverUpdate ───────────────────────────────────────────────────++ describe('onGranuleHoverUpdate', () => {+ it('calls updateFootprint when proj exists, platform and date provided, and geometry exists', () => {+ const mockGeometry = { type: 'Polygon', coordinates: [] };+ getActiveGranuleFootPrints.mockReturnValue({ '2024-01-15': mockGeometry });+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler('TERRA', '2024-01-15');+ expect(mockUpdateFootprint).toHaveBeenCalledWith(mockGeometry, '2024-01-15');+ });++ it('does NOT call updateFootprint when proj is not in granuleFootprints', () => {+ renderComponent(buildProps({ granuleFootprints: {} }));+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler('TERRA', '2024-01-15');+ expect(mockUpdateFootprint).not.toHaveBeenCalled();+ });++ it('does NOT call updateFootprint when geometry is undefined (platform falsy)', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler(null, '2024-01-15');+ expect(mockUpdateFootprint).not.toHaveBeenCalled();+ });++ it('does NOT call updateFootprint when geometry is undefined (date falsy)', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler('TERRA', null);+ expect(mockUpdateFootprint).not.toHaveBeenCalled();+ });++ it('does NOT call updateFootprint when geometry is not found in active footprints', () => {+ getActiveGranuleFootPrints.mockReturnValue({});+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler('TERRA', '2024-01-15');+ expect(mockUpdateFootprint).not.toHaveBeenCalled();+ });++ it('calls getActiveGranuleFootPrints with state when platform and date are provided', () => {+ const mockGeometry = { type: 'Polygon', coordinates: [] };+ getActiveGranuleFootPrints.mockReturnValue({ '2024-01-15': mockGeometry });+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler('TERRA', '2024-01-15');+ expect(getActiveGranuleFootPrints).toHaveBeenCalledTimes(1);+ });++ it('does NOT call getActiveGranuleFootPrints when platform is falsy', () => {+ renderComponent(buildProps());+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler(null, '2024-01-15');+ expect(getActiveGranuleFootPrints).not.toHaveBeenCalled();+ });++ it('uses the correct projection code from ui.selected', () => {+ mockProjection.getCode.mockReturnValue('EPSG:3413');+ const mockGeometry = { type: 'Polygon', coordinates: [] };+ getActiveGranuleFootPrints.mockReturnValue({ '2024-01-15': mockGeometry });+ const props = buildProps({+ granuleFootprints: { 'EPSG:3413': mockGranuleFootprintLayer },+ });+ renderComponent(props);+ const handler = getHandler(GRANULE_HOVER_UPDATE);+ handler('TERRA', '2024-01-15');+ expect(mockUpdateFootprint).toHaveBeenCalledTimes(1);+ });+ });++ // ── mapStateToProps ────────────────────────────────────────────────────────++ describe('mapStateToProps', () => {+ it('passes the full Redux state as the "state" prop', () => {+ const customState = { layers: { active: [] }, date: { selected: new Date() } };+ const store = buildStore(customState);+ const props = buildProps();+ renderComponent(props, store);+ const handler = getHandler(GRANULE_HOVERED);+ const mockGeometry = { type: 'Polygon' };+ getActiveGranuleFootPrints.mockReturnValue({ '2024-01-15': mockGeometry });+ handler('TERRA', '2024-01-15');+ expect(getActiveGranuleFootPrints).toHaveBeenCalledWith(+ expect.objectContaining(customState),+ );+ });+ });});diff --git a/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.test.js b/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.test.jsindex 8d538e29b..39691a8b8 100644--- a/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.test.js+++ b/web/js/mapUI/components/kiosk/kiosk-animations/kiosk-animations.test.js@@ -1,3 +1,350 @@-test('kiosk-animations mapUI test', () => {+import { render } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import KioskAnimations from './kiosk-animations';+jest.mock('../../../../modules/animation/actions', () => ({+ onActivate: jest.fn(() => ({ type: 'INITIATE_ANIMATION' })),+ playKioskAnimation: jest.fn((startDate, endDate) => ({+ type: 'PLAY_KIOSK_ANIMATION',+ startDate,+ endDate,+ })),+}));++jest.mock('../../../../modules/date/actions', () => ({+ selectDate: jest.fn((date) => ({ type: 'SELECT_DATE', date })),+}));++const mockStore = configureMockStore();++const mockSelectedDate = new Date('2024-06-15T12:00:00Z');++const mockSelected = { frameState_: {} };++function buildStore(overrides = {}) {+ return mockStore({+ date: { selected: mockSelectedDate },+ animation: { isPlaying: false },+ map: { ui: { selected: mockSelected } },+ ui: {+ isKioskModeActive: true,+ eic: 'da',+ eicMeasurementComplete: true,+ eicMeasurementAborted: false,+ },+ ...overrides,+ });+}++function buildUi(frameState = {}) {+ return { selected: { frameState_: frameState } };+}++function renderComponent(store, ui = buildUi()) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <KioskAnimations ui={ui} />+ </Provider>,+ );+ return { ...utils, store: s };+}++describe('KioskAnimations', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const { container } = renderComponent();+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect guard conditions ─────────────────────────────────────────────++ describe('useEffect guard conditions', () => {+ it('does NOT dispatch when ui.selected is null', () => {+ const { store } = renderComponent(buildStore(), { selected: null });+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT dispatch when isKioskModeActive is false', () => {+ const { store } = renderComponent(buildStore({ ui: { isKioskModeActive: false, eic: 'da', eicMeasurementComplete: true, eicMeasurementAborted: false } }));+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT dispatch when eicMeasurementComplete is false', () => {+ const { store } = renderComponent(buildStore({ ui: { isKioskModeActive: true, eic: 'da', eicMeasurementComplete: false, eicMeasurementAborted: false } }));+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT dispatch when isAnimationPlaying is true', () => {+ const { store } = renderComponent(buildStore({ animation: { isPlaying: true }, ui: { isKioskModeActive: true, eic: 'da', eicMeasurementComplete: true, eicMeasurementAborted: false } }));+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT dispatch when eic is not "sa" or "da" (eicAnimationMode is false)', () => {+ const { store } = renderComponent(buildStore({ ui: { isKioskModeActive: true, eic: 'si', eicMeasurementComplete: true, eicMeasurementAborted: false } }));+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT dispatch when eicMeasurementAborted is true', () => {+ const { store } = renderComponent(buildStore({ ui: { isKioskModeActive: true, eic: 'da', eicMeasurementComplete: true, eicMeasurementAborted: true } }));+ expect(store.getActions()).toHaveLength(0);+ });++ it('does NOT dispatch when ui.selected has no frameState_', () => {+ const { store } = renderComponent(buildStore(), { selected: {} });+ expect(store.getActions()).toHaveLength(0);+ });+ });++ // ── eicAnimationMode ───────────────────────────────────────────────────────++ describe('eicAnimationMode', () => {+ it('is active when eic is "sa"', () => {+ const { store } = renderComponent(buildStore({ ui: { isKioskModeActive: true, eic: 'sa', eicMeasurementComplete: true, eicMeasurementAborted: false } }));+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('is active when eic is "da"', () => {+ const { store } = renderComponent(buildStore());+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'INITIATE_ANIMATION' }),+ );+ });++ it('is NOT active when eic is "si"', () => {+ const { store } = renderComponent(buildStore({ ui: { isKioskModeActive: true, eic: 'si', eicMeasurementComplete: true, eicMeasurementAborted: false } }));+ expect(store.getActions()).toHaveLength(0);+ });+ });++ // ── checkAnimationSettings: daily (eic === "da") ───────────────────────────++ describe('checkAnimationSettings: daily mode (eic === "da")', () => {+ it('dispatches INITIATE_ANIMATION when dailyPlayCheck is true', () => {+ const { store } = renderComponent(buildStore());+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'INITIATE_ANIMATION' }),+ );+ });++ it('dispatches PLAY_KIOSK_ANIMATION when dailyPlayCheck is true', () => {+ const { store } = renderComponent(buildStore());+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'PLAY_KIOSK_ANIMATION' }),+ );+ });++ it('does NOT dispatch SELECT_DATE in daily mode', () => {+ const { store } = renderComponent(buildStore());+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('does NOT dispatch when isAnimationPlaying is true (dailyPlayCheck is false)', () => {+ const store = buildStore({+ animation: { isPlaying: true },+ ui: { isKioskModeActive: true, eic: 'da', eicMeasurementComplete: true, eicMeasurementAborted: false },+ });+ renderComponent(store);+ expect(store.getActions()).toHaveLength(0);+ });+ });++ // ── checkAnimationSettings: subdaily (eic === "sa") ───────────────────────++ describe('checkAnimationSettings: subdaily mode (eic === "sa")', () => {+ const subdailyStore = () => buildStore({+ ui: {+ isKioskModeActive: true,+ eic: 'sa',+ eicMeasurementComplete: true,+ eicMeasurementAborted: false,+ },+ });++ it('dispatches SELECT_DATE on first render to move date back one day', () => {+ const { store } = renderComponent(subdailyStore());+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('dispatches SELECT_DATE with the previous day', () => {+ const { store } = renderComponent(subdailyStore());+ const action = store.getActions().find((a) => a.type === 'SELECT_DATE');+ const expectedPrevDay = new Date(mockSelectedDate);+ expectedPrevDay.setDate(expectedPrevDay.getDate() - 1);+ expect(action.date.toDateString()).toBe(expectedPrevDay.toDateString());+ });++ it('does NOT dispatch INITIATE_ANIMATION on first subdaily render', () => {+ const { store } = renderComponent(subdailyStore());+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'INITIATE_ANIMATION' }),+ );+ });++ it('does NOT dispatch PLAY_KIOSK_ANIMATION on first subdaily render', () => {+ const { store } = renderComponent(subdailyStore());+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'PLAY_KIOSK_ANIMATION' }),+ );+ });+ });++ // ── handleAnimationSettings: PLAY_KIOSK_ANIMATION payload ─────────────────++ describe('handleAnimationSettings: PLAY_KIOSK_ANIMATION payload', () => {+ it('dispatches PLAY_KIOSK_ANIMATION with startDate and endDate', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action).toHaveProperty('startDate');+ expect(action).toHaveProperty('endDate');+ });++ it('dispatches PLAY_KIOSK_ANIMATION with endDate equal to selectedDate (zeroed)', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.endDate.getSeconds()).toBe(0);+ expect(action.endDate.getMilliseconds()).toBe(0);+ });++ it('dispatches PLAY_KIOSK_ANIMATION with startDate before endDate', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.startDate.getTime()).toBeLessThan(action.endDate.getTime());+ });+ });++ // ── updateStartTime: daily subtracts 1 month ───────────────────────────────++ describe('updateStartTime: daily mode subtracts 1 month', () => {+ it('sets startDate approximately 1 month before endDate', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ const diffMs = action.endDate.getTime() - action.startDate.getTime();+ const diffDays = diffMs / (1000 * 60 * 60 * 24);+ expect(diffDays).toBeGreaterThanOrEqual(28);+ expect(diffDays).toBeLessThanOrEqual(31);+ });+ });++ // ── updateStartTime: subdaily subtracts 6 hours ────────────────────────────++ describe('updateStartTime: subdaily mode subtracts 6 hours', () => {+ it('sets startDate exactly 6 hours before selectedDate for subdaily after date shift', () => {+ const store = buildStore({+ ui: {+ isKioskModeActive: true,+ eic: 'sa',+ eicMeasurementComplete: true,+ eicMeasurementAborted: false,+ },+ animation: { isPlaying: false },+ });++ const { rerender } = render(+ <Provider store={store}>+ <KioskAnimations ui={buildUi()} />+ </Provider>,+ );++ const updatedStore = buildStore({+ date: { selected: new Date('2024-06-14T12:00:00Z') },+ animation: { isPlaying: false },+ ui: {+ isKioskModeActive: true,+ eic: 'sa',+ eicMeasurementComplete: true,+ eicMeasurementAborted: false,+ },+ });++ rerender(+ <Provider store={updatedStore}>+ <KioskAnimations ui={buildUi()} />+ </Provider>,+ );++ const action = updatedStore.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ if (action) {+ const diffMs = action.endDate.getTime() - action.startDate.getTime();+ const diffHours = diffMs / (1000 * 60 * 60);+ expect(diffHours).toBe(6);+ }+ });+ });++ // ── zeroDates ──────────────────────────────────────────────────────────────++ describe('zeroDates', () => {+ it('zeros seconds on startDate to 0', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.startDate.getSeconds()).toBe(0);+ });++ it('zeros milliseconds on startDate to 0', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.startDate.getMilliseconds()).toBe(0);+ });++ it('zeros seconds on endDate to 0', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.endDate.getSeconds()).toBe(0);+ });++ it('zeros milliseconds on endDate to 0', () => {+ const { store } = renderComponent(buildStore());+ const action = store.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.endDate.getMilliseconds()).toBe(0);+ });++ it('rounds startDate minutes down to the nearest 10', () => {+ const storeWithOddMinutes = buildStore({+ date: { selected: new Date('2024-06-15T12:37:45.123Z') },+ ui: { isKioskModeActive: true, eic: 'da', eicMeasurementComplete: true, eicMeasurementAborted: false },+ animation: { isPlaying: false },+ });+ renderComponent(storeWithOddMinutes);+ const action = storeWithOddMinutes.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.startDate.getUTCMinutes() % 10).toBe(0);+ });++ it('rounds endDate minutes down to the nearest 10', () => {+ const storeWithOddMinutes = buildStore({+ date: { selected: new Date('2024-06-15T12:37:45.123Z') },+ ui: { isKioskModeActive: true, eic: 'da', eicMeasurementComplete: true, eicMeasurementAborted: false },+ animation: { isPlaying: false },+ });+ renderComponent(storeWithOddMinutes);+ const action = storeWithOddMinutes.getActions().find((a) => a.type === 'PLAY_KIOSK_ANIMATION');+ expect(action.endDate.getUTCMinutes() % 10).toBe(0);+ });+ });++ // ── dispatch order ─────────────────────────────────────────────────────────++ describe('dispatch order', () => {+ it('dispatches INITIATE_ANIMATION before PLAY_KIOSK_ANIMATION', () => {+ const { store } = renderComponent(buildStore());+ const actions = store.getActions().map((a) => a.type);+ const initiateIdx = actions.indexOf('INITIATE_ANIMATION');+ const playIdx = actions.indexOf('PLAY_KIOSK_ANIMATION');+ expect(initiateIdx).toBeLessThan(playIdx);+ });+ });});diff --git a/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.test.js b/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.test.jsindex 89e86d32b..cf68052b5 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.test.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/tile-measurement.test.js@@ -1,3 +1,599 @@-test('tile-measurement mapUI test', () => {+import { render, act } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import TileMeasurement from './tile-measurement';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('../../../../modules/date/actions', () => ({+ selectDate: jest.fn((date) => ({ type: 'SELECT_DATE', date })),+}));++jest.mock('../../../../modules/ui/actions', () => ({+ setEICMeasurementComplete: jest.fn(() => ({ type: 'SET_EIC_MEASUREMENT_COMPLETE' })),+ setEICMeasurementAborted: jest.fn(() => ({ type: 'SET_EIC_MEASUREMENT_ABORTED' })),+ toggleStaticMap: jest.fn((isActive) => ({ type: 'TOGGLE_STATIC_MAP', isActive })),+}));++jest.mock('../../../../modules/layers/actions', () => ({+ toggleGroupVisibility: jest.fn((ids, visible) => ({ type: 'TOGGLE_GROUP_VISIBILITY', ids, visible })),+}));++jest.mock('../../../../modules/layers/selectors', () => ({+ getActiveLayers: jest.fn(() => []),+}));++jest.mock('./utils/date-util', () => ({+ getDates: jest.fn(() => ['2024-06-15', '2024-06-14', '2024-06-13']),+}));++jest.mock('./utils/image-api-request', () => jest.fn());+jest.mock('./utils/calculate-pixels', () => jest.fn());++jest.mock('./utils/layer-data-eic', () => ({+ layersToMeasure: ['MODIS_Terra_CorrectedReflectance_TrueColor'],+ layerPixelData: {+ MODIS_Terra_CorrectedReflectance_TrueColor: { threshold: 0.70 },+ },+ bestDates: {+ MODIS_Terra_CorrectedReflectance_TrueColor: { date: '2023-10-29' },+ },+}));++jest.mock('./utils/verify-map-tiles', () => jest.fn());++jest.mock('ol/proj', () => ({+ transformExtent: jest.fn((extent) => extent),+}));++import { getActiveLayers } from '../../../../modules/layers/selectors';+import { getDates } from './utils/date-util';+import fetchWMSImage from './utils/image-api-request';+import calculatePixels from './utils/calculate-pixels';+import countTilesForSpecifiedLayers from './utils/verify-map-tiles';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockView = {+ calculateExtent: jest.fn(() => [-180, -90, 180, 90]),+ getSize: jest.fn(() => [800, 600]),+};++const mockSelected = {+ getView: jest.fn(() => mockView),+ getSize: jest.fn(() => [800, 600]),+};++const mockUi = { selected: mockSelected };++const mockActiveLayers = [+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'daily' },+];++function buildStore(overrides = {}) {+ return mockStore({+ ui: {+ eic: 'si',+ eicLegacy: false,+ scenario: '',+ ...overrides.ui,+ },+ date: {+ appNow: new Date('2024-06-15T00:00:00Z'),+ ...overrides.date,+ },+ compare: { activeString: 'activeA' },+ layers: { active: [] },+ ...overrides,+ });+}++function buildDefaultTileResult(overrides = {}) {+ return {+ totalExpectedTileCount: 4,+ totalLoadedTileCount: 4,+ totalTilesLoadedWithBadImage: 0,+ totalErrorTiles: 0,+ totalEmptyTiles: 0,+ totalOtherTileStates: [],+ ...overrides,+ };+}++function renderComponent(store, ui = mockUi) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <TileMeasurement ui={ui} />+ </Provider>,+ );+ return { ...utils, store: s };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('TileMeasurement', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();+ jest.spyOn(console, 'log').mockImplementation(() => {});+ jest.spyOn(console, 'error').mockImplementation(() => {});++ getActiveLayers.mockReturnValue(mockActiveLayers);+ getDates.mockReturnValue(['2024-06-15', '2024-06-14', '2024-06-13']);+ fetchWMSImage.mockResolvedValue('blob:mock-url');+ calculatePixels.mockResolvedValue(0.3);+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult());+ });++ afterEach(() => {+ jest.useRealTimers();+ console.log.mockRestore();+ console.error.mockRestore();+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const { container } = renderComponent();+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect guard conditions ─────────────────────────────────────────────++ describe('useEffect guard conditions', () => {+ it('does NOT call calculateMeasurements when eic is falsy', async () => {+ const store = buildStore({ ui: { eic: '', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).not.toHaveBeenCalled();+ });++ it('does NOT call calculateMeasurements when ui.selected is null', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store, { selected: null });+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).not.toHaveBeenCalled();+ });++ it('does NOT call calculateMeasurements when activeLayers is falsy', async () => {+ getActiveLayers.mockReturnValue(null);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).not.toHaveBeenCalled();+ });++ it('does NOT call calculateMeasurements when both eicLegacy is false AND scenario is set', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: 'some-scenario' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).not.toHaveBeenCalled();+ });++ it('calls calculateMeasurements when eicLegacy is true (regardless of scenario)', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: true, scenario: 'some-scenario' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).toHaveBeenCalled();+ });++ it('calls calculateMeasurements when scenario is empty string', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).toHaveBeenCalled();+ });++ it('only triggers calculateMeasurements once (measurementsStarted guard)', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).toHaveBeenCalledTimes(1);+ });+ });++ // ── findLayersToMeasure ────────────────────────────────────────────────────++ describe('findLayersToMeasure', () => {+ it('logs layer count when matching layers are found', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('EIC layer(s) found to measure'),+ );+ });++ it('aborts and calls verifyTilesAndHandleErrors when no matching layers found', async () => {+ getActiveLayers.mockReturnValue([{ id: 'NON_MATCHING_LAYER', period: 'daily' }]);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.error).toHaveBeenCalledWith(+ 'No layers found to be measured... Aborting...',+ );+ expect(countTilesForSpecifiedLayers).toHaveBeenCalled();+ });++ it('filters layers by layersToMeasure', async () => {+ getActiveLayers.mockReturnValue([+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'daily' },+ { id: 'NON_EIC_LAYER', period: 'daily' },+ ]);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).toHaveBeenCalledWith(+ 'MODIS_Terra_CorrectedReflectance_TrueColor',+ expect.any(String),+ expect.anything(),+ );+ expect(fetchWMSImage).not.toHaveBeenCalledWith(+ 'NON_EIC_LAYER',+ expect.any(String),+ expect.anything(),+ );+ });++ it('uses "subdaily" period when any layer is subdaily', async () => {+ getActiveLayers.mockReturnValue([+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'subdaily' },+ ]);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(getDates).toHaveBeenCalledWith(expect.anything(), 'subdaily');+ });++ it('uses "daily" period when no layers are subdaily', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(getDates).toHaveBeenCalledWith(expect.anything(), 'daily');+ });+ });++ // ── findDateRange ──────────────────────────────────────────────────────────++ describe('findDateRange', () => {+ it('aborts when getDates returns falsy', async () => {+ getDates.mockReturnValue(null);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.error).toHaveBeenCalledWith('No date range found... Aborting..');+ expect(countTilesForSpecifiedLayers).toHaveBeenCalled();+ });++ it('calls getDates with realTime from the store', async () => {+ const appNow = new Date('2024-06-15T00:00:00Z');+ const store = buildStore({+ ui: { eic: 'si', eicLegacy: false, scenario: '' },+ date: { appNow },+ });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(getDates).toHaveBeenCalledWith(appNow, expect.any(String));+ });+ });++ // ── findFullImageryDate ────────────────────────────────────────────────────++ describe('findFullImageryDate', () => {+ it('calls fetchWMSImage for each date until threshold is satisfied', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(fetchWMSImage).toHaveBeenCalledWith(+ 'MODIS_Terra_CorrectedReflectance_TrueColor',+ '2024-06-15',+ expect.anything(),+ );+ });++ it('dispatches SELECT_DATE with the full imagery date found', async () => {+ calculatePixels.mockResolvedValue(0.3);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ });++ it('logs when a layer is BELOW the threshold', async () => {+ calculatePixels.mockResolvedValue(0.3);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('BELOW the threshold'),+ );+ });++ it('logs when a layer is BREAKING the threshold', async () => {+ calculatePixels.mockResolvedValue(0.9);+ getDates.mockReturnValue(['2024-06-15']);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('BREAKING the threshold'),+ );+ });++ it('logs when all layers meet threshold for a date', async () => {+ calculatePixels.mockResolvedValue(0.3);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.log).toHaveBeenCalledWith(+ expect.stringContaining('All layers meet thresholds'),+ );+ });++ it('returns the best date when fetchWMSImage throws', async () => {+ fetchWMSImage.mockRejectedValue(new Error('WMS error'));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.error).toHaveBeenCalledWith(+ expect.stringContaining('No WMS image tile available'),+ expect.any(Error),+ );+ });++ it('falls back to best date when no date satisfies threshold', async () => {+ calculatePixels.mockResolvedValue(0.9);+ getDates.mockReturnValue(['2024-06-15']);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ const selectAction = store.getActions().find((a) => a.type === 'SELECT_DATE');+ expect(selectAction).toBeDefined();+ });++ it('logs error when no best date exists for any layer', async () => {+ calculatePixels.mockResolvedValue(0.9);+ getDates.mockReturnValue(['2024-06-15']);+ getActiveLayers.mockReturnValue([+ { id: 'VIIRS_SNPP_NDVI_8Day', period: 'daily' },+ ]);+ jest.mock('./utils/layer-data-eic', () => ({+ layersToMeasure: ['VIIRS_SNPP_NDVI_8Day'],+ layerPixelData: { VIIRS_SNPP_NDVI_8Day: { threshold: 0.70 } },+ bestDates: {},+ }));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.error).toHaveBeenCalled();+ });+ });++ // ── updateDate ─────────────────────────────────────────────────────────────++ describe('updateDate', () => {+ it('dispatches SELECT_DATE with a daily date parsed as local noon', async () => {+ calculatePixels.mockResolvedValue(0.3);+ getDates.mockReturnValue(['2024-06-15']);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ const action = store.getActions().find((a) => a.type === 'SELECT_DATE');+ expect(action.date).toEqual(new Date(2024, 5, 15, 12, 0, 0));+ });++ it('dispatches SELECT_DATE with a subdaily ISO date as UTC', async () => {+ getActiveLayers.mockReturnValue([+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', period: 'subdaily' },+ ]);+ getDates.mockReturnValue(['2024-06-15T14:30:00.000Z']);+ calculatePixels.mockResolvedValue(0.3);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ const action = store.getActions().find((a) => a.type === 'SELECT_DATE');+ expect(action.date).toEqual(new Date(Date.UTC(2024, 5, 15, 14, 30, 0)));+ });+ });++ // ── calculateMeasurements: bestDate branch ─────────────────────────────────++ describe('calculateMeasurements: bestDate branch', () => {+ it('uses best date and calls verifyTiles when fullImageryDate equals bestDate', async () => {+ calculatePixels.mockResolvedValue(0.9);+ getDates.mockReturnValue(['2023-10-29']);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SELECT_DATE' }),+ );+ expect(countTilesForSpecifiedLayers).toHaveBeenCalled();+ });++ it('uses best date when fullImageryDate is null/undefined', async () => {+ fetchWMSImage.mockRejectedValue(new Error('fail'));+ getDates.mockReturnValue(['2024-06-15']);+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(countTilesForSpecifiedLayers).toHaveBeenCalled();+ });+ });++ // ── verifyTilesAndHandleErrors ─────────────────────────────────────────────++ describe('verifyTilesAndHandleErrors', () => {+ it('calls countTilesForSpecifiedLayers', async () => {+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(countTilesForSpecifiedLayers).toHaveBeenCalled();+ });++ it('dispatches SET_EIC_MEASUREMENT_COMPLETE when eic is "da" and not aborted', async () => {+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult());+ const store = buildStore({ ui: { eic: 'da', eicLegacy: true, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_MEASUREMENT_COMPLETE' }),+ );+ });++ it('dispatches SET_EIC_MEASUREMENT_COMPLETE when eic is "sa" and not aborted', async () => {+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult());+ const store = buildStore({ ui: { eic: 'sa', eicLegacy: true, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_MEASUREMENT_COMPLETE' }),+ );+ });++ it('dispatches SET_EIC_MEASUREMENT_COMPLETE when tiles are loaded and not aborted', async () => {+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult(+ { totalLoadedTileCount: 4 },+ ));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_MEASUREMENT_COMPLETE' }),+ );+ });++ it('dispatches SET_EIC_MEASUREMENT_ABORTED when tiles loaded but abort is true', async () => {+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult(+ { totalLoadedTileCount: 0 },+ ));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => {+ await Promise.resolve();+ jest.runAllTicks();+ });++ await act(async () => {+ for (let i = 0; i < 11; i += 1) {+ jest.advanceTimersByTime(1000);+ await Promise.resolve();+ }+ });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_EIC_MEASUREMENT_ABORTED' }),+ );+ });++ it('dispatches TOGGLE_STATIC_MAP(true) when no tiles found and aborted', async () => {+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult(+ { totalLoadedTileCount: 0 },+ ));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => {+ await Promise.resolve();+ jest.runAllTicks();+ });++ await act(async () => {+ for (let i = 0; i < 11; i += 1) {+ jest.advanceTimersByTime(1000);+ await Promise.resolve();+ }+ });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'TOGGLE_STATIC_MAP', isActive: true }),+ );+ });++ it('dispatches TOGGLE_GROUP_VISIBILITY with active layer ids and false when aborted with no tiles', async () => {+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult(+ { totalLoadedTileCount: 0 },+ ));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => {+ await Promise.resolve();+ jest.runAllTicks();+ });++ await act(async () => {+ for (let i = 0; i < 11; i += 1) {+ jest.advanceTimersByTime(1000);+ await Promise.resolve();+ }+ });+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({+ type: 'TOGGLE_GROUP_VISIBILITY',+ ids: ['MODIS_Terra_CorrectedReflectance_TrueColor'],+ visible: false,+ }),+ );+ });++ it('retries up to 10 times when loadedTilesCount is 0', async () => {+ countTilesForSpecifiedLayers.mockReturnValue(buildDefaultTileResult(+ { totalLoadedTileCount: 0 },+ ));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => {+ await Promise.resolve();+ jest.runAllTicks();+ });++ await act(async () => {+ for (let i = 0; i < 11; i += 1) {+ jest.advanceTimersByTime(1000);+ await Promise.resolve();+ }+ });+ expect(countTilesForSpecifiedLayers).toHaveBeenCalledTimes(10);+ });++ it('breaks out of retry loop when loadedTilesCount > 0', async () => {+ countTilesForSpecifiedLayers+ .mockReturnValueOnce(buildDefaultTileResult({ totalLoadedTileCount: 0 }))+ .mockReturnValueOnce(buildDefaultTileResult({ totalLoadedTileCount: 4 }));+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => {+ await Promise.resolve();+ jest.runAllTicks();+ });++ await act(async () => {+ for (let i = 0; i < 11; i += 1) {+ jest.advanceTimersByTime(1000);+ await Promise.resolve();+ }+ });+ expect(countTilesForSpecifiedLayers).toHaveBeenCalledTimes(2);+ });+ });++ // ── error handling ─────────────────────────────────────────────────────────++ describe('error handling', () => {+ it('logs "Error calculating measurements:" when calculateMeasurements throws', async () => {+ getDates.mockImplementation(() => { throw new Error('unexpected'); });+ const store = buildStore({ ui: { eic: 'si', eicLegacy: false, scenario: '' } });+ renderComponent(store);+ await act(async () => { jest.runAllTimers(); });+ expect(console.error).toHaveBeenCalledWith(+ 'Error calculating measurements:',+ expect.any(Error),+ );+ });+ });});diff --git a/web/js/mapUI/components/kiosk/tile-measurement/utils/calculate-pixels.test.js b/web/js/mapUI/components/kiosk/tile-measurement/utils/calculate-pixels.test.jsindex 1b1245f57..f43320dae 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/utils/calculate-pixels.test.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/utils/calculate-pixels.test.js@@ -1,3 +1,300 @@-test('calcualte-pixels mapUI test', () => {+import calculateBlackPixelRatio from './calculate-pixels';+// ─── Canvas mock setup ────────────────────────────────────────────────────────++// Builds a mock canvas context whose getImageData returns a controlled pixel array+function buildMockCtx(pixelData) {+ return {+ drawImage: jest.fn(),+ getImageData: jest.fn(() => ({ data: pixelData })),+ };+}++// Builds a mock canvas element using a given ctx+function buildMockCanvas(ctx) {+ return {+ getContext: jest.fn(() => ctx),+ width: 0,+ height: 0,+ };+}++// Helper to build a flat RGBA pixel array for an N×N image+// Each pixel is described as [r, g, b, a]+function buildPixelData(pixels) {+ return new Uint8ClampedArray(pixels.flat());+}++// Convenience to build a 1×1 target with a given pixel+function buildTarget(width, height) {+ return { width, height };+}++describe('calculateBlackPixelRatio', () => {+ let mockImgInstance;+ let mockCtx;+ let mockCanvas;++ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'error').mockImplementation(() => {});++ mockImgInstance = { src: null, onload: null, onerror: null };+ jest.spyOn(global, 'Image').mockImplementation(() => mockImgInstance);++ mockCtx = buildMockCtx([]);+ mockCanvas = buildMockCanvas(mockCtx);++ jest.spyOn(document, 'createElement').mockImplementation((tag) => {+ if (tag === 'canvas') return mockCanvas;+ return document.createElement.wrappedMethod+ ? document.createElement.wrappedMethod(tag)+ : {};+ });+ });++ afterEach(() => {+ console.error.mockRestore();+ global.Image.mockRestore();+ document.createElement.mockRestore();+ });++ // ── Return value ───────────────────────────────────────────────────────────++ describe('Return value', () => {+ it('returns a Promise', () => {+ const result = calculateBlackPixelRatio('blob:mock-url');+ expect(result).toBeInstanceOf(Promise);+ });+ });++ // ── img.src ────────────────────────────────────────────────────────────────++ describe('img.src', () => {+ it('sets img.src to the provided blobUrl', () => {+ calculateBlackPixelRatio('blob:test-url');+ expect(mockImgInstance.src).toBe('blob:test-url');+ });++ it('sets img.src to an empty string when blobUrl is empty', () => {+ calculateBlackPixelRatio('');+ expect(mockImgInstance.src).toBe('');+ });+ });++ // ── canvas setup ───────────────────────────────────────────────────────────++ describe('canvas setup', () => {+ it('creates a canvas element via document.createElement', async () => {+ const target = buildTarget(4, 4);+ mockCtx.getImageData.mockReturnValue({ data: buildPixelData(Array(16).fill([0, 0, 0, 0])) });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ await promise;+ expect(document.createElement).toHaveBeenCalledWith('canvas');+ });++ it('sets canvas.width to target.width', async () => {+ const target = buildTarget(10, 5);+ mockCtx.getImageData.mockReturnValue({ data: buildPixelData(Array(50).fill([0, 0, 0, 0])) });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ await promise;+ expect(mockCanvas.width).toBe(10);+ });++ it('sets canvas.height to target.height', async () => {+ const target = buildTarget(10, 5);+ mockCtx.getImageData.mockReturnValue({ data: buildPixelData(Array(50).fill([0, 0, 0, 0])) });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ await promise;+ expect(mockCanvas.height).toBe(5);+ });++ it('calls ctx.drawImage with the target and its dimensions', async () => {+ const target = buildTarget(8, 8);+ mockCtx.getImageData.mockReturnValue({+ data: buildPixelData(Array(64).fill([255, 255, 255, 255])),+ });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ await promise;+ expect(mockCtx.drawImage).toHaveBeenCalledWith(target, 0, 0, 8, 8);+ });++ it('calls ctx.getImageData with correct dimensions', async () => {+ const target = buildTarget(3, 3);+ mockCtx.getImageData.mockReturnValue({+ data: buildPixelData(Array(9).fill([255, 255, 255, 255])),+ });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ await promise;+ expect(mockCtx.getImageData).toHaveBeenCalledWith(0, 0, 3, 3);+ });++ it('calls canvas.getContext with "2d"', async () => {+ const target = buildTarget(2, 2);+ mockCtx.getImageData.mockReturnValue({ data: buildPixelData(Array(4).fill([0, 0, 0, 0])) });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ await promise;+ expect(mockCanvas.getContext).toHaveBeenCalledWith('2d');+ });+ });++ // ── black pixel counting ───────────────────────────────────────────────────++ describe('black pixel counting', () => {+ async function resolveWithPixels(pixels, width, height) {+ const target = buildTarget(width, height);+ mockCtx.getImageData.mockReturnValue({ data: buildPixelData(pixels) });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ return promise;+ }++ it('resolves with 0 when all pixels are white (255,255,255,255)', async () => {+ const result = await resolveWithPixels(+ Array(4).fill([255, 255, 255, 255]),+ 2, 2,+ );+ expect(result).toBe(0);+ });++ it('resolves with 1 when all pixels are fully black (0,0,0,255)', async () => {+ const result = await resolveWithPixels(+ Array(4).fill([0, 0, 0, 255]),+ 2, 2,+ );+ expect(result).toBe(1);+ });++ it('resolves with 1 when all pixels are transparent black (0,0,0,0)', async () => {+ const result = await resolveWithPixels(+ Array(4).fill([0, 0, 0, 0]),+ 2, 2,+ );+ expect(result).toBe(1);+ });++ it('resolves with 0.5 when half the pixels are black (0,0,0,255)', async () => {+ const pixels = [+ [0, 0, 0, 255],+ [0, 0, 0, 255],+ [255, 255, 255, 255],+ [255, 255, 255, 255],+ ];+ const result = await resolveWithPixels(pixels, 2, 2);+ expect(result).toBe(0.5);+ });++ it('resolves with 0.25 when one of four pixels is black', async () => {+ const pixels = [+ [0, 0, 0, 255],+ [255, 0, 0, 255],+ [0, 255, 0, 255],+ [0, 0, 255, 255],+ ];+ const result = await resolveWithPixels(pixels, 2, 2);+ expect(result).toBe(0.25);+ });++ it('does NOT count a pixel as black when alpha is not 255 or 0', async () => {+ const pixels = [[0, 0, 0, 128]];+ const result = await resolveWithPixels(pixels, 1, 1);+ expect(result).toBe(0);+ });++ it('does NOT count a pixel as black when only R is 0', async () => {+ const pixels = [[0, 255, 255, 255]];+ const result = await resolveWithPixels(pixels, 1, 1);+ expect(result).toBe(0);+ });++ it('does NOT count a pixel as black when only G is 0', async () => {+ const pixels = [[255, 0, 255, 255]];+ const result = await resolveWithPixels(pixels, 1, 1);+ expect(result).toBe(0);+ });++ it('does NOT count a pixel as black when only B is 0', async () => {+ const pixels = [[255, 255, 0, 255]];+ const result = await resolveWithPixels(pixels, 1, 1);+ expect(result).toBe(0);+ });++ it('resolves with 1 for a single fully black pixel (1×1)', async () => {+ const result = await resolveWithPixels([[0, 0, 0, 255]], 1, 1);+ expect(result).toBe(1);+ });++ it('resolves with 0 for a single white pixel (1×1)', async () => {+ const result = await resolveWithPixels([[255, 255, 255, 255]], 1, 1);+ expect(result).toBe(0);+ });++ it('correctly counts transparent black pixels (alpha 0) as black', async () => {+ const pixels = [+ [0, 0, 0, 0],+ [255, 255, 255, 255],+ ];+ const result = await resolveWithPixels(pixels, 2, 1);+ expect(result).toBe(0.5);+ });++ it('resolves with 0 for an image with no pixels (0×0)', async () => {+ const target = buildTarget(0, 0);+ mockCtx.getImageData.mockReturnValue({ data: new Uint8ClampedArray([]) });+ const promise = calculateBlackPixelRatio('blob:url');+ await mockImgInstance.onload({ target });+ const result = await promise;+ expect(result).toBeNaN();+ });++ it('handles a large image correctly', async () => {+ const size = 100;+ const halfBlack = Array(size * size / 2).fill([0, 0, 0, 255]);+ const halfWhite = Array(size * size / 2).fill([255, 255, 255, 255]);+ const result = await resolveWithPixels([...halfBlack, ...halfWhite], size, size);+ expect(result).toBe(0.5);+ });+ });++ // ── img.onerror ────────────────────────────────────────────────────────────++ describe('img.onerror', () => {+ it('rejects the promise when img.onerror fires', async () => {+ const mockError = new Error('load failed');+ const promise = calculateBlackPixelRatio('blob:bad-url');+ mockImgInstance.onerror(mockError);+ await expect(promise).rejects.toThrow('load failed');+ });++ it('calls console.error with "Image loading error:" when onerror fires', async () => {+ const mockError = new Error('load failed');+ const promise = calculateBlackPixelRatio('blob:bad-url');+ mockImgInstance.onerror(mockError);+ await promise.catch(() => {});+ expect(console.error).toHaveBeenCalledWith('Image loading error:', mockError);+ });++ it('rejects with the original error object', async () => {+ const mockError = new Event('error');+ const promise = calculateBlackPixelRatio('blob:bad-url');+ mockImgInstance.onerror(mockError);+ await expect(promise).rejects.toBe(mockError);+ });++ it('does NOT resolve when onerror fires', async () => {+ const mockError = new Error('fail');+ let resolved = false;+ const promise = calculateBlackPixelRatio('blob:bad-url');+ promise.then(() => { resolved = true; }).catch(() => {});+ mockImgInstance.onerror(mockError);+ await promise.catch(() => {});+ expect(resolved).toBe(false);+ });+ });});diff --git a/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.test.js b/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.test.jsindex f962f4bbb..10091c515 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.test.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/utils/date-util.test.js@@ -1,3 +1,466 @@-test('date-util mapUI test', () => {+import {+ formatDailyDate,+ formatSubdailyDate,+ formatReduxDailyDate,+ formatReduxSubdailyDate,+ getDates,+ getOrbitalDatesBackwards,+ getOrbitalDatesForwards,+ getOrbitalDatesForwardsAndBackwards,+ getOrbitalDates,+} from './date-util';+// ─── formatDailyDate ──────────────────────────────────────────────────────────++describe('formatDailyDate', () => {+ it('formats a standard date correctly', () => {+ expect(formatDailyDate(new Date(2024, 5, 15))).toBe('2024-06-15');+ });++ it('pads single-digit month with a leading zero', () => {+ expect(formatDailyDate(new Date(2024, 0, 5))).toBe('2024-01-05');+ });++ it('pads single-digit day with a leading zero', () => {+ expect(formatDailyDate(new Date(2024, 11, 3))).toBe('2024-12-03');+ });++ it('formats the last day of the year correctly', () => {+ expect(formatDailyDate(new Date(2024, 11, 31))).toBe('2024-12-31');+ });++ it('formats the first day of the year correctly', () => {+ expect(formatDailyDate(new Date(2024, 0, 1))).toBe('2024-01-01');+ });++ it('returns a string in YYYY-MM-DD format', () => {+ expect(formatDailyDate(new Date(2020, 2, 20))).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });+});++// ─── formatSubdailyDate ───────────────────────────────────────────────────────++describe('formatSubdailyDate', () => {+ it('formats a date with time correctly', () => {+ expect(formatSubdailyDate(new Date(2024, 5, 15, 14, 30))).toBe('2024-06-15T14:30:00Z');+ });++ it('pads single-digit hour with a leading zero', () => {+ expect(formatSubdailyDate(new Date(2024, 5, 15, 9, 5))).toBe('2024-06-15T09:05:00Z');+ });++ it('pads single-digit minute with a leading zero', () => {+ expect(formatSubdailyDate(new Date(2024, 5, 15, 10, 7))).toBe('2024-06-15T10:07:00Z');+ });++ it('formats midnight correctly', () => {+ expect(formatSubdailyDate(new Date(2024, 5, 15, 0, 0))).toBe('2024-06-15T00:00:00Z');+ });++ it('always ends with :00Z', () => {+ const result = formatSubdailyDate(new Date(2024, 5, 15, 12, 45));+ expect(result).toMatch(/:00Z$/);+ });++ it('returns a string in YYYY-MM-DDTHH:MM:00Z format', () => {+ expect(formatSubdailyDate(new Date(2024, 5, 15, 8, 20))).toMatch(+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00Z$/,+ );+ });+});++// ─── formatReduxDailyDate ─────────────────────────────────────────────────────++describe('formatReduxDailyDate', () => {+ it('formats a UTC date string correctly', () => {+ expect(formatReduxDailyDate(new Date('2024-06-15T00:00:00Z'))).toBe('2024-06-15');+ });++ it('pads single-digit month with a leading zero', () => {+ expect(formatReduxDailyDate(new Date('2024-01-05T00:00:00Z'))).toBe('2024-01-05');+ });++ it('pads single-digit day with a leading zero', () => {+ expect(formatReduxDailyDate(new Date('2024-03-03T00:00:00Z'))).toBe('2024-03-03');+ });++ it('formats the last day of the year correctly', () => {+ expect(formatReduxDailyDate(new Date('2024-12-31T00:00:00Z'))).toBe('2024-12-31');+ });++ it('returns a string in YYYY-MM-DD format', () => {+ expect(formatReduxDailyDate(new Date('2022-08-20T00:00:00Z'))).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });++ it('ignores the time component', () => {+ expect(formatReduxDailyDate(new Date('2024-06-15T23:59:59Z'))).toBe('2024-06-15');+ });+});++// ─── formatReduxSubdailyDate ──────────────────────────────────────────────────++describe('formatReduxSubdailyDate', () => {+ it('formats a UTC datetime correctly', () => {+ expect(formatReduxSubdailyDate(new Date('2024-06-15T14:30:00Z'))).toBe('2024-06-15T14:30:00Z');+ });++ it('pads single-digit hour with a leading zero', () => {+ expect(formatReduxSubdailyDate(new Date('2024-06-15T09:05:00Z'))).toBe('2024-06-15T09:05:00Z');+ });++ it('pads single-digit minute with a leading zero', () => {+ expect(formatReduxSubdailyDate(new Date('2024-06-15T10:07:00Z'))).toBe('2024-06-15T10:07:00Z');+ });++ it('formats midnight correctly', () => {+ expect(formatReduxSubdailyDate(new Date('2024-06-15T00:00:00Z'))).toBe('2024-06-15T00:00:00Z');+ });++ it('always ends with :00Z', () => {+ expect(formatReduxSubdailyDate(new Date('2024-06-15T12:45:00Z'))).toMatch(/:00Z$/);+ });++ it('returns a string in YYYY-MM-DDTHH:MM:00Z format', () => {+ expect(formatReduxSubdailyDate(new Date('2024-06-15T08:20:00Z'))).toMatch(+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00Z$/,+ );+ });+});++// ─── getDates ─────────────────────────────────────────────────────────────────++describe('getDates', () => {+ const selectedDate = new Date('2024-06-15T12:00:00Z');++ describe('daily period', () => {+ it('returns an array when period is "daily"', () => {+ expect(Array.isArray(getDates(selectedDate, 'daily'))).toBe(true);+ });++ it('returns 7 dates for daily period', () => {+ expect(getDates(selectedDate, 'daily')).toHaveLength(7);+ });++ it('first date is the selected date', () => {+ const dates = getDates(selectedDate, 'daily');+ expect(dates[0]).toBe('2024-06-15');+ });++ it('dates are in descending order (most recent first)', () => {+ const dates = getDates(selectedDate, 'daily');+ expect(dates[0]).toBe('2024-06-15');+ expect(dates[1]).toBe('2024-06-14');+ expect(dates[2]).toBe('2024-06-13');+ });++ it('last date is 6 days before the selected date', () => {+ const dates = getDates(selectedDate, 'daily');+ expect(dates[6]).toBe('2024-06-09');+ });++ it('all dates match YYYY-MM-DD format', () => {+ getDates(selectedDate, 'daily').forEach((d) => {+ expect(d).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });+ });++ it('wraps correctly around month boundaries', () => {+ const monthBoundary = new Date('2024-07-02T00:00:00Z');+ const dates = getDates(monthBoundary, 'daily');+ expect(dates).toContain('2024-06-30');+ expect(dates).toContain('2024-06-29');+ });++ it('wraps correctly around year boundaries', () => {+ const yearBoundary = new Date('2024-01-03T00:00:00Z');+ const dates = getDates(yearBoundary, 'daily');+ expect(dates).toContain('2023-12-31');+ expect(dates).toContain('2023-12-30');+ });+ });++ describe('subdaily period', () => {+ it('returns an array when period is "subdaily"', () => {+ expect(Array.isArray(getDates(selectedDate, 'subdaily'))).toBe(true);+ });++ it('returns 13 dates for subdaily period', () => {+ expect(getDates(selectedDate, 'subdaily')).toHaveLength(13);+ });++ it('all dates match subdaily format YYYY-MM-DDTHH:MM:00Z', () => {+ getDates(selectedDate, 'subdaily').forEach((d) => {+ expect(d).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00Z$/);+ });+ });++ it('all minutes are multiples of 10', () => {+ getDates(selectedDate, 'subdaily').forEach((d) => {+ const minutes = parseInt(d.slice(14, 16), 10);+ expect(minutes % 10).toBe(0);+ });+ });++ it('dates are in descending order (most recent first)', () => {+ const dates = getDates(selectedDate, 'subdaily');+ for (let i = 1; i < dates.length; i += 1) {+ expect(new Date(dates[i]).getTime()).toBeLessThan(new Date(dates[i - 1]).getTime());+ }+ });++ it('consecutive dates are exactly 10 minutes apart', () => {+ const dates = getDates(selectedDate, 'subdaily');+ for (let i = 1; i < dates.length; i += 1) {+ const diff = new Date(dates[i - 1]).getTime() - new Date(dates[i]).getTime();+ expect(diff).toBe(10 * 60 * 1000);+ }+ });++ it('first date is 30 minutes before selectedDate, rounded down to nearest 10 minutes', () => {+ const dates = getDates(new Date('2024-06-15T12:00:00Z'), 'subdaily');+ expect(dates[0]).toBe('2024-06-15T11:30:00Z');+ });++ it('rounds down an uneven minute correctly before subtracting 30 minutes', () => {+ const dates = getDates(new Date('2024-06-15T12:47:00Z'), 'subdaily');+ expect(dates[0]).toBe('2024-06-15T12:10:00Z');+ });+ });++ describe('period routing', () => {+ it('returns daily dates for period "daily"', () => {+ expect(getDates(selectedDate, 'daily')).toHaveLength(7);+ });++ it('returns subdaily dates for any period other than "daily"', () => {+ expect(getDates(selectedDate, 'subdaily')).toHaveLength(13);+ });++ it('returns subdaily dates when period is an empty string', () => {+ expect(getDates(selectedDate, '')).toHaveLength(13);+ });+ });+});++// ─── getOrbitalDatesBackwards ─────────────────────────────────────────────────++describe('getOrbitalDatesBackwards', () => {+ const selectedDate = new Date('2024-06-15T00:00:00Z');++ it('returns an array of 14 dates', () => {+ expect(getOrbitalDatesBackwards(selectedDate)).toHaveLength(14);+ });++ it('first date is the selected date', () => {+ expect(getOrbitalDatesBackwards(selectedDate)[0]).toBe('2024-06-15');+ });++ it('dates are in descending order', () => {+ const dates = getOrbitalDatesBackwards(selectedDate);+ for (let i = 1; i < dates.length; i += 1) {+ expect(new Date(dates[i]).getTime()).toBeLessThan(new Date(dates[i - 1]).getTime());+ }+ });++ it('last date is 13 days before the selected date', () => {+ const dates = getOrbitalDatesBackwards(selectedDate);+ expect(dates[13]).toBe('2024-06-02');+ });++ it('each consecutive date is 1 day earlier', () => {+ const dates = getOrbitalDatesBackwards(selectedDate);+ for (let i = 1; i < dates.length; i += 1) {+ const diff = new Date(dates[i - 1]).getTime() - new Date(dates[i]).getTime();+ expect(diff).toBe(24 * 60 * 60 * 1000);+ }+ });++ it('all dates match YYYY-MM-DD format', () => {+ getOrbitalDatesBackwards(selectedDate).forEach((d) => {+ expect(d).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });+ });++ it('wraps correctly across month boundaries', () => {+ const dates = getOrbitalDatesBackwards(new Date('2024-07-03T00:00:00Z'));+ expect(dates).toContain('2024-06-30');+ expect(dates).toContain('2024-06-29');+ });+});++// ─── getOrbitalDatesForwards ──────────────────────────────────────────────────++describe('getOrbitalDatesForwards', () => {+ const selectedDate = new Date('2024-06-01T00:00:00Z');+ const latestDate = '2024-06-15';++ it('first date is the selected date', () => {+ expect(getOrbitalDatesForwards(selectedDate, latestDate)[0]).toBe('2024-06-01');+ });++ it('does not exceed the latestDate', () => {+ const dates = getOrbitalDatesForwards(selectedDate, latestDate);+ dates.forEach((d) => {+ expect(new Date(d).getTime()).toBeLessThanOrEqual(new Date(latestDate).getTime());+ });+ });++ it('stops before the latestDate when latestDate is close', () => {+ // Use latestDate one day ahead so the boundary comparison is unambiguous+ const dates = getOrbitalDatesForwards(new Date('2024-06-14T00:00:00Z'), '2024-06-16');+ expect(dates).toContain('2024-06-14');+ expect(dates).toContain('2024-06-15');+ expect(dates).not.toContain('2024-06-17');+ });++ it('returns only the selected date when latestDate equals selectedDate', () => {+ const dates = getOrbitalDatesForwards(+ new Date('2024-06-15T00:00:00Z'),+ '2024-06-15',+ );+ expect(dates).toHaveLength(1);+ expect(dates[0]).toBe('2024-06-15');+ });++ it('returns up to 14 dates when latestDate is far in the future', () => {+ const dates = getOrbitalDatesForwards(selectedDate, '2030-01-01');+ expect(dates).toHaveLength(14);+ });++ it('dates are in ascending order', () => {+ const dates = getOrbitalDatesForwards(selectedDate, '2030-01-01');+ for (let i = 1; i < dates.length; i += 1) {+ expect(new Date(dates[i]).getTime()).toBeGreaterThan(new Date(dates[i - 1]).getTime());+ }+ });++ it('consecutive dates are 1 day apart', () => {+ const dates = getOrbitalDatesForwards(selectedDate, '2030-01-01');+ for (let i = 1; i < dates.length; i += 1) {+ const diff = new Date(dates[i]).getTime() - new Date(dates[i - 1]).getTime();+ expect(diff).toBe(24 * 60 * 60 * 1000);+ }+ });++ it('all dates match YYYY-MM-DD format', () => {+ getOrbitalDatesForwards(selectedDate, latestDate).forEach((d) => {+ expect(d).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });+ });+});++// ─── getOrbitalDatesForwardsAndBackwards ──────────────────────────────────────++describe('getOrbitalDatesForwardsAndBackwards', () => {+ const selectedDate = new Date('2024-06-15T00:00:00Z');+ const latestDate = '2030-01-01';++ it('returns a maximum of 14 dates', () => {+ expect(getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate)).toHaveLength(14);+ });++ it('first date is always the selected date', () => {+ expect(getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate)[0]).toBe('2024-06-15');+ });++ it('does not include dates beyond latestDate', () => {+ const dates = getOrbitalDatesForwardsAndBackwards(selectedDate, '2024-06-17');+ dates.forEach((d) => {+ expect(new Date(d).getTime()).toBeLessThanOrEqual(new Date('2024-06-17').getTime());+ });+ });++ it('includes both future and past dates', () => {+ const dates = getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate);+ const hasAfter = dates.some((d) => new Date(d) > new Date(selectedDate));+ const hasBefore = dates.some((d) => new Date(d) < new Date(selectedDate));+ expect(hasAfter).toBe(true);+ expect(hasBefore).toBe(true);+ });++ it('all dates match YYYY-MM-DD format', () => {+ getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate).forEach((d) => {+ expect(d).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });+ });++ it('does not contain duplicate dates', () => {+ const dates = getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate);+ expect(new Set(dates).size).toBe(dates.length);+ });++ it('falls back to only past dates when latestDate equals selectedDate', () => {+ const dates = getOrbitalDatesForwardsAndBackwards(+ new Date('2024-06-15T00:00:00Z'),+ '2024-06-15',+ );+ dates.forEach((d) => {+ expect(new Date(d).getTime()).toBeLessThanOrEqual(new Date('2024-06-15').getTime());+ });+ });++ it('trims result to exactly 14 when more would be generated', () => {+ const dates = getOrbitalDatesForwardsAndBackwards(selectedDate, latestDate);+ expect(dates.length).toBeLessThanOrEqual(14);+ });+});++// ─── getOrbitalDates ──────────────────────────────────────────────────────────++describe('getOrbitalDates', () => {+ // Must be Date objects — the functions call .toLocaleString() on the selectedDate arg+ const selectedDate = new Date('2024-06-15T00:00:00Z');+ const latestDate = '2030-01-01';++ it('calls getOrbitalDatesForwards when searchMethod is 1', () => {+ const result = getOrbitalDates(selectedDate, latestDate, 1);+ expect(result).toBeDefined();+ expect(result[0]).toBe('2024-06-15');+ expect(new Date(result[1]).getTime()).toBeGreaterThan(new Date(result[0]).getTime());+ });++ it('calls getOrbitalDatesBackwards when searchMethod is 2', () => {+ const result = getOrbitalDates(selectedDate, latestDate, 2);+ expect(result).toBeDefined();+ expect(result[0]).toBe('2024-06-15');+ expect(new Date(result[1]).getTime()).toBeLessThan(new Date(result[0]).getTime());+ });++ it('calls getOrbitalDatesForwardsAndBackwards when searchMethod is 3', () => {+ const result = getOrbitalDates(selectedDate, latestDate, 3);+ expect(result).toBeDefined();+ expect(result).toHaveLength(14);+ });++ it('returns undefined when searchMethod is 0', () => {+ expect(getOrbitalDates(selectedDate, latestDate, 0)).toBeUndefined();+ });++ it('returns undefined when searchMethod is an unrecognized value', () => {+ expect(getOrbitalDates(selectedDate, latestDate, 99)).toBeUndefined();+ });++ it('returns undefined when searchMethod is undefined', () => {+ expect(getOrbitalDates(selectedDate, latestDate, undefined)).toBeUndefined();+ });++ it('returns an array for searchMethod 1', () => {+ expect(Array.isArray(getOrbitalDates(selectedDate, latestDate, 1))).toBe(true);+ });++ it('returns an array for searchMethod 2', () => {+ expect(Array.isArray(getOrbitalDates(selectedDate, latestDate, 2))).toBe(true);+ });++ it('returns an array for searchMethod 3', () => {+ expect(Array.isArray(getOrbitalDates(selectedDate, latestDate, 3))).toBe(true);+ });++ it('returns 14 dates for searchMethod 2 (backwards)', () => {+ expect(getOrbitalDates(selectedDate, latestDate, 2)).toHaveLength(14);+ });++ it('returns up to 14 dates for searchMethod 1 (forwards) with far latestDate', () => {+ expect(getOrbitalDates(selectedDate, latestDate, 1)).toHaveLength(14);+ });});diff --git a/web/js/mapUI/components/kiosk/tile-measurement/utils/image-api-request.test.js b/web/js/mapUI/components/kiosk/tile-measurement/utils/image-api-request.test.jsindex 36ccd3df3..ae04cf62c 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/utils/image-api-request.test.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/utils/image-api-request.test.js@@ -1,3 +1,236 @@-test('image-api-request mapUI test', () => {+import axios from 'axios';+import { saveAs } from 'file-saver';+import fetchWMSImage from './image-api-request';+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/jpeg';++function buildAxiosResponse(overrides = {}) {+ return {+ data: mockResponseData,+ headers: { 'content-type': mockContentType },+ ...overrides,+ };+}++describe('fetchWMSImage', () => {+ 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();+ });++ // ── Return value ───────────────────────────────────────────────────────────++ describe('return value', () => {+ it('returns a blob object URL on success', async () => {+ const result = await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(result).toBe(mockObjectUrl);+ });++ it('returns null when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('Network error'));+ const result = await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(result).toBeNull();+ });+ });++ // ── axios.get call ────────────────────────────────────────────────────────++ describe('axios.get call', () => {+ it('calls axios.get with the correct base URL', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ 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, false);+ expect(axios.get).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ responseType: 'arraybuffer' }),+ );+ });++ it('calls axios.get exactly once', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(axios.get).toHaveBeenCalledTimes(1);+ });+ });++ // ── WMS params ─────────────────────────────────────────────────────────────++ describe('WMS params', () => {+ async function getParams() {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ 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/jpeg"', async () => {+ expect((await getParams()).format).toBe('image/jpeg');+ });++ 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('sets bbox from the extent when extent has no NaN', async () => {+ expect((await getParams()).bbox).toBe('-100,30,-80,50');+ });++ it('sets bbox to the full extent when extent contains NaN', async () => {+ await fetchWMSImage(mockLayer, mockDate, [NaN, 30, -80, 50], false);+ const params = axios.get.mock.calls[0][1].params;+ expect(params.bbox).toBe('-20037508.34,-20048966.1,20037508.34,20048966.1');+ });++ it('uses full extent bbox when any extent value is NaN', async () => {+ await fetchWMSImage(mockLayer, mockDate, [-100, NaN, NaN, NaN], false);+ const params = axios.get.mock.calls[0][1].params;+ expect(params.bbox).toBe('-20037508.34,-20048966.1,20037508.34,20048966.1');+ });++ it('builds bbox string as "x1,y1,x2,y2"', async () => {+ await fetchWMSImage(mockLayer, mockDate, [1, 2, 3, 4], false);+ const params = axios.get.mock.calls[0][1].params;+ expect(params.bbox).toBe('1,2,3,4');+ });+ });++ // ── Blob / URL.createObjectURL ─────────────────────────────────────────────++ describe('Blob and URL.createObjectURL', () => {+ it('calls URL.createObjectURL with a Blob', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ 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, false);+ const blob = URL.createObjectURL.mock.calls[0][0];+ expect(blob.type).toBe(mockContentType);+ });++ it('returns the result of URL.createObjectURL', async () => {+ global.URL.createObjectURL.mockReturnValue('blob:custom-url');+ const result = await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(result).toBe('blob:custom-url');+ });+ });++ // ── testMode ───────────────────────────────────────────────────────────────++ describe('testMode', () => {+ it('does NOT call saveAs when testMode is false', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(saveAs).not.toHaveBeenCalled();+ });++ it('calls saveAs when testMode is true', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, true);+ expect(saveAs).toHaveBeenCalledTimes(1);+ });++ it('calls saveAs with a Blob and the correct filename when testMode is true', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, true);+ const [blob, filename] = saveAs.mock.calls[0];+ expect(blob).toBeInstanceOf(Blob);+ expect(filename).toBe(`${mockLayer}.jpeg`);+ });++ it('calls saveAs with a Blob of type "image/jpeg" when testMode is true', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, true);+ const blob = saveAs.mock.calls[0][0];+ expect(blob.type).toBe('image/jpeg');+ });++ it('does NOT call saveAs when testMode is undefined', async () => {+ await fetchWMSImage(mockLayer, mockDate, mockExtent, undefined);+ expect(saveAs).not.toHaveBeenCalled();+ });+ });++ // ── error handling ─────────────────────────────────────────────────────────++ 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, false);+ expect(console.error).toHaveBeenCalledWith(mockError);+ });++ it('returns null when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('fail'));+ const result = await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(result).toBeNull();+ });++ it('does NOT call saveAs when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('fail'));+ await fetchWMSImage(mockLayer, mockDate, mockExtent, true);+ expect(saveAs).not.toHaveBeenCalled();+ });++ it('does NOT call URL.createObjectURL when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('fail'));+ await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(URL.createObjectURL).not.toHaveBeenCalled();+ });++ it('calls console.error exactly once when axios throws', async () => {+ axios.get.mockRejectedValue(new Error('fail'));+ await fetchWMSImage(mockLayer, mockDate, mockExtent, false);+ expect(console.error).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/web/js/mapUI/components/kiosk/tile-measurement/utils/layer-data-eic.test.js b/web/js/mapUI/components/kiosk/tile-measurement/utils/layer-data-eic.test.jsindex 6dae53b52..4917d8be1 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/utils/layer-data-eic.test.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/utils/layer-data-eic.test.js@@ -1,3 +1,446 @@-test('layer-data-eic mapUI test', () => {+import {+ layerPixelData,+ bestDates,+ layersToMeasure,+ travelModeData,+} from './layer-data-eic';+// ─── layerPixelData ───────────────────────────────────────────────────────────++describe('layerPixelData', () => {+ describe('structure', () => {+ it('is an object', () => {+ expect(typeof layerPixelData).toBe('object');+ expect(layerPixelData).not.toBeNull();+ });++ it('every entry has a numeric threshold property', () => {+ Object.values(layerPixelData).forEach(({ threshold }) => {+ expect(typeof threshold).toBe('number');+ });+ });++ it('every threshold is between 0 and 1 (inclusive)', () => {+ Object.values(layerPixelData).forEach(({ threshold }) => {+ expect(threshold).toBeGreaterThanOrEqual(0);+ expect(threshold).toBeLessThanOrEqual(1);+ });+ });++ it('every entry has exactly one key (threshold)', () => {+ Object.values(layerPixelData).forEach((entry) => {+ expect(Object.keys(entry)).toEqual(['threshold']);+ });+ });+ });++ describe('individual layer thresholds', () => {+ it('MODIS_Terra_CorrectedReflectance_TrueColor has threshold 0.70', () => {+ expect(layerPixelData.MODIS_Terra_CorrectedReflectance_TrueColor.threshold).toBe(0.70);+ });++ it('VIIRS_SNPP_DayNightBand_At_Sensor_Radiance has threshold 0.70', () => {+ expect(layerPixelData.VIIRS_SNPP_DayNightBand_At_Sensor_Radiance.threshold).toBe(0.70);+ });++ it('VIIRS_SNPP_CorrectedReflectance_TrueColor has threshold 0.65', () => {+ expect(layerPixelData.VIIRS_SNPP_CorrectedReflectance_TrueColor.threshold).toBe(0.65);+ });++ it('IMERG_Precipitation_Rate has threshold 0.95', () => {+ expect(layerPixelData.IMERG_Precipitation_Rate.threshold).toBe(0.95);+ });++ it('GHRSST_L4_MUR_Sea_Surface_Temperature has threshold 0.65', () => {+ expect(layerPixelData.GHRSST_L4_MUR_Sea_Surface_Temperature.threshold).toBe(0.65);+ });++ it('MODIS_Aqua_Land_Surface_Temp_Day has threshold 0.80', () => {+ expect(layerPixelData.MODIS_Aqua_Land_Surface_Temp_Day.threshold).toBe(0.80);+ });++ it('MODIS_Aqua_CorrectedReflectance_TrueColor has threshold 0.50', () => {+ expect(layerPixelData.MODIS_Aqua_CorrectedReflectance_TrueColor.threshold).toBe(0.50);+ });++ it('GOES-East_ABI_GeoColor has threshold 0.76', () => {+ expect(layerPixelData['GOES-East_ABI_GeoColor'].threshold).toBe(0.76);+ });++ it('GOES-West_ABI_GeoColor has threshold 0.76', () => {+ expect(layerPixelData['GOES-West_ABI_GeoColor'].threshold).toBe(0.76);+ });++ it('Himawari_AHI_Band3_Red_Visible_1km has threshold 0.76', () => {+ expect(layerPixelData.Himawari_AHI_Band3_Red_Visible_1km.threshold).toBe(0.76);+ });++ it('AMSRU2_Sea_Ice_Concentration_12km has threshold 0.85', () => {+ expect(layerPixelData.AMSRU2_Sea_Ice_Concentration_12km.threshold).toBe(0.85);+ });++ it('OMI_Nitrogen_Dioxide_Tropo_Column has threshold 0.50', () => {+ expect(layerPixelData.OMI_Nitrogen_Dioxide_Tropo_Column.threshold).toBe(0.50);+ });++ it('VIIRS_SNPP_AOD_Dark_Target_Land_Ocean has threshold 0.95', () => {+ expect(layerPixelData.VIIRS_SNPP_AOD_Dark_Target_Land_Ocean.threshold).toBe(0.95);+ });++ it('VIIRS_SNPP_AOT_Deep_Blue_Best_Estimate has threshold 0.95', () => {+ expect(layerPixelData.VIIRS_SNPP_AOT_Deep_Blue_Best_Estimate.threshold).toBe(0.95);+ });++ it('AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Night has threshold 0.20', () => {+ expect(+ layerPixelData.AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Night.threshold,+ ).toBe(0.20);+ });++ it('AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Day has threshold 0.20', () => {+ expect(+ layerPixelData.AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Day.threshold,+ ).toBe(0.20);+ });++ it('VIIRS_NOAA20_CorrectedReflectance_TrueColor has threshold 0.65', () => {+ expect(layerPixelData.VIIRS_NOAA20_CorrectedReflectance_TrueColor.threshold).toBe(0.65);+ });++ it('CERES_EBAF_TOA_Shortwave_Flux_All_Sky_Monthly has threshold 0.01', () => {+ expect(layerPixelData.CERES_EBAF_TOA_Shortwave_Flux_All_Sky_Monthly.threshold).toBe(0.01);+ });++ it('TEMPO_L3_NO2_Vertical_Column_Troposphere has threshold 0.99', () => {+ expect(layerPixelData.TEMPO_L3_NO2_Vertical_Column_Troposphere.threshold).toBe(0.99);+ });++ it('TEMPO_L3_Ozone_Column_Amount has threshold 0.99', () => {+ expect(layerPixelData.TEMPO_L3_Ozone_Column_Amount.threshold).toBe(0.99);+ });++ it('VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance has threshold 0.45', () => {+ expect(layerPixelData.VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance.threshold).toBe(0.45);+ });++ it('VIIRS_NOAA20_DayNightBand_AtSensor_M15 has threshold 0.10', () => {+ expect(layerPixelData.VIIRS_NOAA20_DayNightBand_AtSensor_M15.threshold).toBe(0.10);+ });++ it('VIIRS_NOAA20_AOT_Deep_Blue_Best_Estimate has threshold 0.90', () => {+ expect(layerPixelData.VIIRS_NOAA20_AOT_Deep_Blue_Best_Estimate.threshold).toBe(0.90);+ });++ it('VIIRS_NOAA20_AOD_Dark_Target_Land_Ocean has threshold 0.90', () => {+ expect(layerPixelData.VIIRS_NOAA20_AOD_Dark_Target_Land_Ocean.threshold).toBe(0.90);+ });++ it('VIIRS_NOAA21_CorrectedReflectance_TrueColor has threshold 0.65', () => {+ expect(layerPixelData.VIIRS_NOAA21_CorrectedReflectance_TrueColor.threshold).toBe(0.65);+ });++ it('VIIRS_SNPP_NDVI_8Day has threshold 0.90', () => {+ expect(layerPixelData.VIIRS_SNPP_NDVI_8Day.threshold).toBe(0.90);+ });+ });+});++// ─── bestDates ────────────────────────────────────────────────────────────────++describe('bestDates', () => {+ describe('structure', () => {+ it('is an object', () => {+ expect(typeof bestDates).toBe('object');+ expect(bestDates).not.toBeNull();+ });++ it('every entry has a date string property', () => {+ Object.values(bestDates).forEach(({ date }) => {+ expect(typeof date).toBe('string');+ });+ });++ it('every entry has exactly one key (date)', () => {+ Object.values(bestDates).forEach((entry) => {+ expect(Object.keys(entry)).toEqual(['date']);+ });+ });++ it('every date string is non-empty', () => {+ Object.values(bestDates).forEach(({ date }) => {+ expect(date.length).toBeGreaterThan(0);+ });+ });+ });++ describe('individual layer best dates', () => {+ it('GOES-East_ABI_GeoColor has date 2023-10-30T23:50:00.000Z', () => {+ expect(bestDates['GOES-East_ABI_GeoColor'].date).toBe('2023-10-30T23:50:00.000Z');+ });++ it('GOES-West_ABI_GeoColor has date 2023-10-30T23:50:00.000Z', () => {+ expect(bestDates['GOES-West_ABI_GeoColor'].date).toBe('2023-10-30T23:50:00.000Z');+ });++ it('Himawari_AHI_Band3_Red_Visible_1km has date 2023-10-30T23:50:00.000Z', () => {+ expect(bestDates.Himawari_AHI_Band3_Red_Visible_1km.date).toBe('2023-10-30T23:50:00.000Z');+ });++ it('MODIS_Terra_CorrectedReflectance_TrueColor has date 2023-10-29', () => {+ expect(bestDates.MODIS_Terra_CorrectedReflectance_TrueColor.date).toBe('2023-10-29');+ });++ it('VIIRS_SNPP_DayNightBand_At_Sensor_Radiance has date 2023-10-30', () => {+ expect(bestDates.VIIRS_SNPP_DayNightBand_At_Sensor_Radiance.date).toBe('2023-10-30');+ });++ it('VIIRS_SNPP_CorrectedReflectance_TrueColor has date 2023-10-30', () => {+ expect(bestDates.VIIRS_SNPP_CorrectedReflectance_TrueColor.date).toBe('2023-10-30');+ });++ it('IMERG_Precipitation_Rate has date 2023-10-30', () => {+ expect(bestDates.IMERG_Precipitation_Rate.date).toBe('2023-10-30');+ });++ it('GHRSST_L4_MUR_Sea_Surface_Temperature has date 2023-10-30', () => {+ expect(bestDates.GHRSST_L4_MUR_Sea_Surface_Temperature.date).toBe('2023-10-30');+ });++ it('MODIS_Aqua_Land_Surface_Temp_Day has date 2023-10-30', () => {+ expect(bestDates.MODIS_Aqua_Land_Surface_Temp_Day.date).toBe('2023-10-30');+ });++ it('MODIS_Aqua_CorrectedReflectance_TrueColor has date 2023-10-29', () => {+ expect(bestDates.MODIS_Aqua_CorrectedReflectance_TrueColor.date).toBe('2023-10-29');+ });++ it('OMI_Nitrogen_Dioxide_Tropo_Column has date 2023-10-27', () => {+ expect(bestDates.OMI_Nitrogen_Dioxide_Tropo_Column.date).toBe('2023-10-27');+ });++ it('VIIRS_SNPP_AOD_Dark_Target_Land_Ocean has date 2023-10-29', () => {+ expect(bestDates.VIIRS_SNPP_AOD_Dark_Target_Land_Ocean.date).toBe('2023-10-29');+ });++ it('VIIRS_SNPP_AOT_Deep_Blue_Best_Estimate has date 2023-10-30', () => {+ expect(bestDates.VIIRS_SNPP_AOT_Deep_Blue_Best_Estimate.date).toBe('2023-10-30');+ });++ it('AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Night has date 2023-10-17', () => {+ expect(bestDates.AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Night.date).toBe('2023-10-17');+ });++ it('AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Day has date 2023-10-17', () => {+ expect(bestDates.AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Day.date).toBe('2023-10-17');+ });++ it('VIIRS_NOAA20_CorrectedReflectance_TrueColor has date 2023-10-30', () => {+ expect(bestDates.VIIRS_NOAA20_CorrectedReflectance_TrueColor.date).toBe('2023-10-30');+ });++ it('CERES_EBAF_TOA_Shortwave_Flux_All_Sky_Monthly has date 2023-10-30', () => {+ expect(bestDates.CERES_EBAF_TOA_Shortwave_Flux_All_Sky_Monthly.date).toBe('2023-10-30');+ });++ it('TEMPO_L3_NO2_Vertical_Column_Troposphere has date 2024-06-03T17:00:00.000Z', () => {+ expect(bestDates.TEMPO_L3_NO2_Vertical_Column_Troposphere.date).toBe('2024-06-03T17:00:00.000Z');+ });++ it('TEMPO_L3_Ozone_Column_Amount has date 2024-06-03T17:00:00.000Z', () => {+ expect(bestDates.TEMPO_L3_Ozone_Column_Amount.date).toBe('2024-06-03T17:00:00.000Z');+ });++ it('VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance has date 2024-10-01', () => {+ expect(bestDates.VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance.date).toBe('2024-10-01');+ });++ it('VIIRS_NOAA20_DayNightBand_AtSensor_M15 has date 2024-10-01', () => {+ expect(bestDates.VIIRS_NOAA20_DayNightBand_AtSensor_M15.date).toBe('2024-10-01');+ });++ it('VIIRS_NOAA20_AOT_Deep_Blue_Best_Estimate has date 2024-10-01', () => {+ expect(bestDates.VIIRS_NOAA20_AOT_Deep_Blue_Best_Estimate.date).toBe('2024-10-01');+ });++ it('VIIRS_NOAA20_AOD_Dark_Target_Land_Ocean has date 2024-10-01', () => {+ expect(bestDates.VIIRS_NOAA20_AOD_Dark_Target_Land_Ocean.date).toBe('2024-10-01');+ });++ it('VIIRS_NOAA21_CorrectedReflectance_TrueColor has date 2024-10-01', () => {+ expect(bestDates.VIIRS_NOAA21_CorrectedReflectance_TrueColor.date).toBe('2024-10-01');+ });++ it('VIIRS_SNPP_NDVI_8Day has date 2025-08-24', () => {+ expect(bestDates.VIIRS_SNPP_NDVI_8Day.date).toBe('2025-08-24');+ });+ });+});++// ─── layersToMeasure ──────────────────────────────────────────────────────────++describe('layersToMeasure', () => {+ it('is an array', () => {+ expect(Array.isArray(layersToMeasure)).toBe(true);+ });++ it('has 26 entries', () => {+ expect(layersToMeasure).toHaveLength(26);+ });++ it('contains only strings', () => {+ layersToMeasure.forEach((layer) => {+ expect(typeof layer).toBe('string');+ });+ });++ it('has no duplicate entries', () => {+ expect(new Set(layersToMeasure).size).toBe(layersToMeasure.length);+ });++ it('contains MODIS_Terra_CorrectedReflectance_TrueColor', () => {+ expect(layersToMeasure).toContain('MODIS_Terra_CorrectedReflectance_TrueColor');+ });++ it('contains GOES-East_ABI_GeoColor', () => {+ expect(layersToMeasure).toContain('GOES-East_ABI_GeoColor');+ });++ it('contains GOES-West_ABI_GeoColor', () => {+ expect(layersToMeasure).toContain('GOES-West_ABI_GeoColor');+ });++ it('contains VIIRS_SNPP_NDVI_8Day', () => {+ expect(layersToMeasure).toContain('VIIRS_SNPP_NDVI_8Day');+ });++ it('contains TEMPO_L3_NO2_Vertical_Column_Troposphere', () => {+ expect(layersToMeasure).toContain('TEMPO_L3_NO2_Vertical_Column_Troposphere');+ });++ it('contains TEMPO_L3_Ozone_Column_Amount', () => {+ expect(layersToMeasure).toContain('TEMPO_L3_Ozone_Column_Amount');+ });++ it('every layer in layersToMeasure has a corresponding entry in layerPixelData', () => {+ layersToMeasure.forEach((layer) => {+ expect(layerPixelData).toHaveProperty(layer);+ });+ });+});++// ─── travelModeData ───────────────────────────────────────────────────────────++describe('travelModeData', () => {+ describe('structure', () => {+ it('is an object', () => {+ expect(typeof travelModeData).toBe('object');+ expect(travelModeData).not.toBeNull();+ });++ it('has 20 entries', () => {+ expect(Object.keys(travelModeData)).toHaveLength(20);+ });++ it('keys are numeric (1 through 20)', () => {+ const keys = Object.keys(travelModeData).map(Number);+ for (let i = 1; i <= 20; i += 1) {+ expect(keys).toContain(i);+ }+ });++ it('every entry has a title string', () => {+ Object.values(travelModeData).forEach(({ title }) => {+ expect(typeof title).toBe('string');+ expect(title.length).toBeGreaterThan(0);+ });+ });++ it('every entry has exactly one key (title)', () => {+ Object.values(travelModeData).forEach((entry) => {+ expect(Object.keys(entry)).toEqual(['title']);+ });+ });+ });++ describe('individual travel mode titles', () => {+ it('mode 1 is "True Color Imagery from Terra satellite"', () => {+ expect(travelModeData[1].title).toBe('True Color Imagery from Terra satellite');+ });++ it('mode 2 is "Geostationary imagery from NOAA and JAXA satellites"', () => {+ expect(travelModeData[2].title).toBe('Geostationary imagery from NOAA and JAXA satellites');+ });++ it('mode 3 is "Active fires detected by Suomi NPP satellite"', () => {+ expect(travelModeData[3].title).toBe('Active fires detected by Suomi NPP satellite');+ });++ it('mode 4 is "Black Marble Night Time Imaging from Suomi NPP satellite"', () => {+ expect(travelModeData[4].title).toBe('Black Marble Night Time Imaging from Suomi NPP satellite');+ });++ it('mode 5 is "Rain and Snow"', () => {+ expect(travelModeData[5].title).toBe('Rain and Snow');+ });++ it('mode 6 is "Sea Surface Temperature"', () => {+ expect(travelModeData[6].title).toBe('Sea Surface Temperature');+ });++ it('mode 7 is "Land Surface Temperature"', () => {+ expect(travelModeData[7].title).toBe('Land Surface Temperature');+ });++ it('mode 8 is "Arctic Sea Ice"', () => {+ expect(travelModeData[8].title).toBe('Arctic Sea Ice');+ });++ it('mode 9 is "Antarctic Sea Ice"', () => {+ expect(travelModeData[9].title).toBe('Antarctic Sea Ice');+ });++ it('mode 10 is "Active fires detected by NOAA-20 satellite"', () => {+ expect(travelModeData[10].title).toBe('Active fires detected by NOAA-20 satellite');+ });++ it('mode 11 is "Nitrogen Dioxide (NO2) by Aura satellite"', () => {+ expect(travelModeData[11].title).toBe('Nitrogen Dioxide (NO2) by Aura satellite');+ });++ it('mode 12 is "Carbon Monoxide (CO) by Aqua satellite"', () => {+ expect(travelModeData[12].title).toBe('Carbon Monoxide (CO) by Aqua satellite');+ });++ it('mode 13 is "Aerosol Optical Depth (AOD) by Suomi NPP satellite"', () => {+ expect(travelModeData[13].title).toBe('Aerosol Optical Depth (AOD) by Suomi NPP satellite');+ });++ it('mode 14 is "Nitrogen Dioxide Vertical Column Troposphere (L3) by TEMPO satellite"', () => {+ expect(travelModeData[14].title).toBe('Nitrogen Dioxide Vertical Column Troposphere (L3) by TEMPO satellite');+ });++ it('mode 15 is "Ozone Column Amount (L3) by TEMPO satellite"', () => {+ expect(travelModeData[15].title).toBe('Ozone Column Amount (L3) by TEMPO satellite');+ });++ it('mode 16 is "Black Marble Nighttime At Sensor Radiance from NOAA-20 satellite"', () => {+ expect(travelModeData[16].title).toBe('Black Marble Nighttime At Sensor Radiance from NOAA-20 satellite');+ });++ it('mode 17 is "Black Marble Nighttime Blue/Yellow Composite from NOAA-20 satellite"', () => {+ expect(travelModeData[17].title).toBe('Black Marble Nighttime Blue/Yellow Composite from NOAA-20 satellite');+ });++ it('mode 18 is "Aerosol Optical Depth (AOD) by NOAA-20 satellite"', () => {+ expect(travelModeData[18].title).toBe('Aerosol Optical Depth (AOD) by NOAA-20 satellite');+ });++ it('mode 19 is "Active Fires detected by NOAA-21 satellite"', () => {+ expect(travelModeData[19].title).toBe('Active Fires detected by NOAA-21 satellite');+ });++ it('mode 20 is "Vegetation Index (NDVI) by Suomi NPP satellite"', () => {+ expect(travelModeData[20].title).toBe('Vegetation Index (NDVI) by Suomi NPP satellite');+ });+ });});diff --git a/web/js/mapUI/components/kiosk/tile-measurement/utils/verify-map-tiles.test.js b/web/js/mapUI/components/kiosk/tile-measurement/utils/verify-map-tiles.test.jsindex 9d1b3f98f..ba2c3a959 100644--- a/web/js/mapUI/components/kiosk/tile-measurement/utils/verify-map-tiles.test.js+++ b/web/js/mapUI/components/kiosk/tile-measurement/utils/verify-map-tiles.test.js@@ -1,3 +1,571 @@-test('verify-map-tiles mapUI test', () => {+import countTilesForSpecifiedLayers from './verify-map-tiles';+import TileLayer from 'ol/layer/Tile';+jest.mock('ol/layer/Tile');+jest.mock('ol/proj', () => ({+ transformExtent: jest.fn((extent) => extent),+}));++import { transformExtent } from 'ol/proj';++// ─── Canvas mock setup ────────────────────────────────────────────────────────++function buildMockContext(pixelData) {+ return {+ drawImage: jest.fn(),+ getImageData: jest.fn(() => ({ data: pixelData })),+ };+}++function buildMockCanvas(ctx) {+ return {+ getContext: jest.fn(() => ctx),+ width: 0,+ height: 0,+ };+}++// ─── Tile / TileGrid / Source / Layer factories ───────────────────────────────++function buildMockTile(state, imageOverride) {+ const defaultImage = { complete: true, naturalWidth: 1, width: 2, height: 2 };+ return {+ getState: jest.fn(() => state),+ image_: imageOverride ?? defaultImage,+ };+}++function buildMockTileGrid(tiles = []) {+ return {+ getZForResolution: jest.fn(() => 5),+ forEachTileCoord: jest.fn((extent, z, cb) => {+ tiles.forEach((tile, i) => cb([z, i, 0]));+ }),+ };+}++function buildMockSource(tiles = [], projectionOverride = null) {+ const tileGrid = buildMockTileGrid(tiles);+ const tileMap = {};+ tiles.forEach((tile, i) => { tileMap[i] = tile; });++ return {+ getProjection: jest.fn(() => projectionOverride),+ getTileGridForProjection: jest.fn(() => tileGrid),+ getTile: jest.fn((z, x) => tileMap[x] ?? tiles[x]),+ };+}++function buildMockTileLayer(source, id = 'test-layer-id') {+ const layer = new TileLayer();+ layer.getSource = jest.fn(() => source);+ layer.wv = { id };+ return layer;+}++function buildMockView(projectionCode = 'EPSG:4326') {+ const projection = { getCode: jest.fn(() => projectionCode) };+ return {+ calculateExtent: jest.fn(() => [-180, -90, 180, 90]),+ getZoom: jest.fn(() => 5),+ getProjection: jest.fn(() => projection),+ getResolutionForZoom: jest.fn(() => 0.5),+ };+}++function buildMockMap(layers = [], viewOverride) {+ const view = viewOverride ?? buildMockView();+ return {+ getView: jest.fn(() => view),+ getSize: jest.fn(() => [800, 600]),+ getLayers: jest.fn(() => ({+ getArray: jest.fn(() => layers),+ })),+ };+}++function buildUi(map) {+ return { selected: map };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('countTilesForSpecifiedLayers', () => {+ let mockCtx;+ let mockCanvas;++ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'log').mockImplementation(() => {});+ jest.spyOn(console, 'error').mockImplementation(() => {});++ // Default: multi-color (valid) image — 2×2 with 4 different colored pixels+ mockCtx = buildMockContext(new Uint8ClampedArray([+ 255, 0, 0, 255,+ 0, 255, 0, 255,+ 0, 0, 255, 255,+ 255, 255, 0, 255,+ ]));+ mockCanvas = buildMockCanvas(mockCtx);+ jest.spyOn(document, 'createElement').mockImplementation((tag) => {+ if (tag === 'canvas') return mockCanvas;+ return {};+ });++ // Make TileLayer instances recognizable via instanceof+ TileLayer.mockImplementation(function MockTileLayer() {});+ });++ afterEach(() => {+ console.log.mockRestore();+ console.error.mockRestore();+ document.createElement.mockRestore();+ });++ // ── Return shape ───────────────────────────────────────────────────────────++ describe('return shape', () => {+ it('returns an object with all six expected keys', async () => {+ const map = buildMockMap([]);+ const result = countTilesForSpecifiedLayers(buildUi(map), []);+ await Promise.resolve();+ expect(result).toHaveProperty('totalExpectedTileCount');+ expect(result).toHaveProperty('totalLoadedTileCount');+ expect(result).toHaveProperty('totalTilesLoadedWithBadImage');+ expect(result).toHaveProperty('totalErrorTiles');+ expect(result).toHaveProperty('totalEmptyTiles');+ expect(result).toHaveProperty('totalOtherTileStates');+ });++ it('returns all zeros when there are no matching layers', async () => {+ const map = buildMockMap([]);+ const result = countTilesForSpecifiedLayers(buildUi(map), ['some-layer']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(0);+ expect(result.totalLoadedTileCount).toBe(0);+ expect(result.totalTilesLoadedWithBadImage).toBe(0);+ expect(result.totalErrorTiles).toBe(0);+ expect(result.totalEmptyTiles).toBe(0);+ expect(result.totalOtherTileStates).toEqual([]);+ });+ });++ // ── Layer filtering ────────────────────────────────────────────────────────++ describe('layer filtering', () => {+ it('only processes layers whose wv.id is in layersToCheck', async () => {+ const tileA = buildMockTile(4);+ const tileB = buildMockTile(4);+ const sourceA = buildMockSource([tileA]);+ const sourceB = buildMockSource([tileB]);+ const layerA = buildMockTileLayer(sourceA, 'layer-a');+ const layerB = buildMockTileLayer(sourceB, 'layer-b');+ const map = buildMockMap([layerA, layerB]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(1);+ });++ it('processes multiple matching layers', async () => {+ const tileA = buildMockTile(4);+ const tileB = buildMockTile(4);+ const sourceA = buildMockSource([tileA]);+ const sourceB = buildMockSource([tileB]);+ const layerA = buildMockTileLayer(sourceA, 'layer-a');+ const layerB = buildMockTileLayer(sourceB, 'layer-b');+ const map = buildMockMap([layerA, layerB]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a', 'layer-b']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(2);+ });++ it('excludes layers without a wv property', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ delete layer.wv;+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(0);+ });++ it('excludes layers with wv but no id', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ layer.wv = {};+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(0);+ });++ it('returns all zeros when layersToCheck is empty', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), []);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(0);+ });+ });++ // ── LayerGroup (getLayers) ─────────────────────────────────────────────────++ describe('LayerGroup processing', () => {+ it('recurses into LayerGroup sub-layers', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const subLayer = buildMockTileLayer(source, 'layer-a');++ const layerGroup = {+ wv: { id: 'layer-a' },+ getLayers: jest.fn(() => ({ getArray: jest.fn(() => [subLayer]) })),+ };+ const map = buildMockMap([layerGroup]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(1);+ });++ it('recurses into nested LayerGroups', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const subLayer = buildMockTileLayer(source, 'layer-a');++ const innerGroup = {+ wv: { id: 'inner' },+ getLayers: jest.fn(() => ({ getArray: jest.fn(() => [subLayer]) })),+ };+ const outerGroup = {+ wv: { id: 'layer-a' },+ getLayers: jest.fn(() => ({ getArray: jest.fn(() => [innerGroup]) })),+ };+ const map = buildMockMap([outerGroup]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(1);+ });++ it('calls console.error for layers that are neither TileLayer nor LayerGroup', async () => {+ const unknownLayer = { wv: { id: 'layer-a' } };+ const map = buildMockMap([unknownLayer]);++ countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(console.error).toHaveBeenCalledWith(+ 'Layer is not an instance of a TileLayer or LayerGroup',+ );+ });+ });++ // ── Tile state counting ────────────────────────────────────────────────────++ describe('tile state counting', () => {+ it('increments totalExpectedTileCount for every tile', async () => {+ const tiles = [buildMockTile(0), buildMockTile(0), buildMockTile(0)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(3);+ });++ it('counts state 3 tiles as errorTiles', async () => {+ const tiles = [buildMockTile(3), buildMockTile(3)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalErrorTiles).toBe(2);+ });++ it('counts state 4 tiles as emptyTiles', async () => {+ const tiles = [buildMockTile(4), buildMockTile(4), buildMockTile(4)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalEmptyTiles).toBe(3);+ });++ it('pushes state 0 (IDLE) into totalOtherTileStates', async () => {+ const tiles = [buildMockTile(0)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalOtherTileStates).toContain(0);+ });++ it('pushes state 1 (LOADING) into totalOtherTileStates', async () => {+ const tiles = [buildMockTile(1)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalOtherTileStates).toContain(1);+ });++ it('pushes state 5 (ABORT) into totalOtherTileStates', async () => {+ const tiles = [buildMockTile(5)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalOtherTileStates).toContain(5);+ });++ it('accumulates otherTileStates from multiple tiles', async () => {+ const tiles = [buildMockTile(0), buildMockTile(1), buildMockTile(5)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalOtherTileStates).toEqual([0, 1, 5]);+ });+ });++ // ── Tile state 2 (LOADED) and checkTileImage ───────────────────────────────++ describe('tile state 2 (LOADED) and checkTileImage', () => {+ it('increments totalLoadedTileCount when state is 2 and image is invalid (multi-color)', async () => {+ // Multi-color pixel data — checkTileImage returns false (not single color, not transparent)+ mockCtx.getImageData.mockReturnValue({+ data: new Uint8ClampedArray([+ 255, 0, 0, 255,+ 0, 255, 0, 255,+ ]),+ });+ const tile = buildMockTile(2);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalLoadedTileCount).toBe(1);+ expect(result.totalTilesLoadedWithBadImage).toBe(0);+ });++ it('increments totalTilesLoadedWithBadImage when state is 2 and image is single-color', async () => {+ // Single-color pixel data — checkTileImage returns true+ mockCtx.getImageData.mockReturnValue({+ data: new Uint8ClampedArray([+ 255, 0, 0, 255,+ 255, 0, 0, 255,+ ]),+ });+ const tile = buildMockTile(2);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalTilesLoadedWithBadImage).toBe(1);+ expect(result.totalLoadedTileCount).toBe(0);+ });++ it('increments totalTilesLoadedWithBadImage when state is 2 and image is fully transparent', async () => {+ // All-transparent pixel data — checkTileImage returns true+ mockCtx.getImageData.mockReturnValue({+ data: new Uint8ClampedArray([+ 0, 0, 0, 0,+ 0, 0, 0, 0,+ ]),+ });+ const tile = buildMockTile(2);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalTilesLoadedWithBadImage).toBe(1);+ });++ it('counts loaded tile with invalid image (image.complete is false) as totalLoadedTileCount', async () => {+ const tile = buildMockTile(2, { complete: false, naturalWidth: 0, width: 2, height: 2 });+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalLoadedTileCount).toBe(1);+ expect(result.totalTilesLoadedWithBadImage).toBe(0);+ });++ it('counts loaded tile with naturalWidth 0 as totalLoadedTileCount', async () => {+ const tile = buildMockTile(2, { complete: true, naturalWidth: 0, width: 2, height: 2 });+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalLoadedTileCount).toBe(1);+ expect(result.totalTilesLoadedWithBadImage).toBe(0);+ });++ it('calls console.log("Image invalid.") when image is not complete', async () => {+ const tile = buildMockTile(2, { complete: false, naturalWidth: 0, width: 2, height: 2 });+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(console.log).toHaveBeenCalledWith('Image invalid.');+ });+ });++ // ── processTileLayer internals ─────────────────────────────────────────────++ describe('processTileLayer internals', () => {+ it('calls transformExtent with the view extent and projections', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const view = buildMockView();+ const map = buildMockMap([layer], view);++ countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(transformExtent).toHaveBeenCalledWith(+ [-180, -90, 180, 90],+ view.getProjection(),+ view.getProjection(),+ );+ });++ it('uses source.getProjection() when it returns a value', async () => {+ const mockSourceProj = { getCode: jest.fn(() => 'EPSG:3857') };+ const tile = buildMockTile(4);+ const source = buildMockSource([tile], mockSourceProj);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(source.getTileGridForProjection).toHaveBeenCalledWith(mockSourceProj);+ });++ it('falls back to view.getProjection() when source.getProjection() returns null', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile], null);+ const layer = buildMockTileLayer(source, 'layer-a');+ const view = buildMockView();+ const map = buildMockMap([layer], view);++ countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(source.getTileGridForProjection).toHaveBeenCalledWith(view.getProjection());+ });++ it('calls source.getTile with correct tileCoord arguments', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(source.getTile).toHaveBeenCalledWith(5, 0, 0, 1, expect.anything());+ });++ it('calls tileGrid.getZForResolution with the view resolution', async () => {+ const tile = buildMockTile(4);+ const source = buildMockSource([tile]);+ const layer = buildMockTileLayer(source, 'layer-a');+ const view = buildMockView();+ const map = buildMockMap([layer], view);++ countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ const tileGrid = source.getTileGridForProjection();+ expect(tileGrid.getZForResolution).toHaveBeenCalledWith(0.5);+ });+ });++ // ── Aggregation across multiple layers ────────────────────────────────────++ describe('aggregation across multiple layers', () => {+ it('sums totalErrorTiles across multiple layers', async () => {+ const tilesA = [buildMockTile(3)];+ const tilesB = [buildMockTile(3), buildMockTile(3)];+ const sourceA = buildMockSource(tilesA);+ const sourceB = buildMockSource(tilesB);+ const layerA = buildMockTileLayer(sourceA, 'layer-a');+ const layerB = buildMockTileLayer(sourceB, 'layer-b');+ const map = buildMockMap([layerA, layerB]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a', 'layer-b']);+ await Promise.resolve();+ expect(result.totalErrorTiles).toBe(3);+ });++ it('sums totalEmptyTiles across multiple layers', async () => {+ const tilesA = [buildMockTile(4), buildMockTile(4)];+ const tilesB = [buildMockTile(4)];+ const sourceA = buildMockSource(tilesA);+ const sourceB = buildMockSource(tilesB);+ const layerA = buildMockTileLayer(sourceA, 'layer-a');+ const layerB = buildMockTileLayer(sourceB, 'layer-b');+ const map = buildMockMap([layerA, layerB]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a', 'layer-b']);+ await Promise.resolve();+ expect(result.totalEmptyTiles).toBe(3);+ });++ it('concatenates totalOtherTileStates across multiple layers', async () => {+ const tilesA = [buildMockTile(0)];+ const tilesB = [buildMockTile(1)];+ const sourceA = buildMockSource(tilesA);+ const sourceB = buildMockSource(tilesB);+ const layerA = buildMockTileLayer(sourceA, 'layer-a');+ const layerB = buildMockTileLayer(sourceB, 'layer-b');+ const map = buildMockMap([layerA, layerB]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a', 'layer-b']);+ await Promise.resolve();+ expect(result.totalOtherTileStates).toEqual([0, 1]);+ });++ it('sums totalExpectedTileCount across mixed tile states', async () => {+ const tiles = [buildMockTile(2), buildMockTile(3), buildMockTile(4), buildMockTile(0)];+ const source = buildMockSource(tiles);+ const layer = buildMockTileLayer(source, 'layer-a');+ const map = buildMockMap([layer]);++ const result = countTilesForSpecifiedLayers(buildUi(map), ['layer-a']);+ await Promise.resolve();+ expect(result.totalExpectedTileCount).toBe(4);+ });+ });});diff --git a/web/js/mapUI/components/kiosk/travel-mode/travelMode.test.js b/web/js/mapUI/components/kiosk/travel-mode/travelMode.test.jsindex bfdc4bd6b..0bc6de1f5 100644--- a/web/js/mapUI/components/kiosk/travel-mode/travelMode.test.js+++ b/web/js/mapUI/components/kiosk/travel-mode/travelMode.test.js@@ -1,3 +1,61 @@-test('travelMode mapUI test', () => {+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';+import TravelMode from './travelMode';+jest.mock('./travelModeTitle', () => () => <div data-testid="travel-mode-title" />);+jest.mock('./travelModeColorbars', () => () => <div data-testid="travel-mode-colorbars" />);++function renderComponent() {+ return render(<TravelMode />);+}++describe('TravelMode', () => {+ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent()).not.toThrow();+ });++ it('renders the outer wrapper with id "travel-mode"', () => {+ const { container } = renderComponent();+ expect(container.querySelector('#travel-mode')).toBeInTheDocument();+ });++ it('renders TravelModeTitle', () => {+ renderComponent();+ expect(screen.getByTestId('travel-mode-title')).toBeInTheDocument();+ });++ it('renders TravelModeColorbars', () => {+ renderComponent();+ expect(screen.getByTestId('travel-mode-colorbars')).toBeInTheDocument();+ });++ it('renders exactly two children inside the wrapper', () => {+ const { container } = renderComponent();+ expect(container.querySelector('#travel-mode').children).toHaveLength(2);+ });+ });++ describe('Child component order', () => {+ it('renders TravelModeTitle before TravelModeColorbars', () => {+ const { container } = renderComponent();+ const children = Array.from(container.querySelector('#travel-mode').children);+ const titleIdx = children.findIndex((el) => el.dataset.testid === 'travel-mode-title');+ const colorbarsIdx = children.findIndex((el) => el.dataset.testid === 'travel-mode-colorbars');+ expect(titleIdx).toBeLessThan(colorbarsIdx);+ });++ it('renders TravelModeTitle as the first child', () => {+ const { container } = renderComponent();+ const firstChild = container.querySelector('#travel-mode').children[0];+ expect(firstChild).toHaveAttribute('data-testid', 'travel-mode-title');+ });++ it('renders TravelModeColorbars as the last child', () => {+ const { container } = renderComponent();+ const wrapper = container.querySelector('#travel-mode');+ const lastChild = wrapper.children[wrapper.children.length - 1];+ expect(lastChild).toHaveAttribute('data-testid', 'travel-mode-colorbars');+ });+ });});diff --git a/web/js/mapUI/components/kiosk/travel-mode/travelModeColorbars.test.js b/web/js/mapUI/components/kiosk/travel-mode/travelModeColorbars.test.jsindex 248b9beb7..7cebbc4df 100644--- a/web/js/mapUI/components/kiosk/travel-mode/travelModeColorbars.test.js+++ b/web/js/mapUI/components/kiosk/travel-mode/travelModeColorbars.test.js@@ -1,3 +1,368 @@-test('travelModeColorbars mapUI test', () => {+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import TravelModeColorbars from './travelModeColorbars';+jest.mock('../../../../modules/palettes/util', () => ({+ drawTravelModePaletteOnCanvas: jest.fn(),+}));++import { drawTravelModePaletteOnCanvas } from '../../../../modules/palettes/util';++const mockStore = configureMockStore();++// ─── Legend / palette builders ────────────────────────────────────────────────++function buildLegend(overrides = {}) {+ return {+ id: 'legend-1',+ type: 'continuous',+ title: 'Sea Surface Temperature',+ minLabel: '0',+ maxLabel: '30',+ units: '°C',+ colors: ['#ff0000', '#00ff00'],+ ...overrides,+ };+}++function buildLayer(id, legends = [buildLegend()]) {+ return {+ id,+ maps: legends.map((legend) => ({ legend })),+ };+}++function buildStore({ active = {}, rendered = {} } = {}) {+ return mockStore({+ palettes: { active, rendered },+ });+}++function renderComponent(store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <TravelModeColorbars />+ </Provider>,+ );+ return { ...utils, store: s };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('TravelModeColorbars', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ // ── TravelModeColorbars: null / empty states ───────────────────────────────++ describe('TravelModeColorbars: null / empty states', () => {+ it('renders null when both active and rendered palettes are empty', () => {+ const { container } = renderComponent(buildStore({ active: {}, rendered: {} }));+ expect(container.firstChild).toBeNull();+ });++ it('renders null when palettes is null', () => {+ const { container } = renderComponent(buildStore({ active: {}, rendered: null }));+ expect(container.firstChild).toBeNull();+ });++ it('renders null when all maps contain only classification legends', () => {+ const classificationLegend = buildLegend({ type: 'classification' });+ const layer = buildLayer('layer-1', [classificationLegend]);+ const { container } = renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': layer },+ }));+ expect(container.firstChild).toBeNull();+ });++ it('renders null when filteredPalettes has no maps after filtering', () => {+ const layer = buildLayer('layer-1', [buildLegend({ type: 'classification' })]);+ const { container } = renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': layer },+ }));+ expect(container.firstChild).toBeNull();+ });+ });++ // ── TravelModeColorbars: palette source selection ─────────────────────────++ describe('TravelModeColorbars: palette source selection', () => {+ it('uses renderedPalettes when activePalettes is empty', () => {+ const layer = buildLayer('layer-1');+ renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': layer },+ }));+ expect(screen.getByText('Sea Surface Temperature')).toBeInTheDocument();+ });++ it('uses activePalettes when activePalettes has entries', () => {+ const activeLayer = buildLayer('layer-active', [buildLegend({ title: 'Active Layer Title' })]);+ const renderedLayer = buildLayer('layer-rendered', [buildLegend({ title: 'Rendered Layer Title' })]);+ renderComponent(buildStore({+ active: { 'layer-active': activeLayer },+ rendered: { 'layer-rendered': renderedLayer },+ }));+ expect(screen.getByText('Active Layer Title')).toBeInTheDocument();+ expect(screen.queryByText('Rendered Layer Title')).not.toBeInTheDocument();+ });++ it('falls back to renderedPalettes when activePalettes is empty object', () => {+ const renderedLayer = buildLayer('layer-1', [buildLegend({ title: 'Rendered Title' })]);+ renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': renderedLayer },+ }));+ expect(screen.getByText('Rendered Title')).toBeInTheDocument();+ });+ });++ // ── TravelModeColorbars: container rendering ──────────────────────────────++ describe('TravelModeColorbars: container rendering', () => {+ it('renders the container with id "travel-mode-colorbar-container"', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': layer },+ }));+ expect(container.querySelector('#travel-mode-colorbar-container')).toBeInTheDocument();+ });++ it('renders one ColorBarRow per non-classification legend', () => {+ const layer = buildLayer('layer-1', [+ buildLegend({ id: 'legend-1', title: 'Temp' }),+ buildLegend({ id: 'legend-2', title: 'Pressure' }),+ ]);+ renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': layer },+ }));+ expect(screen.getAllByText(/travel-mode-colorbar-row|Temp|Pressure/i)).toBeTruthy();+ expect(screen.getByText('Temp')).toBeInTheDocument();+ expect(screen.getByText('Pressure')).toBeInTheDocument();+ });++ it('renders ColorBarRows for multiple layers', () => {+ const layer1 = buildLayer('layer-1', [buildLegend({ id: 'leg-1', title: 'Layer One' })]);+ const layer2 = buildLayer('layer-2', [buildLegend({ id: 'leg-2', title: 'Layer Two' })]);+ renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': layer1, 'layer-2': layer2 },+ }));+ expect(screen.getByText('Layer One')).toBeInTheDocument();+ expect(screen.getByText('Layer Two')).toBeInTheDocument();+ });++ it('skips classification legends but renders non-classification ones in the same layer', () => {+ const layer = buildLayer('layer-1', [+ buildLegend({ id: 'leg-class', type: 'classification', title: 'Classification' }),+ buildLegend({ id: 'leg-cont', type: 'continuous', title: 'Continuous' }),+ ]);+ renderComponent(buildStore({+ active: {},+ rendered: { 'layer-1': layer },+ }));+ expect(screen.queryByText('Classification')).not.toBeInTheDocument();+ expect(screen.getByText('Continuous')).toBeInTheDocument();+ });+ });++ // ── ColorBarRow: title rendering ──────────────────────────────────────────++ describe('ColorBarRow: title rendering', () => {+ it('renders the legend title', () => {+ const layer = buildLayer('layer-1', [buildLegend({ title: 'My Layer' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('My Layer')).toBeInTheDocument();+ });++ it('replaces "Nitric Oxide" title with "Nitrogen Dioxide"', () => {+ const layer = buildLayer('layer-1', [buildLegend({ title: 'Nitric Oxide' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('Nitrogen Dioxide')).toBeInTheDocument();+ expect(screen.queryByText('Nitric Oxide')).not.toBeInTheDocument();+ });++ it('replaces "Deep Blue Aerosol Optical Depth" with "Aerosol Optical Depth"', () => {+ const layer = buildLayer('layer-1', [buildLegend({ title: 'Deep Blue Aerosol Optical Depth' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('Aerosol Optical Depth')).toBeInTheDocument();+ expect(screen.queryByText('Deep Blue Aerosol Optical Depth')).not.toBeInTheDocument();+ });++ it('renders other titles unchanged', () => {+ const layer = buildLayer('layer-1', [buildLegend({ title: 'Carbon Monoxide' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('Carbon Monoxide')).toBeInTheDocument();+ });++ it('renders title in a div with class "travel-mode-colorbar-title"', () => {+ const layer = buildLayer('layer-1', [buildLegend({ title: 'My Title' })]);+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('.travel-mode-colorbar-title')).toHaveTextContent('My Title');+ });+ });++ // ── ColorBarRow: min/max labels ───────────────────────────────────────────++ describe('ColorBarRow: min/max labels', () => {+ it('renders minLabel with units when units are defined', () => {+ const layer = buildLayer('layer-1', [buildLegend({ minLabel: '0', units: '°C' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('0 °C')).toBeInTheDocument();+ });++ it('renders maxLabel with units when units are defined', () => {+ const layer = buildLayer('layer-1', [buildLegend({ maxLabel: '30', units: '°C' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('30 °C')).toBeInTheDocument();+ });++ it('renders minLabel without units when units are undefined', () => {+ const layer = buildLayer('layer-1', [buildLegend({ minLabel: '0', units: undefined })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('0')).toBeInTheDocument();+ });++ it('renders maxLabel without units when units are undefined', () => {+ const layer = buildLayer('layer-1', [buildLegend({ maxLabel: '100', units: undefined })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(screen.getByText('100')).toBeInTheDocument();+ });++ it('renders min label in a div with class "travel-mode-colorbar-min-label"', () => {+ const layer = buildLayer('layer-1', [buildLegend({ minLabel: '-10', units: 'K' })]);+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('.travel-mode-colorbar-min-label')).toHaveTextContent('-10 K');+ });++ it('renders max label in a div with class "travel-mode-colorbar-max-label"', () => {+ const layer = buildLayer('layer-1', [buildLegend({ maxLabel: '50', units: 'K' })]);+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('.travel-mode-colorbar-max-label')).toHaveTextContent('50 K');+ });+ });++ // ── ColorBarRow: canvas ───────────────────────────────────────────────────++ describe('ColorBarRow: canvas', () => {+ it('renders a canvas element', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('canvas')).toBeInTheDocument();+ });++ it('renders canvas with class "travel-mode-colorbar"', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('canvas.travel-mode-colorbar')).toBeInTheDocument();+ });++ it('renders canvas with width 400', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('canvas')).toHaveAttribute('width', '400');+ });++ it('renders canvas with height 40', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('canvas')).toHaveAttribute('height', '40');+ });+ });++ // ── ColorBarRow: drawTravelModePaletteOnCanvas ────────────────────────────++ describe('ColorBarRow: drawTravelModePaletteOnCanvas', () => {+ it('calls drawTravelModePaletteOnCanvas for a continuous legend', () => {+ const layer = buildLayer('layer-1', [buildLegend({ type: 'continuous' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(drawTravelModePaletteOnCanvas).toHaveBeenCalledTimes(1);+ });++ it('calls drawTravelModePaletteOnCanvas for a discrete legend', () => {+ const layer = buildLayer('layer-1', [buildLegend({ type: 'discrete' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(drawTravelModePaletteOnCanvas).toHaveBeenCalledTimes(1);+ });++ it('does NOT call drawTravelModePaletteOnCanvas for a classification legend', () => {+ const layer = buildLayer('layer-1', [buildLegend({ type: 'classification' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(drawTravelModePaletteOnCanvas).not.toHaveBeenCalled();+ });++ it('calls drawTravelModePaletteOnCanvas with the correct colors', () => {+ const colors = ['#ff0000', '#00ff00', '#0000ff'];+ const layer = buildLayer('layer-1', [buildLegend({ type: 'continuous', colors })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(drawTravelModePaletteOnCanvas).toHaveBeenCalledWith(+ expect.anything(),+ colors,+ 400,+ 40,+ );+ });++ it('calls drawTravelModePaletteOnCanvas with width 400 and height 40', () => {+ const layer = buildLayer('layer-1', [buildLegend({ type: 'continuous' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(drawTravelModePaletteOnCanvas).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ 400,+ 40,+ );+ });++ it('calls drawTravelModePaletteOnCanvas once per continuous/discrete legend', () => {+ const layer = buildLayer('layer-1', [+ buildLegend({ id: 'leg-1', type: 'continuous' }),+ buildLegend({ id: 'leg-2', type: 'discrete' }),+ ]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(drawTravelModePaletteOnCanvas).toHaveBeenCalledTimes(2);+ });++ it('does NOT call drawTravelModePaletteOnCanvas for an unrecognized legend type', () => {+ const layer = buildLayer('layer-1', [buildLegend({ type: 'unknown' })]);+ renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(drawTravelModePaletteOnCanvas).not.toHaveBeenCalled();+ });+ });++ // ── ColorBarRow: DOM structure ────────────────────────────────────────────++ describe('ColorBarRow: DOM structure', () => {+ it('renders the row wrapper with class "travel-mode-colorbar-row"', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('.travel-mode-colorbar-row')).toBeInTheDocument();+ });++ it('renders the canvas wrapper with class "travel-mode-colorbar-case"', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('.travel-mode-colorbar-case')).toBeInTheDocument();+ });++ it('renders the label container with class "travel-mode-colorbar-label-container"', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('.travel-mode-colorbar-label-container')).toBeInTheDocument();+ });++ it('renders the labels wrapper with class "travel-mode-colorbar-labels"', () => {+ const layer = buildLayer('layer-1');+ const { container } = renderComponent(buildStore({ active: {}, rendered: { 'layer-1': layer } }));+ expect(container.querySelector('.travel-mode-colorbar-labels')).toBeInTheDocument();+ });+ });});diff --git a/web/js/mapUI/components/kiosk/travel-mode/travelModeTitle.test.js b/web/js/mapUI/components/kiosk/travel-mode/travelModeTitle.test.jsindex 12cda13c3..3247d8c89 100644--- a/web/js/mapUI/components/kiosk/travel-mode/travelModeTitle.test.js+++ b/web/js/mapUI/components/kiosk/travel-mode/travelModeTitle.test.js@@ -1,3 +1,133 @@-test('travelModeTitle mapUI test', () => {+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import TravelModeTitle from './travelModeTitle';+jest.mock('../tile-measurement/utils/layer-data-eic', () => ({+ travelModeData: {+ 1: { title: 'True Color Imagery from Terra satellite' },+ 2: { title: 'Geostationary imagery from NOAA and JAXA satellites' },+ 3: { title: 'Active fires detected by Suomi NPP satellite' },+ 4: { title: 'Black Marble Night Time Imaging from Suomi NPP satellite' },+ 5: { title: 'Rain and Snow' },+ },+}));++const mockStore = configureMockStore();++function buildStore(travelMode) {+ return mockStore({ ui: { travelMode } });+}++function renderComponent(travelMode) {+ const store = buildStore(travelMode);+ const utils = render(+ <Provider store={store}>+ <TravelModeTitle />+ </Provider>,+ );+ return { ...utils, store };+}++describe('TravelModeTitle', () => {+ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders without crashing', () => {+ expect(() => renderComponent(1)).not.toThrow();+ });++ it('renders the outer wrapper with id "travel-mode-title"', () => {+ const { container } = renderComponent(1);+ expect(container.querySelector('#travel-mode-title')).toBeInTheDocument();+ });++ it('renders a span inside the wrapper', () => {+ const { container } = renderComponent(1);+ expect(container.querySelector('#travel-mode-title span')).toBeInTheDocument();+ });+ });++ // ── Title text: known travelModeIDs ───────────────────────────────────────++ describe('Title text: known travelModeIDs', () => {+ it('renders the title for travelMode 1', () => {+ renderComponent(1);+ expect(screen.getByText('True Color Imagery from Terra satellite')).toBeInTheDocument();+ });++ it('renders the title for travelMode 2', () => {+ renderComponent(2);+ expect(screen.getByText('Geostationary imagery from NOAA and JAXA satellites')).toBeInTheDocument();+ });++ it('renders the title for travelMode 3', () => {+ renderComponent(3);+ expect(screen.getByText('Active fires detected by Suomi NPP satellite')).toBeInTheDocument();+ });++ it('renders the title for travelMode 4', () => {+ renderComponent(4);+ expect(screen.getByText('Black Marble Night Time Imaging from Suomi NPP satellite')).toBeInTheDocument();+ });++ it('renders the title for travelMode 5', () => {+ renderComponent(5);+ expect(screen.getByText('Rain and Snow')).toBeInTheDocument();+ });+ });++ // ── Title text: unknown / falsy travelModeIDs ─────────────────────────────++ describe('Title text: unknown / falsy travelModeIDs', () => {+ it('renders an empty string when travelMode is 0 (not in travelModeData)', () => {+ renderComponent(0);+ const span = document.querySelector('#travel-mode-title span');+ expect(span).toBeEmptyDOMElement();+ });++ it('renders an empty string when travelMode is null', () => {+ renderComponent(null);+ const span = document.querySelector('#travel-mode-title span');+ expect(span).toBeEmptyDOMElement();+ });++ it('renders an empty string when travelMode is undefined', () => {+ renderComponent(undefined);+ const span = document.querySelector('#travel-mode-title span');+ expect(span).toBeEmptyDOMElement();+ });++ it('renders an empty string when travelMode is an unrecognized number', () => {+ renderComponent(999);+ const span = document.querySelector('#travel-mode-title span');+ expect(span).toBeEmptyDOMElement();+ });++ it('renders an empty string when travelMode is an empty string', () => {+ renderComponent('');+ const span = document.querySelector('#travel-mode-title span');+ expect(span).toBeEmptyDOMElement();+ });+ });++ // ── useSelector ───────────────────────────────────────────────────────────++ describe('useSelector', () => {+ it('reads state.ui.travelMode from the Redux store', () => {+ renderComponent(1);+ expect(screen.getByText('True Color Imagery from Terra satellite')).toBeInTheDocument();+ });++ it('updates the title when the store has a different travelMode', () => {+ renderComponent(2);+ expect(screen.getByText('Geostationary imagery from NOAA and JAXA satellites')).toBeInTheDocument();+ });++ it('does not render the wrong title for the given travelMode', () => {+ renderComponent(1);+ expect(screen.queryByText('Rain and Snow')).not.toBeInTheDocument();+ });+ });});diff --git a/web/js/mapUI/components/layers/addLayer.test.js b/web/js/mapUI/components/layers/addLayer.test.jsindex 0fc0b5d5e..fed230295 100644--- a/web/js/mapUI/components/layers/addLayer.test.js+++ b/web/js/mapUI/components/layers/addLayer.test.js@@ -1,3 +1,550 @@-test('addLayer 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 ConnectedAddLayer from './addLayer';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('../../../modules/layers/selectors', () => ({+ getLayers: jest.fn(() => []),+}));++jest.mock('../../../modules/layers/constants', () => ({+ ADD_LAYER: 'ADD_LAYER',+ UPDATE_DDV_LAYER: 'UPDATE_DDV_LAYER',+}));++jest.mock('../../../modules/date/actions', () => ({+ clearPreload: jest.fn(() => ({ type: 'CLEAR_PRELOAD' })),+}));++jest.mock('../../../modules/ui/constants', () => ({+ DISPLAY_STATIC_MAP: 'DISPLAY_STATIC_MAP',+}));++import { getLayers } from '../../../modules/layers/selectors';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockNewLayer = { wv: { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' } };+const mockLayerDef = { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', type: 'wms' };++function buildMockGroupLayers(existingLayerIds = []) {+ const arr = existingLayerIds.map((id) => ({ wv: { id } }));+ return {+ getArray: jest.fn(() => [...arr]),+ removeAt: jest.fn((i) => arr.splice(i, 1)),+ insertAt: jest.fn(),+ push: jest.fn(),+ getLength: jest.fn(() => arr.length),+ };+}++function buildMockFirstLayer(group = null, granule = false) {+ return {+ get: jest.fn((key) => {+ if (key === 'group') return group;+ if (key === 'granule') return granule;+ return null;+ }),+ getLayers: jest.fn(() => buildMockGroupLayers()),+ };+}++function buildMockMapLayers(mapLayerArray = []) {+ return {+ getArray: jest.fn(() => mapLayerArray),+ insertAt: jest.fn(),+ push: jest.fn(),+ getLength: jest.fn(() => mapLayerArray.length),+ removeAt: jest.fn(),+ };+}++function buildMockSelected(mapLayersObj) {+ return {+ getLayers: jest.fn(() => mapLayersObj),+ getSize: jest.fn(() => [800, 600]),+ };+}++function buildMockUi(createLayerResult = mockNewLayer, mapLayersObj = null) {+ const layers = mapLayersObj ?? buildMockMapLayers([]);+ return {+ createLayer: jest.fn().mockResolvedValue(createLayerResult),+ selected: buildMockSelected(layers),+ processingPromise: null,+ };+}++function buildAction(type, layerDef = mockLayerDef) {+ return {+ type,+ id: layerDef.id,+ layers: [layerDef],+ };+}++function buildStore() {+ return mockStore({+ compare: {+ activeString: 'active',+ active: false,+ mode: 'compare',+ },+ date: {+ selected: new Date('2024-06-15'),+ selectedB: new Date('2024-06-14'),+ },+ layers: { active: [] },+ proj: { id: 'geographic' },+ });+}++// Props passed directly — note that clearPreload and projFilteredLayers are+// overridden by mapDispatchToProps / mapStateToProps in the connected component.+// clearPreload assertions must use store.getActions(), and projFilteredLayers+// is controlled via getLayers mock.+function buildProps(overrides = {}) {+ const ui = buildMockUi();+ return {+ action: buildAction('ADD_LAYER'),+ activeString: 'active',+ clearPreload: jest.fn(),+ compareDate: new Date('2024-06-15'),+ compareMapUi: { create: jest.fn() },+ mode: 'compare',+ preloadNextTiles: jest.fn(),+ projFilteredLayers: [mockLayerDef],+ updateLayerVisibilities: jest.fn(),+ ui,+ ...overrides,+ };+}++function renderComponent(props, store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <ConnectedAddLayer {...props} />+ </Provider>,+ );+ return { ...utils, store: s };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('AddLayer', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'warn').mockImplementation(() => {});+ // Default: one matching layer so projFilteredLayers index !== -1+ getLayers.mockReturnValue([mockLayerDef]);+ });++ afterEach(() => {+ console.warn.mockRestore();+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const props = buildProps({ action: { type: 'UNKNOWN' } });+ const { container } = renderComponent(props);+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect: action type routing ────────────────────────────────────────++ describe('useEffect: action type routing', () => {+ // clearPreload is bound via mapDispatchToProps — assert via store.getActions()+ it('dispatches CLEAR_PRELOAD when action type is ADD_LAYER and def is not granule', async () => {+ const store = buildStore();+ const props = buildProps();+ renderComponent(props, store);+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'CLEAR_PRELOAD' }),+ );+ });++ it('dispatches CLEAR_PRELOAD when action type is UPDATE_DDV_LAYER', async () => {+ const store = buildStore();+ const props = buildProps({ action: buildAction('UPDATE_DDV_LAYER') });+ renderComponent(props, store);+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'CLEAR_PRELOAD' }),+ );+ });++ it('does NOT dispatch CLEAR_PRELOAD for granule layers', async () => {+ const store = buildStore();+ const granuleDef = { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', type: 'granule' };+ const props = buildProps({ action: buildAction('ADD_LAYER', granuleDef) });+ renderComponent(props, store);+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'CLEAR_PRELOAD' }),+ );+ });++ it('does NOT dispatch CLEAR_PRELOAD when action type is DISPLAY_STATIC_MAP', async () => {+ const store = buildStore();+ const props = buildProps({ action: { type: 'DISPLAY_STATIC_MAP' } });+ renderComponent(props, store);+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'CLEAR_PRELOAD' }),+ );+ });++ it('does not call createLayer for unknown action types', async () => {+ const props = buildProps({ action: { type: 'UNKNOWN_ACTION' } });+ renderComponent(props);+ await act(async () => {});+ expect(props.ui.createLayer).not.toHaveBeenCalled();+ });+ });++ // ── addLayer: simple (no compare group) ──────────────────────────────────++ describe('addLayer: no compare group (firstLayer.get("group") is falsy)', () => {+ function buildSimpleUi() {+ const firstLayer = { get: jest.fn(() => null) };+ const mapLayersObj = buildMockMapLayers([firstLayer]);+ mapLayersObj.getLength.mockReturnValue(5);+ return buildMockUi(mockNewLayer, mapLayersObj);+ }++ it('calls updateLayerVisibilities immediately on ADD_LAYER', async () => {+ const props = buildProps({ ui: buildSimpleUi() });+ renderComponent(props);+ await act(async () => {});+ expect(props.updateLayerVisibilities).toHaveBeenCalled();+ });++ it('calls createLayer with the layer def', async () => {+ const ui = buildSimpleUi();+ const props = buildProps({ ui });+ renderComponent(props);+ await act(async () => {});+ expect(ui.createLayer).toHaveBeenCalled();+ });++ it('calls insertAt with index 0 when adjustedIndex <= getLength()', async () => {+ const ui = buildSimpleUi();+ const mapLayersObj = ui.selected.getLayers();+ mapLayersObj.getLength.mockReturnValue(5);+ const props = buildProps({ ui });+ renderComponent(props);+ await act(async () => {});+ expect(mapLayersObj.insertAt).toHaveBeenCalledWith(0, mockNewLayer);+ });++ it('calls push when adjustedIndex > getLength()', async () => {+ const firstLayer = { get: jest.fn(() => null) };+ const mapLayersObj = buildMockMapLayers([firstLayer]);+ mapLayersObj.getLength.mockReturnValue(0);+ getLayers.mockReturnValue([+ { id: 'layer-0' },+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ { id: 'layer-2' },+ ]);+ const ui = buildMockUi(mockNewLayer, mapLayersObj);+ const props = buildProps({+ ui,+ projFilteredLayers: [+ { id: 'layer-0' },+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ { id: 'layer-2' },+ ],+ });+ renderComponent(props);+ await act(async () => {});+ expect(mapLayersObj.push).toHaveBeenCalledWith(mockNewLayer);+ });++ // projFilteredLayers comes from mapStateToProps via getLayers — control it there+ it('returns early when def.id is not found in projFilteredLayers (index === -1)', async () => {+ getLayers.mockReturnValue([{ id: 'OTHER_LAYER' }]);+ const ui = buildSimpleUi();+ const props = buildProps({ ui });+ renderComponent(props);+ await act(async () => {});+ expect(ui.createLayer).not.toHaveBeenCalled();+ });++ it('calls preloadNextTiles after layer creation', async () => {+ const ui = buildSimpleUi();+ const props = buildProps({ ui });+ renderComponent(props);+ await act(async () => {});+ expect(props.preloadNextTiles).toHaveBeenCalledTimes(1);+ });++ it('removes an existing layer with the same id before inserting', async () => {+ const existingLayer = { wv: { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' } };+ const firstLayer = { get: jest.fn(() => null) };+ const mapLayersArr = [firstLayer, existingLayer];+ const mapLayersObj = buildMockMapLayers(mapLayersArr);+ mapLayersObj.getLength.mockReturnValue(5);+ const ui = buildMockUi(mockNewLayer, mapLayersObj);+ const props = buildProps({ ui });+ renderComponent(props);+ await act(async () => {});+ expect(mapLayersObj.removeAt).toHaveBeenCalled();+ });++ it('warns and does not throw when createLayer rejects', async () => {+ const firstLayer = { get: jest.fn(() => null) };+ const mapLayersObj = buildMockMapLayers([firstLayer]);+ const ui = buildMockUi(mockNewLayer, mapLayersObj);+ ui.createLayer = jest.fn().mockRejectedValue(new Error('create failed'));+ const props = buildProps({ ui });+ renderComponent(props);+ await act(async () => {});+ expect(console.warn).toHaveBeenCalledWith(+ expect.stringContaining('addLayer failed'),+ expect.any(Error),+ );+ });+ });++ // ── addLayer: compare group (firstLayer has group) ─────────────────────────++ describe('addLayer: compare group (firstLayer.get("group") is set)', () => {+ function buildCompareUi(activeString = 'active', existingIds = []) {+ const groupLayersObj = buildMockGroupLayers(existingIds);+ groupLayersObj.getLength.mockReturnValue(5);+ const firstLayer = buildMockFirstLayer(activeString, false);+ firstLayer.getLayers = jest.fn(() => groupLayersObj);+ const secondLayer = buildMockFirstLayer('activeB', false);+ secondLayer.getLayers = jest.fn(() => buildMockGroupLayers());+ const mapLayersObj = buildMockMapLayers([firstLayer, secondLayer]);+ const ui = {+ createLayer: jest.fn().mockResolvedValue(mockNewLayer),+ selected: buildMockSelected(mapLayersObj),+ processingPromise: null,+ };+ return { ui, groupLayersObj, firstLayer };+ }++ it('calls createLayer with date and group options', async () => {+ const { ui } = buildCompareUi();+ const props = buildProps({ ui, activeString: 'active' });+ renderComponent(props);+ await act(async () => {});+ expect(ui.createLayer).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ group: 'active' }),+ );+ });++ it('calls compareMapUi.create with ui.selected and mode', async () => {+ const { ui } = buildCompareUi();+ const props = buildProps({ ui, activeString: 'active' });+ renderComponent(props);+ await act(async () => {});+ expect(props.compareMapUi.create).toHaveBeenCalledWith(+ ui.selected,+ props.mode,+ );+ });++ it('inserts the new layer into groupLayers via insertAt', async () => {+ const { ui, groupLayersObj } = buildCompareUi();+ const props = buildProps({ ui, activeString: 'active' });+ renderComponent(props);+ await act(async () => {});+ expect(groupLayersObj.insertAt).toHaveBeenCalledWith(+ expect.any(Number),+ mockNewLayer,+ );+ });++ it('removes existing duplicate and adjusts index when existingIndex < index', async () => {+ getLayers.mockReturnValue([+ { id: 'other-layer' },+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ ]);+ const { ui, groupLayersObj } = buildCompareUi('active', [+ 'other-layer',+ 'MODIS_Terra_CorrectedReflectance_TrueColor',+ ]);+ const props = buildProps({+ ui,+ activeString: 'active',+ projFilteredLayers: [+ { id: 'other-layer' },+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ ],+ });+ renderComponent(props);+ await act(async () => {});+ expect(groupLayersObj.removeAt).toHaveBeenCalled();+ });++ it('pushes to groupLayers when adjustedIndex > getLength()', async () => {+ getLayers.mockReturnValue([+ { id: 'a' },+ { id: 'b' },+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ ]);+ const { ui, groupLayersObj } = buildCompareUi();+ groupLayersObj.getLength.mockReturnValue(0);+ const props = buildProps({+ ui,+ activeString: 'active',+ projFilteredLayers: [+ { id: 'a' },+ { id: 'b' },+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ ],+ });+ renderComponent(props);+ await act(async () => {});+ expect(groupLayersObj.push).toHaveBeenCalledWith(mockNewLayer);+ });++ it('uses mapLayers[1] as activelayer when firstLayer group does not match activeString', async () => {+ const groupLayersB = buildMockGroupLayers();+ groupLayersB.getLength.mockReturnValue(5);+ const firstLayer = buildMockFirstLayer('activeB', false);+ const secondLayer = buildMockFirstLayer('active', false);+ secondLayer.getLayers = jest.fn(() => groupLayersB);+ const mapLayersObj = buildMockMapLayers([firstLayer, secondLayer]);+ const ui = {+ createLayer: jest.fn().mockResolvedValue(mockNewLayer),+ selected: buildMockSelected(mapLayersObj),+ processingPromise: null,+ };+ const props = buildProps({ ui, activeString: 'active' });+ renderComponent(props);+ await act(async () => {});+ expect(groupLayersB.insertAt).toHaveBeenCalled();+ });+ });++ // ── granuleLayerAdd ────────────────────────────────────────────────────────++ describe('granuleLayerAdd', () => {+ it('does NOT dispatch CLEAR_PRELOAD for granule type', async () => {+ const store = buildStore();+ const granuleDef = { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', type: 'granule' };+ const props = buildProps({ action: buildAction('ADD_LAYER', granuleDef) });+ renderComponent(props, store);+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'CLEAR_PRELOAD' }),+ );+ });++ it('sets ui.processingPromise after granuleLayerAdd', async () => {+ const granuleDef = { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', type: 'granule' };+ const props = buildProps({ action: buildAction('ADD_LAYER', granuleDef) });+ renderComponent(props);+ await act(async () => {});+ expect(props.ui.processingPromise).toBeDefined();+ });++ it('chains onto existing ui.processingPromise', async () => {+ const granuleDef = { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', type: 'granule' };+ const existingPromise = Promise.resolve();+ const ui = buildMockUi();+ ui.processingPromise = existingPromise;+ const props = buildProps({ action: buildAction('ADD_LAYER', granuleDef), ui });+ renderComponent(props);+ await act(async () => {});+ expect(props.ui.processingPromise).not.toBe(existingPromise);+ });++ it('calls updateLayerVisibilities after granuleLayerAdd resolves', async () => {+ const granuleDef = { id: 'MODIS_Terra_CorrectedReflectance_TrueColor', type: 'granule' };+ const firstLayer = { get: jest.fn(() => null) };+ const mapLayersObj = buildMockMapLayers([firstLayer]);+ mapLayersObj.getLength.mockReturnValue(5);+ const ui = buildMockUi(mockNewLayer, mapLayersObj);+ const props = buildProps({ action: buildAction('ADD_LAYER', granuleDef), ui });+ renderComponent(props);+ await act(async () => {});+ await ui.processingPromise;+ expect(props.updateLayerVisibilities).toHaveBeenCalled();+ });+ });++ // ── addStaticLayer ─────────────────────────────────────────────────────────++ describe('addStaticLayer', () => {+ it('calls createLayer with no arguments for DISPLAY_STATIC_MAP', async () => {+ const ui = buildMockUi();+ const props = buildProps({ action: { type: 'DISPLAY_STATIC_MAP' }, ui });+ renderComponent(props);+ await act(async () => {});+ expect(ui.createLayer).toHaveBeenCalledWith();+ });++ it('calls insertAt(0, newLayer) on ui.selected.getLayers()', async () => {+ const mapLayersObj = buildMockMapLayers([]);+ const ui = buildMockUi(mockNewLayer, mapLayersObj);+ const props = buildProps({ action: { type: 'DISPLAY_STATIC_MAP' }, ui });+ renderComponent(props);+ await act(async () => {});+ expect(mapLayersObj.insertAt).toHaveBeenCalledWith(0, mockNewLayer);+ });+ });++ // ── mapStateToProps ────────────────────────────────────────────────────────++ describe('mapStateToProps', () => {+ it('calls getLayers to populate projFilteredLayers', () => {+ const store = buildStore();+ const props = buildProps({ action: { type: 'UNKNOWN' } });+ renderComponent(props, store);+ expect(getLayers).toHaveBeenCalled();+ });++ it('sets compareDate to selected when compare is not active', () => {+ const store = mockStore({+ compare: { activeString: 'active', active: false, mode: 'compare' },+ date: { selected: new Date('2024-01-01'), selectedB: new Date('2024-06-01') },+ layers: { active: [] },+ proj: { id: 'geographic' },+ });+ const props = buildProps({ action: { type: 'UNKNOWN' } });+ renderComponent(props, store);+ expect(getLayers).toHaveBeenCalled();+ });++ it('sets compareDate to selectedB when compare is active and activeString is "activeB"', () => {+ const store = mockStore({+ compare: { activeString: 'activeB', active: true, mode: 'compare' },+ date: { selected: new Date('2024-01-01'), selectedB: new Date('2024-06-01') },+ layers: { active: [] },+ proj: { id: 'geographic' },+ });+ const props = buildProps({ action: { type: 'UNKNOWN' } });+ renderComponent(props, store);+ expect(getLayers).toHaveBeenCalled();+ });+ });++ // ── mapDispatchToProps ─────────────────────────────────────────────────────++ describe('mapDispatchToProps', () => {+ it('dispatches CLEAR_PRELOAD when ADD_LAYER is triggered', async () => {+ const store = buildStore();+ const props = buildProps();+ renderComponent(props, store);+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'CLEAR_PRELOAD' }),+ );+ });+ });});diff --git a/web/js/mapUI/components/layers/removeLayer.test.js b/web/js/mapUI/components/layers/removeLayer.test.jsindex de62679f7..edc03bacc 100644--- a/web/js/mapUI/components/layers/removeLayer.test.js+++ b/web/js/mapUI/components/layers/removeLayer.test.js@@ -1,3 +1,255 @@-test('removeLayer mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import ConnectedRemoveLayer from './removeLayer';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('../../../modules/layers/selectors', () => ({+ getActiveLayerGroup: jest.fn(),+}));++import { getActiveLayerGroup } from '../../../modules/layers/selectors';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockOlLayer = { id: 'mock-ol-layer' };++function buildMockLayerGroup() {+ return {+ getLayers: jest.fn(() => ({+ remove: jest.fn(),+ })),+ };+}++function buildStore(compareOverride = {}) {+ return mockStore({+ compare: {+ active: false,+ activeString: 'active',+ ...compareOverride,+ },+ map: { ui: { selected: {} } },+ });+}++function buildProps(overrides = {}) {+ return {+ action: { layersToRemove: [{ id: 'MODIS_Terra_CorrectedReflectance_TrueColor' }] },+ findLayer: jest.fn(() => mockOlLayer),+ ui: { selected: { removeLayer: jest.fn() } },+ updateLayerVisibilities: jest.fn(),+ ...overrides,+ };+}++function renderComponent(props, store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <ConnectedRemoveLayer {...props} />+ </Provider>,+ );+ return { ...utils, store: s };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('RemoveLayer', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ getActiveLayerGroup.mockReturnValue(null);+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const props = buildProps({ action: {} });+ const { container } = renderComponent(props);+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect guard: no layersToRemove ────────────────────────────────────++ describe('useEffect guard: action.layersToRemove is absent', () => {+ it('does NOT call findLayer when action has no layersToRemove', () => {+ const props = buildProps({ action: {} });+ renderComponent(props);+ expect(props.findLayer).not.toHaveBeenCalled();+ });++ it('does NOT call updateLayerVisibilities when action has no layersToRemove', () => {+ const props = buildProps({ action: {} });+ renderComponent(props);+ expect(props.updateLayerVisibilities).not.toHaveBeenCalled();+ });++ it('does NOT call ui.selected.removeLayer when action has no layersToRemove', () => {+ const props = buildProps({ action: {} });+ renderComponent(props);+ expect(props.ui.selected.removeLayer).not.toHaveBeenCalled();+ });+ });++ // ── removeLayer: compare NOT active ───────────────────────────────────────++ describe('removeLayer: compare not active (ui.selected.removeLayer path)', () => {+ it('calls findLayer with each def and compare.activeString', () => {+ const store = buildStore({ active: false, activeString: 'active' });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.findLayer).toHaveBeenCalledWith(+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ 'active',+ );+ });++ it('calls ui.selected.removeLayer with the resolved OL layer', () => {+ const store = buildStore({ active: false, activeString: 'active' });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.ui.selected.removeLayer).toHaveBeenCalledWith(mockOlLayer);+ });++ it('does NOT call getActiveLayerGroup when compare is not active', () => {+ const store = buildStore({ active: false });+ const props = buildProps();+ renderComponent(props, store);+ expect(getActiveLayerGroup).not.toHaveBeenCalled();+ });++ it('calls updateLayerVisibilities after removing all layers', () => {+ const store = buildStore({ active: false });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('calls removeLayer for each def in layersToRemove', () => {+ const store = buildStore({ active: false, activeString: 'active' });+ const props = buildProps({+ action: {+ layersToRemove: [+ { id: 'MODIS_Terra_CorrectedReflectance_TrueColor' },+ { id: 'VIIRS_SNPP_CorrectedReflectance_TrueColor' },+ ],+ },+ });+ renderComponent(props, store);+ expect(props.findLayer).toHaveBeenCalledTimes(2);+ expect(props.ui.selected.removeLayer).toHaveBeenCalledTimes(2);+ });++ it('calls updateLayerVisibilities exactly once even when removing multiple layers', () => {+ const store = buildStore({ active: false });+ const props = buildProps({+ action: {+ layersToRemove: [+ { id: 'layer-a' },+ { id: 'layer-b' },+ { id: 'layer-c' },+ ],+ },+ });+ renderComponent(props, store);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });+ });++ // ── removeLayer: compare IS active ────────────────────────────────────────++ describe('removeLayer: compare active (layerGroup.getLayers().remove path)', () => {+ it('calls getActiveLayerGroup with the map and compare state from the store', () => {+ const mockLayerGroup = buildMockLayerGroup();+ getActiveLayerGroup.mockReturnValue(mockLayerGroup);+ const store = buildStore({ active: true, activeString: 'active' });+ const props = buildProps();+ renderComponent(props, store);+ expect(getActiveLayerGroup).toHaveBeenCalledWith(+ expect.objectContaining({+ map: expect.anything(),+ compare: expect.objectContaining({ active: true }),+ }),+ );+ });++ it('does NOT call ui.selected.removeLayer when compare is active', () => {+ const mockLayerGroup = buildMockLayerGroup();+ getActiveLayerGroup.mockReturnValue(mockLayerGroup);+ const store = buildStore({ active: true });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.ui.selected.removeLayer).not.toHaveBeenCalled();+ });++ it('calls updateLayerVisibilities after removing in compare mode', () => {+ const mockLayerGroup = buildMockLayerGroup();+ getActiveLayerGroup.mockReturnValue(mockLayerGroup);+ const store = buildStore({ active: true });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('does NOT call layerGroup.getLayers().remove when getActiveLayerGroup returns null', () => {+ getActiveLayerGroup.mockReturnValue(null);+ const store = buildStore({ active: true });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.ui.selected.removeLayer).not.toHaveBeenCalled();+ });++ it('still calls updateLayerVisibilities when layerGroup is null', () => {+ getActiveLayerGroup.mockReturnValue(null);+ const store = buildStore({ active: true });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('calls findLayer with compare.activeString from the store', () => {+ const mockLayerGroup = buildMockLayerGroup();+ getActiveLayerGroup.mockReturnValue(mockLayerGroup);+ const store = buildStore({ active: true, activeString: 'activeB' });+ const props = buildProps();+ renderComponent(props, store);+ expect(props.findLayer).toHaveBeenCalledWith(+ expect.anything(),+ 'activeB',+ );+ });+ });++ // ── mapStateToProps ────────────────────────────────────────────────────────++ describe('mapStateToProps', () => {+ it('passes compare from the store to the component', () => {+ const store = buildStore({ active: true, activeString: 'activeB' });+ const mockLayerGroup = buildMockLayerGroup();+ getActiveLayerGroup.mockReturnValue(mockLayerGroup);+ const props = buildProps();+ renderComponent(props, store);+ expect(props.findLayer).toHaveBeenCalledWith(+ expect.anything(),+ 'activeB',+ );+ });++ it('passes map from the store to getActiveLayerGroup', () => {+ const mockLayerGroup = buildMockLayerGroup();+ getActiveLayerGroup.mockReturnValue(mockLayerGroup);+ const store = buildStore({ active: true });+ const props = buildProps();+ renderComponent(props, store);+ expect(getActiveLayerGroup).toHaveBeenCalledWith(+ expect.objectContaining({ map: expect.anything() }),+ );+ });+ });});diff --git a/web/js/mapUI/components/markers/markers.test.js b/web/js/mapUI/components/markers/markers.test.jsindex c8a52be7f..69e0389e9 100644--- a/web/js/mapUI/components/markers/markers.test.js+++ b/web/js/mapUI/components/markers/markers.test.js@@ -1,3 +1,653 @@-test('markers 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 ConnectedMarkers from './markers';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('../../../modules/location-search/util-api', () => ({+ reverseGeocode: jest.fn(),+}));++jest.mock('../../../components/location-search/util', () => ({+ getNormalizedCoordinate: jest.fn((coord) => coord),+}));++jest.mock('../../../modules/location-search/util', () => ({+ animateCoordinates: jest.fn(),+ areCoordinatesWithinExtent: jest.fn(() => true),+ getCoordinatesMarker: jest.fn(),+}));++jest.mock('../../../modules/location-search/actions', () => ({+ setGeocodeResults: jest.fn((value) => ({ type: 'SET_GEOCODE_RESULTS', value })),+ removeMarker: jest.fn((value) => ({ type: 'REMOVE_MARKER', value })),+}));++jest.mock('../../../modules/layers/selectors', () => ({+ getActiveLayers: jest.fn(() => []),+ getMaxZoomLevelLayerCollection: jest.fn(() => 8),+}));++import { reverseGeocode } from '../../../modules/location-search/util-api';+import { getNormalizedCoordinate } from '../../../components/location-search/util';+import {+ animateCoordinates,+ areCoordinatesWithinExtent,+ getCoordinatesMarker,+} from '../../../modules/location-search/util';+import { getActiveLayers, getMaxZoomLevelLayerCollection } from '../../../modules/layers/selectors';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockMarker = { id: 'marker-1', setMap: jest.fn() };++const mockCoordinatesObject = { id: 'coord-1', longitude: -77.0, latitude: 38.9 };++const mockView = { getZoom: jest.fn(() => 5) };++const mockSelectedMap = {+ getView: jest.fn(() => mockView),+ removeOverlay: jest.fn(),+ addOverlay: jest.fn(),+ renderSync: jest.fn(),+ removeLayer: jest.fn(),+ proj: 'EPSG:4326',+};++function buildMockUi(markers = []) {+ return { markers, selected: mockSelectedMap };+}++// All state that drives mapStateToProps must live in the store.+// activeLayers is filtered by getActiveLayers mock — control it via that mock.+// coordinates, isKioskModeActive, selectedMap, selectedMapMarkers, isMobileDevice+// all come from the store.+function buildStore(overrides = {}) {+ return mockStore({+ locationSearch: { coordinates: [] },+ proj: { id: 'geographic' },+ screenSize: { isMobileDevice: false },+ map: {+ ui: {+ selected: mockSelectedMap,+ markers: [],+ },+ },+ ui: { isKioskModeActive: false },+ layers: { active: [] },+ compare: { activeString: 'active' },+ ...overrides,+ });+}++// Only pass props that are NOT overridden by mapStateToProps/mapDispatchToProps:+// action, config, removeMarker (prop spy, overridden), setGeocodeResults (prop spy, overridden), ui+function buildProps(overrides = {}) {+ return {+ action: { type: '' },+ config: { sources: {} },+ removeMarker: jest.fn(),+ setGeocodeResults: jest.fn(),+ ui: buildMockUi(),+ ...overrides,+ };+}++function renderComponent(props, store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <ConnectedMarkers {...props} />+ </Provider>,+ );+ return { ...utils, store: s };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('Markers', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ getCoordinatesMarker.mockReturnValue(mockMarker);+ areCoordinatesWithinExtent.mockReturnValue(true);+ reverseGeocode.mockResolvedValue({ address: 'Washington, DC' });+ getNormalizedCoordinate.mockImplementation((coord) => coord);+ getActiveLayers.mockReturnValue([]);+ getMaxZoomLevelLayerCollection.mockReturnValue(8);+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const { container } = renderComponent(buildProps());+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect: ui.selected.proj (handleActiveMapMarker) ───────────────────++ describe('useEffect: ui.selected.proj (handleActiveMapMarker)', () => {+ it('does NOT call reverseGeocode when ui.selected is null', async () => {+ const props = buildProps({ ui: { markers: [], selected: null } });+ renderComponent(props);+ await act(async () => {});+ expect(reverseGeocode).not.toHaveBeenCalled();+ });++ it('does NOT call reverseGeocode when ui.selected has no proj', async () => {+ const selectedNoProj = { ...mockSelectedMap, proj: undefined };+ const props = buildProps({ ui: { markers: [], selected: selectedNoProj } });+ renderComponent(props);+ await act(async () => {});+ expect(reverseGeocode).not.toHaveBeenCalled();+ });++ it('does NOT call reverseGeocode when coordinates is empty', async () => {+ const store = buildStore({ locationSearch: { coordinates: [] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(reverseGeocode).not.toHaveBeenCalled();+ });++ it('calls reverseGeocode for each coordinate within extent', async () => {+ const coords = [+ { id: 'c1', longitude: -77, latitude: 38 },+ { id: 'c2', longitude: -80, latitude: 35 },+ ];+ const store = buildStore({ locationSearch: { coordinates: coords } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(reverseGeocode).toHaveBeenCalledTimes(2);+ });++ it('does NOT call reverseGeocode for coordinates outside extent', async () => {+ areCoordinatesWithinExtent.mockReturnValue(false);+ const store = buildStore({+ locationSearch: { coordinates: [{ id: 'c1', longitude: -77, latitude: 38 }] },+ });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(reverseGeocode).not.toHaveBeenCalled();+ });++ it('calls areCoordinatesWithinExtent with the correct proj and coord', async () => {+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(areCoordinatesWithinExtent).toHaveBeenCalledWith(+ { id: 'geographic' },+ [-77, 38],+ );+ });++ it('calls getNormalizedCoordinate with the coordinate pair', async () => {+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(getNormalizedCoordinate).toHaveBeenCalledWith([-77, 38]);+ });++ it('calls removeAllCoordinatesMarkers before processing coordinates', async () => {+ const existingMarker = { setMap: jest.fn() };+ const ui = buildMockUi([existingMarker]);+ const store = buildStore({ locationSearch: { coordinates: [] } });+ renderComponent(buildProps({ ui }), store);+ await act(async () => {});+ expect(existingMarker.setMap).toHaveBeenCalledWith(null);+ expect(mockSelectedMap.removeOverlay).toHaveBeenCalledWith(existingMarker);+ });++ it('calls addOverlay on ui.selected with the marker after reverseGeocode', async () => {+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(mockSelectedMap.addOverlay).toHaveBeenCalledWith(mockMarker);+ });++ it('calls renderSync on ui.selected after adding the marker', async () => {+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(mockSelectedMap.renderSync).toHaveBeenCalled();+ });++ it('dispatches SET_GEOCODE_RESULTS with reverseGeocode results', async () => {+ const mockResults = { address: 'Washington, DC' };+ reverseGeocode.mockResolvedValue(mockResults);+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_GEOCODE_RESULTS' }),+ );+ });++ it('does NOT call addOverlay when getCoordinatesMarker returns null', async () => {+ getCoordinatesMarker.mockReturnValue(null);+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(mockSelectedMap.addOverlay).not.toHaveBeenCalled();+ });++ it('does NOT dispatch SET_GEOCODE_RESULTS when reverseGeocode resolves with null', async () => {+ reverseGeocode.mockResolvedValue(null);+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(store.getActions()).not.toContainEqual(+ expect.objectContaining({ type: 'SET_GEOCODE_RESULTS' }),+ );+ });++ it('pushes marker to ui.markers', async () => {+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const ui = buildMockUi([]);+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps({ ui }), store);+ await act(async () => {});+ expect(ui.markers).toContain(mockMarker);+ });++ it('calls getCoordinatesMarker with correct arguments', async () => {+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const results = { address: 'Test' };+ reverseGeocode.mockResolvedValue(results);+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(getCoordinatesMarker).toHaveBeenCalledWith(+ { id: 'geographic' },+ coord,+ results,+ expect.any(Function),+ false,+ true,+ );+ });+ });++ // ── useEffect: action dispatch ────────────────────────────────────────────++ describe('useEffect: action type routing', () => {+ describe('LOCATION_SEARCH/REMOVE_MARKER', () => {+ it('calls setMap(null) on the matching marker', () => {+ const markerToRemove = { id: 'coord-1', setMap: jest.fn() };+ // selectedMapMarkers comes from map.ui.markers in the store+ const store = buildStore({+ map: { ui: { selected: mockSelectedMap, markers: [markerToRemove] } },+ });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/REMOVE_MARKER',+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(markerToRemove.setMap).toHaveBeenCalledWith(null);+ });++ it('calls selectedMap.removeOverlay with the matching marker', () => {+ const markerToRemove = { id: 'coord-1', setMap: jest.fn() };+ const store = buildStore({+ map: { ui: { selected: mockSelectedMap, markers: [markerToRemove] } },+ });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/REMOVE_MARKER',+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(mockSelectedMap.removeOverlay).toHaveBeenCalledWith(markerToRemove);+ });++ it('does NOT call setMap on a marker with a different id', () => {+ const otherMarker = { id: 'other-id', setMap: jest.fn() };+ const store = buildStore({+ map: { ui: { selected: mockSelectedMap, markers: [otherMarker] } },+ });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/REMOVE_MARKER',+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(otherMarker.setMap).not.toHaveBeenCalled();+ });+ });++ describe('LOCATION_SEARCH/SET_MARKER', () => {+ it('calls flyToMarker (animateCoordinates) when flyToExistingMarker is true', () => {+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props);+ expect(animateCoordinates).toHaveBeenCalled();+ });++ it('calls animateCoordinates with correct arguments when flyToExistingMarker is true', () => {+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props);+ expect(animateCoordinates).toHaveBeenCalledWith(+ mockSelectedMap,+ { id: 'geographic' },+ [-77, 38.9],+ 8,+ false,+ );+ });++ it('calls addMarkerAndUpdateStore when flyToExistingMarker is false', () => {+ const mockResults = { address: 'DC' };+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: mockResults,+ isCoordinatesSearchActive: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props);+ expect(getCoordinatesMarker).toHaveBeenCalledWith(+ { id: 'geographic' },+ mockCoordinatesObject,+ mockResults,+ expect.any(Function),+ false,+ true,+ );+ });++ it('calls addOverlay and renderSync when flyToExistingMarker is false', () => {+ const mockResults = { address: 'DC' };+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: mockResults,+ isCoordinatesSearchActive: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props);+ expect(mockSelectedMap.addOverlay).toHaveBeenCalledWith(mockMarker);+ expect(mockSelectedMap.renderSync).toHaveBeenCalled();+ });++ it('calls flyToMarker when isCoordinatesSearchActive is true', () => {+ const mockResults = { address: 'DC' };+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: mockResults,+ isCoordinatesSearchActive: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props);+ expect(animateCoordinates).toHaveBeenCalled();+ });++ it('does NOT call flyToMarker when isCoordinatesSearchActive is false', () => {+ const mockResults = { address: 'DC' };+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: mockResults,+ isCoordinatesSearchActive: false,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props);+ expect(animateCoordinates).not.toHaveBeenCalled();+ });++ it('dispatches SET_GEOCODE_RESULTS when flyToExistingMarker is false', () => {+ const mockResults = { address: 'DC' };+ const store = buildStore();+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: mockResults,+ isCoordinatesSearchActive: false,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_GEOCODE_RESULTS' }),+ );+ });++ it('returns undefined when reverseGeocodeResults is null', () => {+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: null,+ isCoordinatesSearchActive: false,+ coordinates: mockCoordinatesObject,+ },+ });+ expect(() => renderComponent(props)).not.toThrow();+ expect(mockSelectedMap.addOverlay).not.toHaveBeenCalled();+ });+ });++ describe('LOCATION_SEARCH/TOGGLE_DIALOG_VISIBLE', () => {+ it('calls addMarkerAndUpdateStore with showDialog=false and no geocodeResults', () => {+ const props = buildProps({+ action: { type: 'LOCATION_SEARCH/TOGGLE_DIALOG_VISIBLE' },+ });+ renderComponent(props);+ expect(mockSelectedMap.addOverlay).not.toHaveBeenCalled();+ });++ it('does not throw for TOGGLE_DIALOG_VISIBLE action', () => {+ const props = buildProps({+ action: { type: 'LOCATION_SEARCH/TOGGLE_DIALOG_VISIBLE' },+ });+ expect(() => renderComponent(props)).not.toThrow();+ });+ });++ describe('unknown action type', () => {+ it('does nothing for an unknown action type', () => {+ const props = buildProps({ action: { type: 'UNKNOWN_ACTION' } });+ renderComponent(props);+ expect(mockSelectedMap.addOverlay).not.toHaveBeenCalled();+ expect(animateCoordinates).not.toHaveBeenCalled();+ });+ });+ });++ // ── removeCoordinatesMarker ────────────────────────────────────────────────++ describe('removeCoordinatesMarker', () => {+ it('calls setMap(null) on each marker matching coordinatesObject.id', () => {+ const matchingMarker = { id: 'coord-1', setMap: jest.fn() };+ const nonMatchingMarker = { id: 'coord-2', setMap: jest.fn() };+ const store = buildStore({+ map: { ui: { selected: mockSelectedMap, markers: [matchingMarker, nonMatchingMarker] } },+ });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/REMOVE_MARKER',+ coordinates: { id: 'coord-1' },+ },+ });+ renderComponent(props, store);+ expect(matchingMarker.setMap).toHaveBeenCalledWith(null);+ expect(nonMatchingMarker.setMap).not.toHaveBeenCalled();+ });++ it('calls selectedMap.removeOverlay only for the matching marker', () => {+ const matchingMarker = { id: 'coord-1', setMap: jest.fn() };+ const nonMatchingMarker = { id: 'coord-2', setMap: jest.fn() };+ const store = buildStore({+ map: { ui: { selected: mockSelectedMap, markers: [matchingMarker, nonMatchingMarker] } },+ });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/REMOVE_MARKER',+ coordinates: { id: 'coord-1' },+ },+ });+ renderComponent(props, store);+ expect(mockSelectedMap.removeOverlay).toHaveBeenCalledWith(matchingMarker);+ expect(mockSelectedMap.removeOverlay).not.toHaveBeenCalledWith(nonMatchingMarker);+ });+ });++ // ── flyToMarker ────────────────────────────────────────────────────────────++ describe('flyToMarker', () => {+ it('calls animateCoordinates with isKioskModeActive flag from the store', () => {+ const store = buildStore({ ui: { isKioskModeActive: true } });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(animateCoordinates).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.anything(),+ expect.anything(),+ true,+ );+ });+ });++ // ── mapStateToProps ────────────────────────────────────────────────────────++ describe('mapStateToProps', () => {+ it('reads coordinates from locationSearch state', async () => {+ const coord = { id: 'c1', longitude: -77, latitude: 38 };+ const store = buildStore({ locationSearch: { coordinates: [coord] } });+ renderComponent(buildProps(), store);+ await act(async () => {});+ expect(reverseGeocode).toHaveBeenCalled();+ });++ it('reads isKioskModeActive from ui state', () => {+ const store = buildStore({ ui: { isKioskModeActive: true } });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(animateCoordinates).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.anything(),+ expect.anything(),+ true,+ );+ });++ it('reads selectedMap from map.ui.selected', () => {+ const store = buildStore();+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: true,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(mockView.getZoom).toHaveBeenCalled();+ });++ it('reads selectedMapMarkers from map.ui.markers', () => {+ const markerToRemove = { id: 'coord-1', setMap: jest.fn() };+ const store = buildStore({+ map: { ui: { selected: mockSelectedMap, markers: [markerToRemove] } },+ });+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/REMOVE_MARKER',+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(markerToRemove.setMap).toHaveBeenCalledWith(null);+ });+ });++ // ── mapDispatchToProps ─────────────────────────────────────────────────────++ describe('mapDispatchToProps', () => {+ it('dispatches SET_GEOCODE_RESULTS when setGeocodeResults is called', () => {+ const mockResults = { address: 'DC' };+ const store = buildStore();+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: mockResults,+ isCoordinatesSearchActive: false,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'SET_GEOCODE_RESULTS' }),+ );+ });++ it('dispatches REMOVE_MARKER when the remove callback from getCoordinatesMarker is invoked', () => {+ const mockResults = { address: 'DC' };+ const store = buildStore();+ const props = buildProps({+ action: {+ type: 'LOCATION_SEARCH/SET_MARKER',+ flyToExistingMarker: false,+ reverseGeocodeResults: mockResults,+ isCoordinatesSearchActive: false,+ coordinates: mockCoordinatesObject,+ },+ });+ renderComponent(props, store);+ const removeFn = getCoordinatesMarker.mock.calls[0][3];+ removeFn();+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'REMOVE_MARKER' }),+ );+ });+ });});diff --git a/web/js/mapUI/components/mouse-move-events/mouseMoveEvents.test.js b/web/js/mapUI/components/mouse-move-events/mouseMoveEvents.test.jsindex aaa675775..8de5c302a 100644--- a/web/js/mapUI/components/mouse-move-events/mouseMoveEvents.test.js+++ b/web/js/mapUI/components/mouse-move-events/mouseMoveEvents.test.js@@ -1,3 +1,370 @@-test('mouseMoveEvents 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 ConnectedMouseMoveEvents from './mouseMoveEvents';+import { MAP_MOUSE_MOVE, MAP_MOUSE_OUT } from '../../../util/constants';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('../../../util/util', () => ({+ __esModule: true,+ default: {+ events: {+ on: jest.fn(),+ },+ },+}));++import util from '../../../util/util';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockPixel = [100, 200];+const mockCoords = [-77, 38];++const mockRunningdata = {+ newPoint: jest.fn(),+ clearAll: jest.fn(),+};++const mockSelected = {+ getCoordinateFromPixel: jest.fn(() => mockCoords),+ proj: 'EPSG:4326',+};++function buildMockUi(overrides = {}) {+ return {+ selected: mockSelected,+ mapIsbeingZoomed: false,+ mapIsbeingDragged: false,+ runningdata: mockRunningdata,+ ...overrides,+ };+}++function buildMockMap(selectedOverride = {}) {+ return {+ ui: {+ selected: {+ proj: 'EPSG:4326',+ ...selectedOverride,+ },+ },+ };+}++function buildStore(overrides = {}) {+ return mockStore({+ events: { active: false },+ locationSearch: { isCoordinateSearchActive: false },+ sidebar: { activeTab: 'layers' },+ animation: { isPlaying: false },+ measure: { isActive: false },+ screenSize: { isMobileDevice: false },+ map: buildMockMap(),+ ...overrides,+ });+}++// Only pass props NOT overridden by mapStateToProps:+// ui, compareMapUi — all boolean flags come from the store+function buildProps(overrides = {}) {+ return {+ ui: buildMockUi(),+ compareMapUi: null,+ ...overrides,+ };+}++function renderComponent(props, store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <ConnectedMouseMoveEvents {...props} />+ </Provider>,+ );+ return { ...utils, store: s };+}++// Extract the registered handler for a given event from util.events.on mock calls+function getHandler(eventName) {+ const call = util.events.on.mock.calls.find(([event]) => event === eventName);+ return call ? call[1] : null;+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('MouseMoveEvents', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.useFakeTimers();+ util.events.on = jest.fn();+ mockSelected.getCoordinateFromPixel.mockReturnValue(mockCoords);+ mockSelected.proj = 'EPSG:4326';+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const { container } = renderComponent(buildProps());+ expect(container.firstChild).toBeNull();+ });+ });++ // ── events.on registration ─────────────────────────────────────────────────++ describe('events.on registration', () => {+ it('registers a MAP_MOUSE_MOVE handler', () => {+ renderComponent(buildProps());+ expect(util.events.on).toHaveBeenCalledWith(MAP_MOUSE_MOVE, expect.any(Function));+ });++ it('registers a MAP_MOUSE_OUT handler', () => {+ renderComponent(buildProps());+ expect(util.events.on).toHaveBeenCalledWith(MAP_MOUSE_OUT, expect.any(Function));+ });++ it('registers exactly two event handlers', () => {+ renderComponent(buildProps());+ expect(util.events.on).toHaveBeenCalledTimes(2);+ });+ });++ // ── throttledOnMouseMove: guard conditions ────────────────────────────────++ describe('throttledOnMouseMove: guard conditions', () => {+ async function triggerMouseMove(props, store, pixel = mockPixel) {+ renderComponent(props, store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ }++ it('calls newPoint when all conditions are satisfied', async () => {+ await triggerMouseMove(buildProps(), buildStore());+ expect(mockRunningdata.newPoint).toHaveBeenCalledWith(mockPixel, mockSelected);+ });++ it('does NOT call newPoint when map.ui.selected is null', async () => {+ const store = buildStore({ map: { ui: { selected: null } } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when map.ui.selected.proj !== ui.selected.proj', async () => {+ const store = buildStore({ map: buildMockMap({ proj: 'EPSG:3413' }) });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when ui.mapIsbeingZoomed is true', async () => {+ const ui = buildMockUi({ mapIsbeingZoomed: true });+ await triggerMouseMove(buildProps({ ui }), buildStore());+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when ui.mapIsbeingDragged is true', async () => {+ const ui = buildMockUi({ mapIsbeingDragged: true });+ await triggerMouseMove(buildProps({ ui }), buildStore());+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when compareMapUi.dragging is true', async () => {+ const props = buildProps({ compareMapUi: { dragging: true } });+ await triggerMouseMove(props, buildStore());+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when isMobile is true', async () => {+ const store = buildStore({ screenSize: { isMobileDevice: true } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when isMeasureActive is true', async () => {+ const store = buildStore({ measure: { isActive: true } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when isCoordinateSearchActive is true', async () => {+ const store = buildStore({ locationSearch: { isCoordinateSearchActive: true } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when coords is null', async () => {+ mockSelected.getCoordinateFromPixel.mockReturnValue(null);+ await triggerMouseMove(buildProps(), buildStore());+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when isEventsTabActive is true', async () => {+ const store = buildStore({ events: { active: true } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when isMapAnimating is true', async () => {+ const store = buildStore({ animation: { isPlaying: true } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('does NOT call newPoint when sidebarActiveTab is "download"', async () => {+ const store = buildStore({ sidebar: { activeTab: 'download' } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('calls newPoint when compareMapUi is null', async () => {+ await triggerMouseMove(buildProps({ compareMapUi: null }), buildStore());+ expect(mockRunningdata.newPoint).toHaveBeenCalled();+ });++ it('calls newPoint when compareMapUi.dragging is false', async () => {+ await triggerMouseMove(buildProps({ compareMapUi: { dragging: false } }), buildStore());+ expect(mockRunningdata.newPoint).toHaveBeenCalled();+ });++ it('calls newPoint when sidebarActiveTab is "layers"', async () => {+ const store = buildStore({ sidebar: { activeTab: 'layers' } });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).toHaveBeenCalled();+ });++ it('calls newPoint when sidebarActiveTab is "events" but isEventsTabActive is false', async () => {+ const store = buildStore({+ sidebar: { activeTab: 'events' },+ events: { active: false },+ });+ await triggerMouseMove(buildProps(), store);+ expect(mockRunningdata.newPoint).toHaveBeenCalled();+ });+ });++ // ── MAP_MOUSE_OUT handler ─────────────────────────────────────────────────++ describe('MAP_MOUSE_OUT handler', () => {+ it('calls ui.runningdata.clearAll when MAP_MOUSE_OUT fires', () => {+ renderComponent(buildProps(), buildStore());+ const handler = getHandler(MAP_MOUSE_OUT);+ act(() => { handler({}); });+ expect(mockRunningdata.clearAll).toHaveBeenCalledTimes(1);+ });+ });++ // ── useEffect: mouseMove state dependency ─────────────────────────────────++ describe('useEffect: mouseMove state dependency', () => {+ it('calls throttledOnMouseMove when setMouseMove is triggered via MAP_MOUSE_MOVE', async () => {+ renderComponent(buildProps(), buildStore());+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).toHaveBeenCalledWith(mockPixel, mockSelected);+ });++ it('calls newPoint with the correct pixel each time MAP_MOUSE_MOVE fires', async () => {+ const pixelA = [10, 20];+ const pixelB = [30, 40];+ renderComponent(buildProps(), buildStore());+ const handler = getHandler(MAP_MOUSE_MOVE);++ act(() => { handler({ pixel: pixelA }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});++ act(() => { handler({ pixel: pixelB }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});++ expect(mockRunningdata.newPoint).toHaveBeenCalledWith(pixelA, mockSelected);+ expect(mockRunningdata.newPoint).toHaveBeenCalledWith(pixelB, mockSelected);+ });+ });++ // ── mapStateToProps ────────────────────────────────────────────────────────++ describe('mapStateToProps', () => {+ it('sets isEventsTabActive to false when events state is undefined', async () => {+ const store = buildStore({ events: undefined });+ renderComponent(buildProps(), store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).toHaveBeenCalled();+ });++ it('sets isEventsTabActive to true when events.active is true', async () => {+ const store = buildStore({ events: { active: true } });+ renderComponent(buildProps(), store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('reads isMobileDevice from screenSize state', async () => {+ const store = buildStore({ screenSize: { isMobileDevice: true } });+ renderComponent(buildProps(), store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('reads isActive from measure state', async () => {+ const store = buildStore({ measure: { isActive: true } });+ renderComponent(buildProps(), store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('reads isPlaying from animation state', async () => {+ const store = buildStore({ animation: { isPlaying: true } });+ renderComponent(buildProps(), store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('reads activeTab from sidebar state', async () => {+ const store = buildStore({ sidebar: { activeTab: 'download' } });+ renderComponent(buildProps(), store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });++ it('reads isCoordinateSearchActive from locationSearch state', async () => {+ const store = buildStore({ locationSearch: { isCoordinateSearchActive: true } });+ renderComponent(buildProps(), store);+ const handler = getHandler(MAP_MOUSE_MOVE);+ act(() => { handler({ pixel: mockPixel }); });+ jest.advanceTimersByTime(300);+ await act(async () => {});+ expect(mockRunningdata.newPoint).not.toHaveBeenCalled();+ });+ });});diff --git a/web/js/mapUI/components/update-collections/updateCollections.test.js b/web/js/mapUI/components/update-collections/updateCollections.test.jsindex 89ed091e0..1851acd34 100644--- a/web/js/mapUI/components/update-collections/updateCollections.test.js+++ b/web/js/mapUI/components/update-collections/updateCollections.test.js@@ -1,3 +1,739 @@-test('updatecollections mapUI test', () => {+import { render, act } from '@testing-library/react';+import { Provider } from 'react-redux';+import configureMockStore from 'redux-mock-store';+import UpdateCollections from './updateCollections';+// ─── Mocks ────────────────────────────────────────────────────────────────────++jest.mock('../../../modules/date/selectors', () => ({+ getSelectedDate: jest.fn((state) => state.date.selected),+}));++jest.mock('../../../modules/layers/actions', () => ({+ updateCollection: jest.fn((collection) => ({ type: 'UPDATE_COLLECTION', collection })),+}));++jest.mock('../kiosk/tile-measurement/utils/date-util', () => ({+ formatDailyDate: jest.fn(() => '2024-06-15'),+ formatSubdailyDate: jest.fn(() => '2024-06-15T12:00:00Z'),+}));++jest.mock('../../../util/util', () => ({+ __esModule: true,+ default: {+ toISOStringSeconds: jest.fn(() => '2024-06-15T12:00:59Z'),+ roundTimeOneMinute: jest.fn((d) => d),+ },+}));++import { formatDailyDate, formatSubdailyDate } from '../kiosk/tile-measurement/utils/date-util';+import util from '../../../util/util';++// ─── Fixtures ─────────────────────────────────────────────────────────────────++const mockStore = configureMockStore();++const mockSelectedDate = new Date('2024-06-15T12:00:00Z');+mockSelectedDate.setSeconds = jest.fn();++const mockLayerDef = {+ id: 'MODIS_Terra_CorrectedReflectance_TrueColor',+ type: 'wmts',+ period: 'daily',+ layergroup: 'Corrected Reflectance',+ visible: true,+ format: 'image/jpeg',+ projections: {+ geographic: {+ matrixSet: '250m',+ layer: 'MODIS_Terra_CorrectedReflectance_TrueColor',+ },+ },+};++const mockGranuleLayerDef = {+ id: 'VIIRS_SNPP_Granule_Layer',+ type: 'granule',+ period: 'daily',+ layergroup: 'Granule',+ visible: true,+ format: 'image/png',+ projections: {+ geographic: {+ matrixSet: '250m',+ layer: 'VIIRS_SNPP_Granule_Layer',+ },+ },+};++const mockSubdailyLayerDef = {+ id: 'GOES-East_ABI_GeoColor',+ type: 'wmts',+ period: 'subdaily',+ layergroup: 'GeoColor',+ visible: true,+ format: 'image/jpeg',+ projections: {+ geographic: {+ matrixSet: '1km',+ layer: 'GOES-East_ABI_GeoColor',+ },+ },+};++function buildMockHeaders(actualId = 'MODIS_Terra_CorrectedReflectance_TrueColor_v6_NRT') {+ return { get: jest.fn((key) => (key === 'layer-identifier-actual' ? actualId : null)) };+}++function buildFetchResponse(actualId = 'MODIS_Terra_CorrectedReflectance_TrueColor_v6_NRT') {+ return { headers: buildMockHeaders(actualId) };+}++function buildLayerConfig(layerIds = ['MODIS_Terra_CorrectedReflectance_TrueColor']) {+ const config = {};+ layerIds.forEach((id) => {+ config[id] = {+ projections: {+ geographic: { source: 'GIBS:geographic' },+ },+ };+ });+ return config;+}++function buildSources() {+ return {+ 'GIBS:geographic': { url: 'https://gibs-{a-b}.earthdata.nasa.gov/wmts' },+ };+}++function buildMapWithLayers(layerArray = []) {+ return {+ getLayers: jest.fn(() => ({ getArray: jest.fn(() => layerArray) })),+ getAllLayers: jest.fn(() => layerArray),+ };+}++function buildStore(overrides = {}) {+ return mockStore({+ date: { selected: mockSelectedDate },+ proj: { id: 'geographic' },+ config: { sources: buildSources() },+ layers: {+ collections: {},+ active: { layers: [mockLayerDef] },+ layerConfig: buildLayerConfig(),+ },+ map: { ui: { selected: buildMapWithLayers() } },+ ...overrides,+ });+}++function renderComponent(store) {+ const s = store ?? buildStore();+ const utils = render(+ <Provider store={s}>+ <UpdateCollections />+ </Provider>,+ );+ return { ...utils, store: s };+}++// ─── Tests ────────────────────────────────────────────────────────────────────++describe('UpdateCollections', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ global.fetch = jest.fn().mockResolvedValue(buildFetchResponse());+ formatDailyDate.mockReturnValue('2024-06-15');+ formatSubdailyDate.mockReturnValue('2024-06-15T12:00:00Z');+ util.toISOStringSeconds.mockReturnValue('2024-06-15T12:00:59Z');+ util.roundTimeOneMinute.mockImplementation((d) => d);+ });++ afterEach(() => {+ delete global.fetch;+ });++ // ── Rendering ──────────────────────────────────────────────────────────────++ describe('Rendering', () => {+ it('renders null (no DOM output)', () => {+ const { container } = renderComponent();+ expect(container.firstChild).toBeNull();+ });+ });++ // ── useEffect guard: layers.length ────────────────────────────────────────++ describe('useEffect guard: empty layers', () => {+ it('does NOT call fetch when layers array is empty', async () => {+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).not.toHaveBeenCalled();+ });+ });++ // ── findLayerCollections ───────────────────────────────────────────────────++ describe('findLayerCollections', () => {+ it('includes a visible wmts layer not yet in collections', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalled();+ });++ it('excludes Reference layergroup layers', async () => {+ const refLayer = { ...mockLayerDef, layergroup: 'Reference' };+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [refLayer] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('excludes layers with type other than wmts or granule', async () => {+ const wmsLayer = { ...mockLayerDef, type: 'wms' };+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [wmsLayer] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('excludes invisible layers', async () => {+ const invisibleLayer = { ...mockLayerDef, visible: false };+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [invisibleLayer] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('includes a layer in collections but with a different date', async () => {+ const store = buildStore({+ layers: {+ collections: {+ MODIS_Terra_CorrectedReflectance_TrueColor: {+ dates: [{ date: '2024-06-14', projection: 'geographic' }],+ },+ },+ active: { layers: [mockLayerDef] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalled();+ });++ it('includes a layer in collections but with a different projection', async () => {+ const store = buildStore({+ layers: {+ collections: {+ MODIS_Terra_CorrectedReflectance_TrueColor: {+ dates: [{ date: '2024-06-15', projection: 'arctic' }],+ },+ },+ active: { layers: [mockLayerDef] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalled();+ });++ it('uses subdailyDate for subdaily period layers', async () => {+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [mockSubdailyLayerDef] },+ layerConfig: buildLayerConfig(['GOES-East_ABI_GeoColor']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalled();+ });++ it('includes a granule layer not in collections', async () => {+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [mockGranuleLayerDef] },+ layerConfig: buildLayerConfig(['VIIRS_SNPP_Granule_Layer']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalled();+ });+ });++ // ── lookupLayerSource ─────────────────────────────────────────────────────++ describe('lookupLayerSource', () => {+ it('replaces the subdomain template with "-a"', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('gibs-a.earthdata.nasa.gov'),+ expect.anything(),+ );+ });++ it('does not alter URLs without a subdomain template', async () => {+ const store = buildStore({+ config: {+ sources: {+ 'GIBS:geographic': { url: 'https://gibs.earthdata.nasa.gov/wmts' },+ },+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('gibs.earthdata.nasa.gov'),+ expect.anything(),+ );+ });+ });++ // ── getHeaders: fetch call ────────────────────────────────────────────────++ describe('getHeaders: fetch request', () => {+ it('calls fetch with method HEAD', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ method: 'HEAD' }),+ );+ });++ it('includes layer id in the fetch URL', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('MODIS_Terra_CorrectedReflectance_TrueColor'),+ expect.anything(),+ );+ });++ it('includes matrixSet in the fetch URL', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('250m'),+ expect.anything(),+ );+ });++ it('includes TIME parameter in the fetch URL when no baseUrl', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('TIME='),+ expect.anything(),+ );+ });++ it('calls util.toISOStringSeconds and util.roundTimeOneMinute', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(util.roundTimeOneMinute).toHaveBeenCalledWith(mockSelectedDate);+ expect(util.toISOStringSeconds).toHaveBeenCalled();+ });++ it('sets seconds to 59 for subdaily layers', async () => {+ const subdailyDate = new Date('2024-06-15T12:00:00Z');+ subdailyDate.setSeconds = jest.fn();+ const store = buildStore({+ date: { selected: subdailyDate },+ layers: {+ collections: {},+ active: { layers: [mockSubdailyLayerDef] },+ layerConfig: buildLayerConfig(['GOES-East_ABI_GeoColor']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(subdailyDate.setSeconds).toHaveBeenCalledWith(59);+ });++ it('uses projConfig.layer as layerId when available', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('layer=MODIS_Terra_CorrectedReflectance_TrueColor'),+ expect.anything(),+ );+ });++ it('falls back to def.id when projConfig.layer and projConfig.id are absent', async () => {+ const layerDefNoProjectionLayer = {+ ...mockLayerDef,+ projections: {+ geographic: { matrixSet: '250m' },+ },+ };+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [layerDefNoProjectionLayer] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('layer=MODIS_Terra_CorrectedReflectance_TrueColor'),+ expect.anything(),+ );+ });++ it('passes an AbortSignal to fetch', async () => {+ renderComponent(buildStore());+ await act(async () => {});+ const fetchOptions = global.fetch.mock.calls[0][1];+ expect(fetchOptions.signal).toBeDefined();+ });++ it('does NOT fetch Reference layergroup layers', async () => {+ const refLayer = { ...mockLayerDef, layergroup: 'Reference' };+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [refLayer] },+ layerConfig: buildLayerConfig(),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).not.toHaveBeenCalled();+ });+ });++ // ── getHeaders: response parsing ──────────────────────────────────────────++ describe('getHeaders: response parsing', () => {+ it('dispatches UPDATE_COLLECTION with NRT type collection', async () => {+ global.fetch.mockResolvedValue(+ buildFetchResponse('MODIS_Terra_CorrectedReflectance_TrueColor_v6_NRT'),+ );+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'UPDATE_COLLECTION' }),+ );+ });++ it('dispatches UPDATE_COLLECTION with STD type collection', async () => {+ global.fetch.mockResolvedValue(+ buildFetchResponse('MODIS_Terra_CorrectedReflectance_TrueColor_v6_STD'),+ );+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ expect(store.getActions()).toContainEqual(+ expect.objectContaining({ type: 'UPDATE_COLLECTION' }),+ );+ });++ it('dispatches UPDATE_COLLECTION with correct id, type, version and projection', async () => {+ global.fetch.mockResolvedValue(+ buildFetchResponse('MODIS_Terra_CorrectedReflectance_TrueColor_v6_NRT'),+ );+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ const [collection] = action.collection;+ expect(collection.id).toBe('MODIS_Terra_CorrectedReflectance_TrueColor');+ expect(collection.type).toBe('NRT');+ expect(collection.version).toBe('v6');+ expect(collection.projection).toBe('geographic');+ });++ it('dispatches UPDATE_COLLECTION with a daily formatted date', async () => {+ formatDailyDate.mockReturnValue('2024-06-15');+ global.fetch.mockResolvedValue(+ buildFetchResponse('MODIS_Terra_CorrectedReflectance_TrueColor_v6_NRT'),+ );+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ const [collection] = action.collection;+ expect(collection.date).toBe('2024-06-15');+ });++ it('dispatches UPDATE_COLLECTION with a subdaily formatted date for subdaily layers', async () => {+ formatSubdailyDate.mockReturnValue('2024-06-15T12:00:00Z');+ global.fetch.mockResolvedValue(+ buildFetchResponse('GOES-East_ABI_GeoColor_v1_NRT'),+ );+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [mockSubdailyLayerDef] },+ layerConfig: buildLayerConfig(['GOES-East_ABI_GeoColor']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ if (action) {+ const [collection] = action.collection;+ expect(collection.date).toBe('2024-06-15T12:00:00Z');+ }+ });++ it('does NOT dispatch UPDATE_COLLECTION when layer-identifier-actual header is missing', async () => {+ global.fetch.mockResolvedValue({ headers: { get: jest.fn(() => null) } });+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ if (action) {+ expect(action.collection).toHaveLength(0);+ }+ });++ it('does NOT dispatch UPDATE_COLLECTION with invalid imagery type', async () => {+ global.fetch.mockResolvedValue(+ buildFetchResponse('MODIS_Terra_CorrectedReflectance_TrueColor_v6_INVALID'),+ );+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ if (action) {+ expect(action.collection).toHaveLength(0);+ }+ });++ it('does NOT dispatch UPDATE_COLLECTION when fetch rejects', async () => {+ global.fetch.mockRejectedValue(new Error('network error'));+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ if (action) {+ expect(action.collection).toHaveLength(0);+ }+ });+ });++ // ── getAllHeaders: granule layers ─────────────────────────────────────────++ describe('getAllHeaders: granule layer handling', () => {+ it('calls fetch with a baseUrl from granule layer URLs', async () => {+ const mockGranuleUrl = 'https://mock-granule-url.com?time=2024-06-15';+ const mockGranuleSource = {+ getUrls: jest.fn(() => [mockGranuleUrl]),+ };+ const mockSubLayer = {+ getSource: jest.fn(() => mockGranuleSource),+ };+ const mockGranuleGroup = {+ wv: { id: 'VIIRS_SNPP_Granule_Layer' },+ getLayersArray: jest.fn(() => [mockSubLayer]),+ };+ const mockMap = buildMapWithLayers([mockGranuleGroup]);+ mockMap.getLayers = jest.fn(() => ({+ getArray: jest.fn(() => [mockGranuleGroup]),+ }));+ const store = buildStore({+ map: { ui: { selected: mockMap } },+ layers: {+ collections: {},+ active: { layers: [mockGranuleLayerDef] },+ layerConfig: buildLayerConfig(['VIIRS_SNPP_Granule_Layer']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining(mockGranuleUrl),+ expect.anything(),+ );+ });++ it('falls back to requestSelectedDateHeaders when layerGroup not found on map', async () => {+ const mockMap = buildMapWithLayers([]);+ const store = buildStore({+ map: { ui: { selected: mockMap } },+ layers: {+ collections: {},+ active: { layers: [mockGranuleLayerDef] },+ layerConfig: buildLayerConfig(['VIIRS_SNPP_Granule_Layer']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('TIME='),+ expect.anything(),+ );+ });++ it('falls back to requestSelectedDateHeaders when map is null', async () => {+ const store = buildStore({+ map: null,+ layers: {+ collections: {},+ active: { layers: [mockGranuleLayerDef] },+ layerConfig: buildLayerConfig(['VIIRS_SNPP_Granule_Layer']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ expect(global.fetch).toHaveBeenCalled();+ });++ it('skips granule sub-layers with no URLs', async () => {+ const mockGranuleSource = { getUrls: jest.fn(() => []) };+ const mockSubLayer = { getSource: jest.fn(() => mockGranuleSource) };+ const mockGranuleGroup = {+ wv: { id: 'VIIRS_SNPP_Granule_Layer' },+ getLayersArray: jest.fn(() => [mockSubLayer]),+ };+ const mockMap = buildMapWithLayers([mockGranuleGroup]);+ mockMap.getLayers = jest.fn(() => ({+ getArray: jest.fn(() => [mockGranuleGroup]),+ }));+ const store = buildStore({+ map: { ui: { selected: mockMap } },+ layers: {+ collections: {},+ active: { layers: [mockGranuleLayerDef] },+ layerConfig: buildLayerConfig(['VIIRS_SNPP_Granule_Layer']),+ },+ });+ renderComponent(store);+ await act(async () => {});+ // Promise.any with empty array rejects — collection should be empty+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ if (action) {+ expect(action.collection).toHaveLength(0);+ }+ });+ });++ // ── updateLayerCollections: forceUpdate ───────────────────────────────────++ describe('updateLayerCollections: forceUpdate via projId/mapLayersLength', () => {+ it('calls fetch even when layer is already in collections when projId changes', async () => {+ const { rerender } = renderComponent(buildStore({+ layers: {+ collections: {+ MODIS_Terra_CorrectedReflectance_TrueColor: {+ dates: [{ date: '2024-06-15', projection: 'geographic' }],+ },+ },+ active: { layers: [mockLayerDef] },+ layerConfig: buildLayerConfig(),+ },+ }));++ await act(async () => {});+ global.fetch.mockClear();++ const newStore = buildStore({+ proj: { id: 'arctic' },+ config: {+ sources: { 'GIBS:geographic': { url: 'https://gibs.earthdata.nasa.gov/wmts' } },+ },+ layers: {+ collections: {+ MODIS_Terra_CorrectedReflectance_TrueColor: {+ dates: [{ date: '2024-06-15', projection: 'geographic' }],+ },+ },+ active: { layers: [{ ...mockLayerDef, projections: { arctic: { matrixSet: '250m', layer: 'MODIS_Terra_CorrectedReflectance_TrueColor' } } }] },+ layerConfig: {+ MODIS_Terra_CorrectedReflectance_TrueColor: {+ projections: { arctic: { source: 'GIBS:geographic' } },+ },+ },+ },+ map: { ui: { selected: buildMapWithLayers() } },+ });++ await act(async () => {+ rerender(+ <Provider store={newStore}>+ <UpdateCollections />+ </Provider>,+ );+ });++ expect(global.fetch).toHaveBeenCalled();+ });+ });++ // ── updateCollection dispatch ─────────────────────────────────────────────++ describe('updateCollection dispatch', () => {+ it('dispatches UPDATE_COLLECTION once per render cycle', async () => {+ global.fetch.mockResolvedValue(+ buildFetchResponse('MODIS_Terra_CorrectedReflectance_TrueColor_v6_NRT'),+ );+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ const updateActions = store.getActions().filter((a) => a.type === 'UPDATE_COLLECTION');+ expect(updateActions.length).toBeGreaterThanOrEqual(1);+ });++ it('dispatches UPDATE_COLLECTION with empty array when no valid collections found', async () => {+ global.fetch.mockResolvedValue({ headers: { get: jest.fn(() => null) } });+ const { store } = renderComponent(buildStore());+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ expect(action.collection).toEqual([]);+ });++ it('dispatches UPDATE_COLLECTION with multiple collections when multiple layers succeed', async () => {+ const secondLayerDef = {+ ...mockLayerDef,+ id: 'MODIS_Aqua_CorrectedReflectance_TrueColor',+ projections: { geographic: { matrixSet: '250m', layer: 'MODIS_Aqua_CorrectedReflectance_TrueColor' } },+ };+ global.fetch+ .mockResolvedValueOnce(buildFetchResponse('MODIS_Terra_CorrectedReflectance_TrueColor_v6_NRT'))+ .mockResolvedValueOnce(buildFetchResponse('MODIS_Aqua_CorrectedReflectance_TrueColor_v6_STD'));+ const store = buildStore({+ layers: {+ collections: {},+ active: { layers: [mockLayerDef, secondLayerDef] },+ layerConfig: buildLayerConfig([+ 'MODIS_Terra_CorrectedReflectance_TrueColor',+ 'MODIS_Aqua_CorrectedReflectance_TrueColor',+ ]),+ },+ });+ renderComponent(store);+ await act(async () => {});+ const action = store.getActions().find((a) => a.type === 'UPDATE_COLLECTION');+ expect(action.collection).toHaveLength(2);+ });+ });});diff --git a/web/js/mapUI/components/update-date/updateDate.test.js b/web/js/mapUI/components/update-date/updateDate.test.jsindex a2ce8893c..58482c2ee 100644--- a/web/js/mapUI/components/update-date/updateDate.test.js+++ b/web/js/mapUI/components/update-date/updateDate.test.js@@ -1,3 +1,829 @@-test('updateDate mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render } from '@testing-library/react';+import * as dateConstants from '../../../modules/date/constants';+import * as layerConstants from '../../../modules/layers/constants';+import {+ getActiveLayers,+ getAllActiveLayers,+ getActiveLayerGroup,+ getGranuleCount,+} from '../../../modules/layers/selectors';+import { setStyleFunction } from '../../../modules/vector-styles/selectors';+import { getSelectedDate } from '../../../modules/date/selectors';+jest.mock('react-redux', () => ({+ ...jest.requireActual('react-redux'),+ connect: () => (Component) => Component,+}));++jest.mock('../../../modules/layers/selectors');+jest.mock('../../../modules/vector-styles/selectors');+jest.mock('../../../modules/date/selectors');++const UpdateDate = require('./updateDate').default;++const flushPromises = () => new Promise((resolve) => { setTimeout(resolve, 0); });++const makeCollection = (arr = []) => {+ const items = [...arr];+ return {+ getArray: () => items,+ setAt: jest.fn((index, val) => { items[index] = val; }),+ };+};++const makeLayer = (id, type = 'tile', period = 'daily', extra = {}) => ({+ wv: {+ id,+ def: { id, type, period, ...(extra.def || {}) },+ ...(extra.wv || {}),+ },+ get: jest.fn((key) => (key === 'group' ? extra.group : undefined)),+ ...(extra.getLayers ? { getLayers: extra.getLayers } : {}),+});++const makeDef = (id, type = 'tile', period = 'daily', extra = {}) => ({+ id,+ type,+ period,+ visible: true,+ ...extra,+});++const buildProps = (overrides = {}) => {+ const createdLayer = { wv: { id: 'layer-1', def: { id: 'layer-1' } } };+ const createLayer = jest.fn().mockResolvedValue(createdLayer);++ const ui = {+ createLayer,+ processingPromise: null,+ selected: null,+ dateUpdateSeq: 0,+ cmrRebuildSeq: 0,+ };++ return {+ action: { type: dateConstants.SELECT_DATE, outOfStep: false },+ activeLayers: [],+ activeString: 'active',+ compareMapUi: { update: jest.fn() },+ config: { vectorStyles: null },+ dateCompareState: { date: {}, compare: { activeString: 'active' } },+ getGranuleOptions: jest.fn().mockReturnValue({}),+ granuleState: {},+ isCompareActive: false,+ layerState: {},+ preloadNextTiles: jest.fn(),+ allActiveLayersState: {},+ ui,+ updateLayerVisibilities: jest.fn(),+ vectorStyleState: {},+ ...overrides,+ };+};++const setupDefaultMocks = (layerId = 'layer-1', type = 'tile', period = 'daily') => {+ const mapLayer = makeLayer(layerId, type, period);+ const collection = makeCollection([mapLayer]);+ const layerGroup = { getLayers: () => collection };++ getActiveLayerGroup.mockReturnValue(layerGroup);+ getAllActiveLayers.mockReturnValue([makeDef(layerId, type, period)]);+ getActiveLayers.mockReturnValue([]);+ getGranuleCount.mockReturnValue(20);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ return { mapLayer, collection, layerGroup };+};++const renderComponent = (props) => render(<UpdateDate {...props} />);++describe('UpdateDate', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ console.warn.mockRestore?.();+ });++ describe('renders null', () => {+ it('returns null from render', () => {+ setupDefaultMocks();+ const props = buildProps();+ const { container } = renderComponent(props);+ expect(container.firstChild).toBeNull();+ });+ });++ describe('actionSwitch — unknown action type', () => {+ it('returns undefined and does not call updateLayerVisibilities', () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: 'UNKNOWN_ACTION' } });+ renderComponent(props);+ expect(props.updateLayerVisibilities).not.toHaveBeenCalled();+ });+ });++ describe('actionSwitch — SELECT_DATE', () => {+ it('calls updateLayerVisibilities immediately', () => {+ setupDefaultMocks();+ const props = buildProps();+ renderComponent(props);+ expect(props.updateLayerVisibilities).toHaveBeenCalled();+ });++ it('calls createLayer for a visible temporal layer', async () => {+ setupDefaultMocks();+ const props = buildProps();+ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).toHaveBeenCalled();+ });++ it('calls preloadNextTiles when outOfStep is false', async () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: dateConstants.SELECT_DATE, outOfStep: false } });+ renderComponent(props);+ await flushPromises();+ expect(props.preloadNextTiles).toHaveBeenCalled();+ });++ it('does not call preloadNextTiles when outOfStep is true', async () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: dateConstants.SELECT_DATE, outOfStep: true } });+ renderComponent(props);+ await flushPromises();+ expect(props.preloadNextTiles).not.toHaveBeenCalled();+ });++ it('waits for processingPromise before calling updateDate', async () => {+ setupDefaultMocks();+ let resolveFn;+ const processingPromise = new Promise((resolve) => { resolveFn = resolve; });+ const props = buildProps();+ props.ui.processingPromise = processingPromise;+ renderComponent(props);+ expect(props.ui.createLayer).not.toHaveBeenCalled();+ resolveFn();+ await flushPromises();+ expect(props.ui.createLayer).toHaveBeenCalled();+ });++ it('clears processingPromise when it is still the same promise after resolution', async () => {+ setupDefaultMocks();+ let resolveFn;+ const processingPromise = new Promise((resolve) => { resolveFn = resolve; });+ const props = buildProps();+ props.ui.processingPromise = processingPromise;+ renderComponent(props);+ resolveFn();+ await flushPromises();+ expect(props.ui.processingPromise).toBeNull();+ });++ it('does not clear processingPromise when it changed during await', async () => {+ setupDefaultMocks();+ let resolveFn;+ const processingPromise = new Promise((resolve) => { resolveFn = resolve; });+ const props = buildProps();+ props.ui.processingPromise = processingPromise;+ renderComponent(props);+ const newPromise = Promise.resolve();+ props.ui.processingPromise = newPromise;+ resolveFn();+ await flushPromises();+ expect(props.ui.processingPromise).toBe(newPromise);+ });++ it('skips non-visible layers', async () => {+ const mapLayer = makeLayer('layer-1', 'tile', 'daily');+ const collection = makeCollection([mapLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));+ getAllActiveLayers.mockReturnValue([makeDef('layer-1', 'tile', 'daily', { visible: false })]);++ const props = buildProps();+ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).not.toHaveBeenCalled();+ });++ it('skips layers not found in the map layer collection', async () => {+ const collection = makeCollection([]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));+ getAllActiveLayers.mockReturnValue([makeDef('missing-layer', 'tile', 'daily')]);++ const props = buildProps();+ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).not.toHaveBeenCalled();+ });++ it('skips setAt if a newer appliedSeq already exists on the layer', async () => {+ // dateUpdateSeq starts at 0, increments to 1 inside updateDate (mySeq=1).+ // appliedSeq must be strictly greater than mySeq to trigger the skip, so use 9999.+ const mapLayer = {+ wv: { id: 'layer-1', def: { id: 'layer-1', type: 'tile', period: 'daily' }, appliedSeq: 9999 },+ };+ const collection = makeCollection([mapLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([makeDef('layer-1', 'tile', 'daily')]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps();+ renderComponent(props);+ await flushPromises();+ expect(collection.setAt).not.toHaveBeenCalled();+ });++ it('handles granule-type layers using getGranuleCount', async () => {+ const granuleLayer = makeLayer('granule-1', 'granule', 'daily');+ const collection = makeCollection([granuleLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([makeDef('granule-1', 'granule', 'daily')]);+ getActiveLayers.mockReturnValue([]);+ getGranuleCount.mockReturnValue(20);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps();+ renderComponent(props);+ await flushPromises();+ expect(getGranuleCount).toHaveBeenCalledWith(props.granuleState, 'granule-1');+ });++ it('uses previousLayer option for non-granule temporal layers', async () => {+ setupDefaultMocks();+ const props = buildProps();+ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ previousLayer: expect.anything() }),+ );+ });++ it('calls setStyleFunction for layers with vectorStyles config', async () => {+ const def = { ...makeDef('layer-1', 'tile', 'daily'), vectorStyle: { id: 'vs-1' } };+ const mapLayer = makeLayer('layer-1', 'tile', 'daily');+ const collection = makeCollection([mapLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([def]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps();+ props.config = { vectorStyles: { 'vs-1': {} } };++ renderComponent(props);+ await flushPromises();+ expect(setStyleFunction).toHaveBeenCalled();+ });++ it('does not call setStyleFunction when config has no vectorStyles', async () => {+ const def = { ...makeDef('layer-1', 'tile', 'daily'), vectorStyle: { id: 'vs-1' } };+ const mapLayer = makeLayer('layer-1', 'tile', 'daily');+ const collection = makeCollection([mapLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([def]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps();+ props.config = { vectorStyles: null };++ renderComponent(props);+ await flushPromises();+ expect(setStyleFunction).not.toHaveBeenCalled();+ });++ it('increments dateUpdateSeq on each updateDate call', async () => {+ setupDefaultMocks();+ const props = buildProps();+ props.ui.dateUpdateSeq = 0;+ renderComponent(props);+ await flushPromises();+ expect(props.ui.dateUpdateSeq).toBe(1);+ });++ it('does not call updateLayerVisibilities a second time when stale after createLayer', async () => {+ setupDefaultMocks();+ const props = buildProps();+ let called = false;+ props.ui.createLayer = jest.fn().mockImplementation(async () => {+ props.ui.dateUpdateSeq += 1;+ called = true;+ return { wv: {} };+ });++ renderComponent(props);+ await flushPromises();+ expect(called).toBe(true);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('skips freshIndex update when freshIndex is -1 after await in non-compare mode', async () => {+ const layer = makeLayer('layer-1', 'tile', 'daily');+ let items = [layer];+ const collection = {+ getArray: () => items,+ setAt: jest.fn(),+ };+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([makeDef('layer-1', 'tile', 'daily')]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps();+ props.ui.createLayer = jest.fn().mockImplementation(async () => {+ items = [];+ return { wv: {} };+ });++ renderComponent(props);+ await flushPromises();+ expect(collection.setAt).not.toHaveBeenCalled();+ });+ });++ describe('actionSwitch — TOGGLE_LAYER_VISIBILITY', () => {+ it('calls updateDate with outOfStep=false', async () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: layerConstants.TOGGLE_LAYER_VISIBILITY } });+ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).toHaveBeenCalled();+ });+ });++ describe('actionSwitch — TOGGLE_OVERLAY_GROUP_VISIBILITY', () => {+ it('calls updateDate with outOfStep=false', async () => {+ setupDefaultMocks();+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUP_VISIBILITY },+ });+ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).toHaveBeenCalled();+ });+ });++ describe('actionSwitch — ADD_GRANULE_DATE_RANGES', () => {+ it('calls updateLayerVisibilities immediately', () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES } });+ renderComponent(props);+ expect(props.updateLayerVisibilities).toHaveBeenCalled();+ });++ it('increments cmrRebuildSeq', () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES } });+ props.ui.cmrRebuildSeq = 0;+ renderComponent(props);+ expect(props.ui.cmrRebuildSeq).toBe(1);+ });++ it('calls updateLayerVisibilities a second time after rebuild when not stale', async () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES } });+ renderComponent(props);+ await flushPromises();+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(2);+ });++ it('does not call updateLayerVisibilities a second time when stale', async () => {+ setupDefaultMocks();+ const props = buildProps({ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES } });+ props.ui.cmrRebuildSeq = 0;+ renderComponent(props);+ props.ui.cmrRebuildSeq = 99;+ await flushPromises();+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('calls rebuildEmptyNonCompareGranules and rebuilds a pending granule', async () => {+ const granuleLayerWv = {+ id: 'g-1',+ def: { id: 'g-1', type: 'granule' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 0,+ };+ const olLayer = { wv: granuleLayerWv };+ const collection = makeCollection([olLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getActiveLayers.mockReturnValue([]);+ getGranuleCount.mockReturnValue(20);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: false,+ });+ const createdLayer = { wv: { id: 'g-1', def: { id: 'g-1' } } };+ props.ui.createLayer = jest.fn().mockResolvedValue(createdLayer);+ props.ui.selected = {};++ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).toHaveBeenCalled();+ });++ it('skips non-compare granule rebuild when ui.selected is null', async () => {+ const granuleLayerWv = {+ id: 'g-1',+ def: { id: 'g-1', type: 'granule' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 0,+ };+ const collection = makeCollection([{ wv: granuleLayerWv }]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: false,+ });+ props.ui.selected = null;++ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).not.toHaveBeenCalled();+ });++ it('skips granule rebuild when cmrRebuildAttempts >= MAX_CMR_REBUILD_ATTEMPTS (3)', async () => {+ const granuleLayerWv = {+ id: 'g-1',+ def: { id: 'g-1', type: 'granule' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 3,+ };+ const collection = makeCollection([{ wv: granuleLayerWv }]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: false,+ });+ props.ui.selected = {};++ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).not.toHaveBeenCalled();+ });++ it('skips non-compare granule rebuild when layer is not a granule type', async () => {+ const layerWv = {+ id: 'tile-1',+ def: { id: 'tile-1', type: 'tile' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 0,+ };+ const collection = makeCollection([{ wv: layerWv }]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: false,+ });+ props.ui.selected = {};++ renderComponent(props);+ await flushPromises();+ expect(props.ui.createLayer).not.toHaveBeenCalled();+ });++ it('calls rebuildAllEmptyCompareGranules when compare is active', async () => {+ const granuleLayerWv = {+ id: 'g-1',+ def: { id: 'g-1', type: 'granule' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 0,+ };+ const olLayer = { wv: granuleLayerWv, get: jest.fn() };+ const groupCollection = makeCollection([olLayer]);+ const groupLayer = {+ get: jest.fn((k) => (k === 'group' ? 'active' : undefined)),+ getLayers: () => groupCollection,+ };+ const allGroupsCollection = makeCollection([groupLayer]);++ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const createdLayer = { wv: { id: 'g-1', def: { id: 'g-1' } } };+ const createLayer = jest.fn().mockResolvedValue(createdLayer);++ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => allGroupsCollection };++ renderComponent(props);+ await flushPromises();+ expect(createLayer).toHaveBeenCalled();+ });++ it('rebuilds both active and activeB compare granule groups', async () => {+ const makeGranuleGroup = (groupName) => {+ const olLayer = {+ wv: {+ id: `g-${groupName}`,+ def: { id: `g-${groupName}`, type: 'granule' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 0,+ },+ get: jest.fn(),+ };+ const groupCollection = makeCollection([olLayer]);+ return {+ get: jest.fn((k) => (k === 'group' ? groupName : undefined)),+ getLayers: () => groupCollection,+ };+ };++ const activeGroup = makeGranuleGroup('active');+ const activeBGroup = makeGranuleGroup('activeB');+ const allGroupsCollection = makeCollection([activeGroup, activeBGroup]);++ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const createLayer = jest.fn().mockResolvedValue({ wv: { id: 'g', def: { id: 'g' } } });++ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => allGroupsCollection };++ renderComponent(props);+ await flushPromises();+ expect(createLayer).toHaveBeenCalledTimes(2);+ });++ it('skips compare group not found in allGroups', async () => {+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const createLayer = jest.fn().mockResolvedValue({ wv: {} });+ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => makeCollection([]) };++ renderComponent(props);+ await flushPromises();+ expect(createLayer).not.toHaveBeenCalled();+ });++ it('waits for processingPromise before rebuilding compare granules', async () => {+ let resolveFn;+ const processingPromise = new Promise((resolve) => { resolveFn = resolve; });++ const olLayer = {+ wv: {+ id: 'g-1',+ def: { id: 'g-1', type: 'granule' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 0,+ },+ get: jest.fn(),+ };+ const groupCollection = makeCollection([olLayer]);+ const groupLayer = {+ get: jest.fn((k) => (k === 'group' ? 'active' : undefined)),+ getLayers: () => groupCollection,+ };+ const allGroupsCollection = makeCollection([groupLayer]);++ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const createLayer = jest.fn().mockResolvedValue({ wv: { id: 'g-1', def: { id: 'g-1' } } });++ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.processingPromise = processingPromise;+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => allGroupsCollection };++ renderComponent(props);+ expect(createLayer).not.toHaveBeenCalled();+ resolveFn();+ await flushPromises();+ expect(createLayer).toHaveBeenCalled();+ });++ it('skips compare rebuild when stale after processingPromise resolves', async () => {+ let resolveFn;+ const processingPromise = new Promise((resolve) => { resolveFn = resolve; });++ const olLayer = {+ wv: {+ id: 'g-1',+ def: { id: 'g-1', type: 'granule' },+ pendingCmrRebuild: true,+ cmrRebuildAttempts: 0,+ },+ get: jest.fn(),+ };+ const groupCollection = makeCollection([olLayer]);+ const groupLayer = {+ get: jest.fn((k) => (k === 'group' ? 'active' : undefined)),+ getLayers: () => groupCollection,+ };+ const allGroupsCollection = makeCollection([groupLayer]);++ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const createLayer = jest.fn().mockResolvedValue({ wv: {} });+ const props = buildProps({+ action: { type: layerConstants.ADD_GRANULE_DATE_RANGES },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.processingPromise = processingPromise;+ props.ui.cmrRebuildSeq = 0;+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => allGroupsCollection };++ renderComponent(props);+ props.ui.cmrRebuildSeq = 99;+ resolveFn();+ await flushPromises();+ expect(createLayer).not.toHaveBeenCalled();+ });+ });++ describe('compare mode — updateCompareLayer', () => {+ const buildCompareProps = (layerDef) => {+ const mapLayer = makeLayer(layerDef.id, layerDef.type, layerDef.period);+ const collection = makeCollection([mapLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([layerDef]);+ getActiveLayers.mockReturnValue([]);+ getGranuleCount.mockReturnValue(20);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const freshOlLayer = { wv: { id: layerDef.id, def: { id: layerDef.id } }, get: jest.fn() };+ const activeGroupCollection = makeCollection([freshOlLayer]);+ const activeGroupLayer = {+ get: jest.fn((k) => (k === 'group' ? 'active' : undefined)),+ getLayers: () => activeGroupCollection,+ };+ const allGroupsCollection = makeCollection([activeGroupLayer]);++ const createdLayer = { wv: { id: layerDef.id, def: { id: layerDef.id } } };+ const createLayer = jest.fn().mockResolvedValue(createdLayer);++ const props = buildProps({+ action: { type: dateConstants.SELECT_DATE, outOfStep: false },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => allGroupsCollection };++ return {+ props, createdLayer, createLayer, activeGroupCollection,+ };+ };++ it('calls createLayer for a temporal tile compare layer', async () => {+ const { props, createLayer } = buildCompareProps(makeDef('layer-1', 'tile', 'daily'));+ renderComponent(props);+ await flushPromises();+ expect(createLayer).toHaveBeenCalled();+ });++ it('calls createLayer for a granule compare layer', async () => {+ const { props, createLayer } = buildCompareProps(makeDef('granule-1', 'granule', 'daily'));+ renderComponent(props);+ await flushPromises();+ expect(createLayer).toHaveBeenCalled();+ });++ it('calls compareMapUi.update after successfully setting the layer', async () => {+ const { props } = buildCompareProps(makeDef('layer-1', 'tile', 'daily'));+ renderComponent(props);+ await flushPromises();+ expect(props.compareMapUi.update).toHaveBeenCalledWith('active');+ });++ it('uses selectedB date key when group is activeB', async () => {+ const layerDef = makeDef('layer-1', 'tile', 'daily');+ const mapLayer = makeLayer('layer-1', 'tile', 'daily');+ const collection = makeCollection([mapLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([layerDef]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const freshOlLayer = { wv: { id: 'layer-1', def: { id: 'layer-1' } }, get: jest.fn() };+ const activeBGroupCollection = makeCollection([freshOlLayer]);+ const activeBGroupLayer = {+ get: jest.fn((k) => (k === 'group' ? 'activeB' : undefined)),+ getLayers: () => activeBGroupCollection,+ };+ const allGroupsCollection = makeCollection([activeBGroupLayer]);++ const createLayer = jest.fn().mockResolvedValue({ wv: { id: 'layer-1', def: { id: 'layer-1' } } });++ const props = buildProps({+ action: { type: dateConstants.SELECT_DATE, outOfStep: false },+ isCompareActive: true,+ activeString: 'activeB',+ });+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => allGroupsCollection };++ renderComponent(props);+ await flushPromises();+ expect(getSelectedDate).toHaveBeenCalledWith(props.dateCompareState, 'selectedB');+ });++ it('skips setAt when freshIndex is -1 after await', async () => {+ const layerDef = makeDef('layer-1', 'tile', 'daily');+ const mapLayer = makeLayer('layer-1', 'tile', 'daily');+ const collection = makeCollection([mapLayer]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([layerDef]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const emptyGroupCollection = makeCollection([]);+ const activeGroupLayer = {+ get: jest.fn((k) => (k === 'group' ? 'active' : undefined)),+ getLayers: () => emptyGroupCollection,+ };+ const allGroupsCollection = makeCollection([activeGroupLayer]);++ const createLayer = jest.fn().mockResolvedValue({ wv: { id: 'layer-1', def: { id: 'layer-1' } } });++ const props = buildProps({+ action: { type: dateConstants.SELECT_DATE, outOfStep: false },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.createLayer = createLayer;+ props.ui.selected = { getLayers: () => allGroupsCollection };++ renderComponent(props);+ await flushPromises();+ expect(emptyGroupCollection.setAt).not.toHaveBeenCalled();+ });++ it('skips setAt when existing layer has a higher appliedSeq', async () => {+ const { props, activeGroupCollection } = buildCompareProps(makeDef('layer-1', 'tile', 'daily'));+ const existingLayer = activeGroupCollection.getArray()[0];+ existingLayer.wv = { ...existingLayer.wv, appliedSeq: 9999 };++ renderComponent(props);+ await flushPromises();+ expect(activeGroupCollection.setAt).not.toHaveBeenCalled();+ });++ it('does not call compareMapUi.update when ui.selected is null and layers collection is empty', async () => {+ const layerDef = makeDef('layer-1', 'tile', 'daily');+ const collection = makeCollection([]);+ getActiveLayerGroup.mockReturnValue({ getLayers: () => collection });+ getAllActiveLayers.mockReturnValue([layerDef]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));++ const props = buildProps({+ action: { type: dateConstants.SELECT_DATE, outOfStep: false },+ isCompareActive: true,+ activeString: 'active',+ });+ props.ui.selected = null;++ renderComponent(props);+ await flushPromises();+ expect(props.compareMapUi.update).not.toHaveBeenCalled();+ });+ });});diff --git a/web/js/mapUI/components/update-opacity/updateOpacity.test.js b/web/js/mapUI/components/update-opacity/updateOpacity.test.jsindex a9e8744a2..fd71eebcf 100644--- a/web/js/mapUI/components/update-opacity/updateOpacity.test.js+++ b/web/js/mapUI/components/update-opacity/updateOpacity.test.js@@ -1,3 +1,322 @@-test('updateOpacity mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render } from '@testing-library/react';+import * as layerConstants from '../../../modules/layers/constants';+import { getActiveLayers } from '../../../modules/layers/selectors';+jest.mock('react-redux', () => ({+ ...jest.requireActual('react-redux'),+ connect: () => (Component) => Component,+}));++jest.mock('../../../modules/layers/selectors');++const UpdateOpacity = require('./updateOpacity').default;++const buildUiSelected = (layers = []) => ({+ selected: {+ getLayers: () => ({+ getArray: () => layers,+ }),+ },+});++const buildProps = (overrides = {}) => ({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'layer-1', opacity: 0.5 },+ activeLayers: [{ id: 'layer-1', type: 'tile' }],+ activeString: 'active',+ compare: {},+ findLayer: jest.fn(),+ isCompareActive: false,+ ui: buildUiSelected(),+ updateLayerVisibilities: jest.fn(),+ ...overrides,+});++const renderComponent = (props) => render(<UpdateOpacity {...props} />);++describe('UpdateOpacity', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ getActiveLayers.mockReturnValue([]);+ });++ describe('renders null', () => {+ it('returns null from render', () => {+ const props = buildProps();+ const { container } = renderComponent(props);+ expect(container.firstChild).toBeNull();+ });+ });++ describe('useEffect — non UPDATE_OPACITY action', () => {+ it('does not call updateLayerVisibilities for an unrelated action type', () => {+ const props = buildProps({ action: { type: 'SOME_OTHER_ACTION' } });+ renderComponent(props);+ expect(props.updateLayerVisibilities).not.toHaveBeenCalled();+ });+ });++ describe('updateOpacity — layer not found in activeLayers', () => {+ it('calls updateLayerVisibilities and returns early when def is not found', () => {+ const props = buildProps({+ activeLayers: [],+ action: { type: layerConstants.UPDATE_OPACITY, id: 'missing-layer', opacity: 0.5 },+ });+ renderComponent(props);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ expect(props.findLayer).not.toHaveBeenCalled();+ });+ });++ describe('updateOpacity — non-granule layer', () => {+ it('calls setOpacity on the layerGroup', () => {+ const layerGroup = { setOpacity: jest.fn() };+ const findLayer = jest.fn().mockReturnValue(layerGroup);+ const props = buildProps({ findLayer });+ renderComponent(props);+ expect(findLayer).toHaveBeenCalledWith({ id: 'layer-1', type: 'tile' }, 'active');+ expect(layerGroup.setOpacity).toHaveBeenCalledWith(0.5);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('also calls setOpacity on each sublayer when getLayersArray is available', () => {+ const sublayer1 = { setOpacity: jest.fn() };+ const sublayer2 = { setOpacity: jest.fn() };+ const layerGroup = {+ setOpacity: jest.fn(),+ getLayersArray: jest.fn().mockReturnValue([sublayer1, sublayer2]),+ };+ const findLayer = jest.fn().mockReturnValue(layerGroup);+ const props = buildProps({ findLayer });+ renderComponent(props);+ expect(sublayer1.setOpacity).toHaveBeenCalledWith(0.5);+ expect(sublayer2.setOpacity).toHaveBeenCalledWith(0.5);+ });++ it('calls updateLayerVisibilities and returns early when findLayer returns null', () => {+ const findLayer = jest.fn().mockReturnValue(null);+ const props = buildProps({ findLayer });+ renderComponent(props);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('calls updateLayerVisibilities and returns early when layerGroup has no setOpacity', () => {+ const layerGroup = {};+ const findLayer = jest.fn().mockReturnValue(layerGroup);+ const props = buildProps({ findLayer });+ renderComponent(props);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });+ });++ describe('updateOpacity — granule layer, non-compare mode', () => {+ it('calls setOpacity on a matching ol-layer when group and id match', () => {+ const granuleDef = { id: 'granule-1', type: 'granule' };+ const granuleLayer = {+ className_: 'ol-layer',+ wv: { id: 'granule-1', group: 'active' },+ setOpacity: jest.fn(),+ };+ const ui = buildUiSelected([granuleLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.7 },+ activeLayers: [granuleDef],+ activeString: 'active',+ compare: {},+ isCompareActive: false,+ ui,+ });+ renderComponent(props);+ expect(granuleLayer.setOpacity).toHaveBeenCalledWith(0.7);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('does not call setOpacity when the group does not match', () => {+ const granuleDef = { id: 'granule-1', type: 'granule' };+ const granuleLayer = {+ className_: 'ol-layer',+ wv: { id: 'granule-1', group: 'activeB' },+ setOpacity: jest.fn(),+ };+ const ui = buildUiSelected([granuleLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.7 },+ activeLayers: [granuleDef],+ activeString: 'active',+ isCompareActive: false,+ ui,+ });+ renderComponent(props);+ expect(granuleLayer.setOpacity).not.toHaveBeenCalled();+ });++ it('does not call setOpacity when the id does not match', () => {+ const granuleDef = { id: 'granule-1', type: 'granule' };+ const granuleLayer = {+ className_: 'ol-layer',+ wv: { id: 'different-id', group: 'active' },+ setOpacity: jest.fn(),+ };+ const ui = buildUiSelected([granuleLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.7 },+ activeLayers: [granuleDef],+ activeString: 'active',+ isCompareActive: false,+ ui,+ });+ renderComponent(props);+ expect(granuleLayer.setOpacity).not.toHaveBeenCalled();+ });++ it('skips layers that are not ol-layer class', () => {+ const granuleDef = { id: 'granule-1', type: 'granule' };+ const nonOlLayer = {+ className_: 'other-class',+ wv: { id: 'granule-1', group: 'active' },+ setOpacity: jest.fn(),+ };+ const ui = buildUiSelected([nonOlLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.7 },+ activeLayers: [granuleDef],+ activeString: 'active',+ isCompareActive: false,+ ui,+ });+ renderComponent(props);+ expect(nonOlLayer.setOpacity).not.toHaveBeenCalled();+ });+ });++ describe('updateOpacity — granule layer, compare mode', () => {+ const buildCompareGranuleLayer = ({+ compareLayerGroupId,+ tileLayerId,+ tileLayerGroup,+ compareSetOpacity = jest.fn(),+ }) => {+ const tileLayer = [{ wv: { id: tileLayerId, group: tileLayerGroup } }];+ const compareLayerGroup = {+ wv: { id: compareLayerGroupId },+ getLayers: () => ({ getArray: () => tileLayer }),+ setOpacity: compareSetOpacity,+ };+ const olLayer = {+ className_: 'ol-layer',+ getLayers: () => ({ getArray: () => [compareLayerGroup] }),+ };+ return { olLayer, compareLayerGroup, tileLayer };+ };++ it('calls setOpacity on compareLayerGroup when tileLayer id and group match', () => {+ const compareSetOpacity = jest.fn();+ const { olLayer } = buildCompareGranuleLayer({+ compareLayerGroupId: 'granule-1',+ tileLayerId: 'granule-1',+ tileLayerGroup: 'active',+ compareSetOpacity,+ });++ const ui = buildUiSelected([olLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.4 },+ activeLayers: [{ id: 'granule-1', type: 'granule' }],+ activeString: 'active',+ compare: { active: true },+ isCompareActive: true,+ ui,+ });+ renderComponent(props);+ expect(compareSetOpacity).toHaveBeenCalledWith(0.4);+ expect(props.updateLayerVisibilities).toHaveBeenCalledTimes(1);+ });++ it('does not call setOpacity when compareLayerGroup id does not match the target id', () => {+ const compareSetOpacity = jest.fn();+ const { olLayer } = buildCompareGranuleLayer({+ compareLayerGroupId: 'different-granule',+ tileLayerId: 'granule-1',+ tileLayerGroup: 'active',+ compareSetOpacity,+ });++ const ui = buildUiSelected([olLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.4 },+ activeLayers: [{ id: 'granule-1', type: 'granule' }],+ activeString: 'active',+ compare: { active: true },+ isCompareActive: true,+ ui,+ });+ renderComponent(props);+ expect(compareSetOpacity).not.toHaveBeenCalled();+ });++ it('does not call setOpacity when tileLayer group does not match activeString', () => {+ const compareSetOpacity = jest.fn();+ const { olLayer } = buildCompareGranuleLayer({+ compareLayerGroupId: 'granule-1',+ tileLayerId: 'granule-1',+ tileLayerGroup: 'activeB',+ compareSetOpacity,+ });++ const ui = buildUiSelected([olLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.4 },+ activeLayers: [{ id: 'granule-1', type: 'granule' }],+ activeString: 'active',+ compare: { active: true },+ isCompareActive: true,+ ui,+ });+ renderComponent(props);+ expect(compareSetOpacity).not.toHaveBeenCalled();+ });++ it('does not call setOpacity when tileLayer id does not match', () => {+ const compareSetOpacity = jest.fn();+ const { olLayer } = buildCompareGranuleLayer({+ compareLayerGroupId: 'granule-1',+ tileLayerId: 'different-tile-id',+ tileLayerGroup: 'active',+ compareSetOpacity,+ });++ const ui = buildUiSelected([olLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.4 },+ activeLayers: [{ id: 'granule-1', type: 'granule' }],+ activeString: 'active',+ compare: { active: true },+ isCompareActive: true,+ ui,+ });+ renderComponent(props);+ expect(compareSetOpacity).not.toHaveBeenCalled();+ });++ it('skips compare path when compareArg is falsy even if isCompareActive is true', () => {+ const compareSetOpacity = jest.fn();+ const granuleLayer = {+ className_: 'ol-layer',+ wv: { id: 'granule-1', group: 'active' },+ setOpacity: jest.fn(),+ };+ const ui = buildUiSelected([granuleLayer]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_OPACITY, id: 'granule-1', opacity: 0.3 },+ activeLayers: [{ id: 'granule-1', type: 'granule' }],+ activeString: 'active',+ compare: null,+ isCompareActive: true,+ ui,+ });+ renderComponent(props);+ expect(compareSetOpacity).not.toHaveBeenCalled();+ expect(granuleLayer.setOpacity).toHaveBeenCalledWith(0.3);+ });+ });});diff --git a/web/js/mapUI/components/update-projection/updateProjection.test.js b/web/js/mapUI/components/update-projection/updateProjection.test.jsindex 4b8f3145d..290475e22 100644--- a/web/js/mapUI/components/update-projection/updateProjection.test.js+++ b/web/js/mapUI/components/update-projection/updateProjection.test.js@@ -1,3 +1,997 @@-test('updateProjection mapUI test', () => {+/* eslint-disable react/jsx-props-no-spreading */+import { render, act } from '@testing-library/react';+import * as layerConstants from '../../../modules/layers/constants';+import * as compareConstants from '../../../modules/compare/constants';+import * as paletteConstants from '../../../modules/palettes/constants';+import * as vectorStyleConstants from '../../../modules/vector-styles/constants';+import { LOCATION_POP_ACTION } from '../../../redux-location-state-customs';+import { EXIT_ANIMATION, STOP_ANIMATION } from '../../../modules/animation/constants';+import { SET_SCREEN_INFO } from '../../../modules/screen-size/constants';+import { getLayers, getActiveLayers } from '../../../modules/layers/selectors';+import { getSelectedDate } from '../../../modules/date/selectors';+import { getLeadingExtent } from '../../../modules/map/util';+import { fly } from '../../../map/util';+import { loadLayersWithSlots } from '../../util/util';+import util from '../../../util/util';+jest.mock('react-redux', () => ({+ ...jest.requireActual('react-redux'),+ connect: () => (Component) => Component,+}));++jest.mock('../../../modules/layers/selectors');+jest.mock('../../../modules/date/selectors');+jest.mock('../../../modules/map/util');+jest.mock('../../../map/util');+jest.mock('../../util/util');+jest.mock('../../../util/util', () => ({ fromQueryString: jest.fn() }));+jest.mock('ol/layer/Group', () => jest.fn().mockImplementation((opts) => opts));+jest.mock('../../../modules/map/actions', () => ({+ fitToLeadingExtent: jest.fn(),+ updateMapUI: jest.fn(),+}));+jest.mock('../../../modules/palettes/actions', () => ({+ requestPalette: jest.fn(),+}));+jest.mock('../../../modules/layers/actions', () => ({+ addTEMPODateRanges: jest.fn(),+}));++/**+ * Replicate usePrevious so it works in the JSDOM/Jest environment without+ * real React batching concerns.+ */+jest.mock('../../../util/customHooks', () => (val) => {+ const { useRef, useEffect } = require('react');+ const ref = useRef(val);+ const prev = ref.current;+ useEffect(() => {+ ref.current = val;+ });+ return prev;+});++// Import the component AFTER all mocks are registered+const UpdateProjection = require('./updateProjection').default;++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++/** Flush all pending microtasks / resolved promises. */+const flushPromises = () => new Promise((resolve) => { Promise.resolve().then(resolve); });++/**+ * Build a minimal, fully-valid OpenLayers-like map object.+ * @param {string} targetId - unique DOM id returned by getTarget(), used by+ * hideMap/showMap. Give different maps different ids so the two calls+ * don't stomp on each other.+ */+const makeMapObj = (targetId = 'map-target') => {+ const mockView = {+ fit: jest.fn(),+ setRotation: jest.fn(),+ getRotation: jest.fn().mockReturnValue(0),+ calculateExtent: jest.fn().mockReturnValue([0, 0, 10, 10]),+ getResolutionForExtent: jest.fn().mockReturnValue(1),+ getZoomForResolution: jest.fn().mockReturnValue(5),+ };+ return {+ setLayers: jest.fn(),+ getLayers: jest.fn().mockReturnValue({ getArray: jest.fn().mockReturnValue([]) }),+ getView: jest.fn().mockReturnValue(mockView),+ getTarget: jest.fn().mockReturnValue(targetId),+ getSize: jest.fn().mockReturnValue([800, 600]),+ updateSize: jest.fn(),+ setCenter: jest.fn(),+ addControl: jest.fn(),+ removeControl: jest.fn(),+ center: null,+ wv: { scaleImperial: {}, scaleMetric: {} },+ };+};++const buildProps = (overrides = {}) => {+ const geographicMap = makeMapObj('map-geographic');+ const arcticMap = makeMapObj('map-arctic');+ const webmercMap = makeMapObj('map-webmerc');++ const ui = {+ selected: geographicMap,+ proj: {+ geographic: geographicMap,+ arctic: arcticMap,+ webmerc: webmercMap,+ },+ createLayer: jest.fn().mockResolvedValue({ wv: {} }),+ cache: { clear: jest.fn() },+ processingPromise: null,+ };++ return {+ action: { type: 'UNKNOWN_ACTION' },+ activeLayers: [],+ compare: {+ active: false,+ activeString: 'active',+ isCompareA: true,+ mode: 'swipe',+ },+ compareMode: 'swipe',+ compareMapUi: {+ active: false,+ destroy: jest.fn(),+ create: jest.fn(),+ update: jest.fn(),+ },+ config: {+ features: { compare: true },+ pageLoadTime: new Date(),+ },+ dateCompareState: {},+ fitToLeadingExtent: jest.fn(),+ getGranuleOptions: jest.fn().mockReturnValue({}),+ layerCreationQueue: {},+ isKioskModeActive: false,+ isMobile: false,+ layerState: {},+ map: {},+ models: { map: {} },+ preloadForCompareMode: jest.fn(),+ // Both shapes used by the component:+ // updateProjection() → proj.id+ // start branch → proj.selected.id+ proj: { id: 'geographic', selected: { id: 'geographic' } },+ projectionTrigger: 0,+ updateExtent: jest.fn(),+ updateLayerVisibilities: jest.fn(),+ updateMapUI: jest.fn(),+ ui,+ renderedPalettes: {},+ requestPalette: jest.fn(),+ addTEMPODateRanges: jest.fn(),+ ...overrides,+ };+};++const renderComponent = (props) => render(<UpdateProjection {...props} />);++// ---------------------------------------------------------------------------+// Test suites+// ---------------------------------------------------------------------------++describe('UpdateProjection', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ getLayers.mockReturnValue([]);+ getActiveLayers.mockReturnValue([]);+ getSelectedDate.mockReturnValue(new Date('2023-01-01'));+ getLeadingExtent.mockReturnValue(null);+ fly.mockReturnValue(undefined);+ loadLayersWithSlots.mockResolvedValue(undefined);+ util.fromQueryString.mockReturnValue({});+ });++ // ── Rendering ─────────────────────────────────────────────────────────────++ describe('renders null', () => {+ it('returns null — component mounts without visible DOM output', () => {+ const { container } = renderComponent(buildProps());+ expect(container.firstChild).toBeNull();+ });+ });++ // ── actionSwitch — unknown / default ──────────────────────────────────────++ describe('actionSwitch — default / unknown action', () => {+ it('does not call any side-effect functions for an unknown action', () => {+ const props = buildProps({ action: { type: 'UNKNOWN' } });+ renderComponent(props);+ expect(props.updateLayerVisibilities).not.toHaveBeenCalled();+ expect(props.preloadForCompareMode).not.toHaveBeenCalled();+ });+ });++ // ── actionSwitch — STOP_ANIMATION / EXIT_ANIMATION ────────────────────────++ describe('actionSwitch — STOP_ANIMATION / EXIT_ANIMATION', () => {+ it('does not call reloadLayers when there are no vector layers', async () => {+ const props = buildProps({+ action: { type: STOP_ANIMATION },+ activeLayers: [{ type: 'tile', id: 'tile-1' }],+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ });++ it('calls reloadLayers when vector layers are present (STOP_ANIMATION)', async () => {+ getLayers.mockReturnValue([{ id: 'vec-1' }]);+ const props = buildProps({+ action: { type: STOP_ANIMATION },+ activeLayers: [{ type: 'vector', id: 'vec-1' }],+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });++ it('handles EXIT_ANIMATION the same as STOP_ANIMATION with vector layers', async () => {+ getLayers.mockReturnValue([{ id: 'vec-1' }]);+ const props = buildProps({+ action: { type: EXIT_ANIMATION },+ activeLayers: [{ type: 'vector', id: 'vec-1' }],+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });++ it('waits for an existing processingPromise before reloading', async () => {+ getLayers.mockReturnValue([{ id: 'vec-1' }]);+ let resolveFn;+ const processingPromise = new Promise((resolve) => { resolveFn = resolve; });+ const props = buildProps({+ action: { type: STOP_ANIMATION },+ activeLayers: [{ type: 'vector', id: 'vec-1' }],+ });+ props.ui.processingPromise = processingPromise;+ renderComponent(props);+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ resolveFn();+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });++ it('still reloads even when the existing processingPromise rejects', async () => {+ getLayers.mockReturnValue([{ id: 'vec-1' }]);+ const props = buildProps({+ action: { type: STOP_ANIMATION },+ activeLayers: [{ type: 'vector', id: 'vec-1' }],+ });+ props.ui.processingPromise = Promise.reject(new Error('boom'));+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });+ });++ // ── actionSwitch — LOCATION_POP_ACTION ────────────────────────────────────++ describe('actionSwitch — LOCATION_POP_ACTION', () => {+ beforeEach(() => { jest.useFakeTimers(); });+ afterEach(() => { jest.useRealTimers(); });++ it('calls updateExtent after the 200 ms timeout', async () => {+ util.fromQueryString.mockReturnValue({});+ const props = buildProps({+ action: { type: LOCATION_POP_ACTION, payload: { search: '' } },+ map: {},+ });+ renderComponent(props);+ jest.advanceTimersByTime(200);+ await act(async () => { await flushPromises(); });+ expect(props.updateExtent).toHaveBeenCalled();+ });++ it('calls flyToNewExtent when state has v, no e, and an extent exists', async () => {+ util.fromQueryString.mockReturnValue({ v: '0,0,10,10' });+ const props = buildProps({+ action: { type: LOCATION_POP_ACTION, payload: { search: '' } },+ map: { extent: [0, 0, 10, 10] },+ });+ renderComponent(props);+ jest.advanceTimersByTime(200);+ await act(async () => { await flushPromises(); });+ expect(fly).toHaveBeenCalled();+ });++ it('does NOT call flyToNewExtent when e is present in parsed state', async () => {+ util.fromQueryString.mockReturnValue({ v: '0,0,10,10', e: 'event-id' });+ const props = buildProps({+ action: { type: LOCATION_POP_ACTION, payload: { search: '' } },+ map: { extent: [0, 0, 10, 10] },+ });+ renderComponent(props);+ jest.advanceTimersByTime(200);+ await act(async () => { await flushPromises(); });+ expect(fly).not.toHaveBeenCalled();+ });++ it('does NOT call flyToNewExtent when no extent is in map state', async () => {+ util.fromQueryString.mockReturnValue({ v: '0,0,10,10' });+ const props = buildProps({+ action: { type: LOCATION_POP_ACTION, payload: { search: '' } },+ map: {},+ });+ renderComponent(props);+ jest.advanceTimersByTime(200);+ await act(async () => { await flushPromises(); });+ expect(fly).not.toHaveBeenCalled();+ });++ it('uses map.rotation as the rotate argument when set', async () => {+ util.fromQueryString.mockReturnValue({ v: '0,0,10,10' });+ const props = buildProps({+ action: { type: LOCATION_POP_ACTION, payload: { search: '' } },+ map: { extent: [0, 0, 10, 10], rotation: 1.5 },+ });+ renderComponent(props);+ jest.advanceTimersByTime(200);+ await act(async () => { await flushPromises(); });+ expect(fly).toHaveBeenCalledWith(+ expect.anything(),+ expect.anything(),+ expect.anything(),+ expect.anything(),+ expect.anything(),+ 1.5,+ );+ });+ });++ // ── actionSwitch — UPDATE_GRANULE_LAYER_OPTIONS ───────────────────────────++ describe('actionSwitch — UPDATE_GRANULE_LAYER_OPTIONS', () => {+ it('calls reloadLayers (loadLayersWithSlots) with granule options', async () => {+ getLayers.mockReturnValue([{ id: 'granule-1' }]);+ const props = buildProps({+ action: { type: layerConstants.UPDATE_GRANULE_LAYER_OPTIONS, id: 'granule-1' },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });+ });++ // ── actionSwitch — RESET_GRANULE_LAYER_OPTIONS ────────────────────────────++ describe('actionSwitch — RESET_GRANULE_LAYER_OPTIONS', () => {+ it('calls reloadLayers with reset granule options', async () => {+ getLayers.mockReturnValue([{ id: 'granule-1' }]);+ const props = buildProps({+ action: { type: layerConstants.RESET_GRANULE_LAYER_OPTIONS, id: 'granule-1' },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });+ });++ // ── actionSwitch — compareConstants.CHANGE_STATE ─────────────────────────++ describe('actionSwitch — CHANGE_STATE (compare)', () => {+ it('calls reloadLayers when compareMode is spy', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({+ action: { type: compareConstants.CHANGE_STATE },+ compareMode: 'spy',+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });++ it('does NOT call reloadLayers when compareMode is not spy', async () => {+ const props = buildProps({+ action: { type: compareConstants.CHANGE_STATE },+ compareMode: 'swipe',+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ });+ });++ // ── actionSwitch — REORDER / TOGGLE_ON_OFF / CHANGE_MODE ─────────────────++ describe('actionSwitch — REORDER_LAYERS / REORDER_OVERLAY_GROUPS / TOGGLE_ON_OFF / CHANGE_MODE', () => {+ [+ layerConstants.REORDER_LAYERS,+ layerConstants.REORDER_OVERLAY_GROUPS,+ compareConstants.TOGGLE_ON_OFF,+ compareConstants.CHANGE_MODE,+ ].forEach((type) => {+ it(`calls reloadLayers AND preloadForCompareMode for ${type}`, async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({ action: { type } });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ expect(props.preloadForCompareMode).toHaveBeenCalled();+ });+ });+ });++ // ── actionSwitch — TOGGLE_OVERLAY_GROUPS ─────────────────────────────────++ describe('actionSwitch — TOGGLE_OVERLAY_GROUPS', () => {+ it('calls reloadLayers', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS } });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });+ });++ // ── actionSwitch — palette / event actions (setTimeout 100 ms) ────────────++ describe('actionSwitch — palette and layer-event actions (setTimeout 100 ms)', () => {+ beforeEach(() => { jest.useFakeTimers(); });+ afterEach(() => { jest.useRealTimers(); });++ [+ paletteConstants.SET_THRESHOLD_RANGE_AND_SQUASH,+ paletteConstants.SET_CUSTOM,+ paletteConstants.SET_DISABLED_CLASSIFICATION,+ paletteConstants.CLEAR_CUSTOM,+ layerConstants.ADD_LAYERS_FOR_EVENT,+ ].forEach((type) => {+ it(`does not fire immediately, fires after 100 ms for ${type}`, async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({ action: { type } });+ renderComponent(props);+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ jest.advanceTimersByTime(100);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });+ });+ });++ // ── actionSwitch — vector-style / screen-info actions (onResize) ──────────++ describe('actionSwitch — vector style and screen-info actions (onResize)', () => {+ [+ vectorStyleConstants.SET_FILTER_RANGE,+ vectorStyleConstants.SET_VECTORSTYLE,+ vectorStyleConstants.CLEAR_VECTORSTYLE,+ SET_SCREEN_INFO,+ ].forEach((type) => {+ it(`calls addControl on non-mobile for ${type}`, () => {+ const props = buildProps({ action: { type }, isMobile: false });+ renderComponent(props);+ expect(props.ui.selected.addControl).toHaveBeenCalled();+ });++ it(`calls removeControl on mobile for ${type}`, () => {+ const props = buildProps({ action: { type }, isMobile: true });+ renderComponent(props);+ expect(props.ui.selected.removeControl).toHaveBeenCalled();+ });+ });+ });++ // ── reloadLayers — non-compare mode ──────────────────────────────────────++ describe('reloadLayers — non-compare mode', () => {+ it('destroys compareMapUi when it was active but compare is now inactive', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ compare: {+ active: false, activeString: 'active', isCompareA: true, mode: 'swipe',+ },+ compareMapUi: { active: true, destroy: jest.fn(), create: jest.fn() },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.compareMapUi.destroy).toHaveBeenCalled();+ });++ it('does NOT destroy compareMapUi when it is already inactive', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ compareMapUi: { active: false, destroy: jest.fn(), create: jest.fn() },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.compareMapUi.destroy).not.toHaveBeenCalled();+ });++ it('clears the cache when saveCache is falsy (TOGGLE_OVERLAY_GROUPS)', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS } });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.ui.cache.clear).toHaveBeenCalled();+ });++ it('calls setLayers([]) on ui.selected (clearLayers)', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS } });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.ui.selected.setLayers).toHaveBeenCalledWith([]);+ });++ it('passes updateLayerVisibilities into loadLayersWithSlots', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS } });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ const callArgs = loadLayersWithSlots.mock.calls[0][0];+ expect(callArgs.updateLayerVisibilities).toBe(props.updateLayerVisibilities);+ });++ it('passes TEMPO tempoCallback when layer id includes TEMPO', async () => {+ getLayers.mockReturnValue([{ id: 'TEMPO_NO2_Vertical-Column_Daily_v03' }]);+ const props = buildProps({ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS } });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ const callArgs = loadLayersWithSlots.mock.calls[0][0];+ const options = callArgs.getLayerOptions({ id: 'TEMPO_NO2_Vertical-Column_Daily_v03' });+ expect(options.tempoCallback).toBe(props.addTEMPODateRanges);+ });++ it('does NOT attach tempoCallback for non-TEMPO layers', async () => {+ getLayers.mockReturnValue([{ id: 'regular-layer' }]);+ const props = buildProps({ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS } });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ const callArgs = loadLayersWithSlots.mock.calls[0][0];+ const options = callArgs.getLayerOptions({ id: 'regular-layer' });+ expect(options.tempoCallback).toBeUndefined();+ });++ it('passes the layerCreationQueue when saveCache is false (TOGGLE_OVERLAY_GROUPS)', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const queue = { push: jest.fn() };+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ layerCreationQueue: queue,+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ const callArgs = loadLayersWithSlots.mock.calls[0][0];+ expect(callArgs.queue).toBe(queue);+ });++ it('passes queue as null when called from updateProjection with start=true (saveCache=false → queue used; saveCache=true → null)', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const queue = { push: jest.fn() };+ const initialLayers = [{ id: 'layer-1', type: 'tile' }];+ const props = buildProps({+ activeLayers: initialLayers,+ action: { type: 'UNKNOWN' },+ layerCreationQueue: queue,+ });+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ const updatedLayers = [+ { id: 'layer-1', type: 'tile' },+ { id: 'layer-2', type: 'tile' },+ ];+ rerender(<UpdateProjection {...props} activeLayers={updatedLayers} />);+ await act(async () => { await flushPromises(); });+ const callArgs = loadLayersWithSlots.mock.calls[0][0];+ expect(callArgs.queue).toBeNull();+ });+ });++ // ── reloadLayers — compare mode ───────────────────────────────────────────++ describe('reloadLayers — compare mode', () => {+ it('calls compareMapUi.create when compare is active', async () => {+ getActiveLayers.mockReturnValue([]);+ getLayers.mockReturnValue([]);+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ compare: {+ active: true, activeString: 'active', isCompareA: true, mode: 'swipe',+ },+ config: { features: { compare: true } },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.compareMapUi.create).toHaveBeenCalled();+ });++ it('reverses stateArray when compare is not A and mode is spy', async () => {+ getActiveLayers.mockReturnValue([]);+ getLayers.mockReturnValue([]);+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ compare: {+ active: true, activeString: 'activeB', isCompareA: false, mode: 'spy',+ },+ config: { features: { compare: true } },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.compareMapUi.create).toHaveBeenCalled();+ });++ it('calls requestPalette for compare-group layers that have a palette', async () => {+ getActiveLayers.mockReturnValue([]);+ getLayers.mockReturnValue([{ id: 'pal-layer', palette: true }]);+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ compare: {+ active: true, activeString: 'active', isCompareA: true, mode: 'swipe',+ },+ config: { features: { compare: true } },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.requestPalette).toHaveBeenCalledWith('pal-layer');+ });++ it('attaches tempoCallback for TEMPO layers in compare mode', async () => {+ getActiveLayers.mockReturnValue([]);+ getLayers.mockReturnValue([{ id: 'TEMPO_NO2_Daily_v03' }]);+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ compare: {+ active: true, activeString: 'active', isCompareA: true, mode: 'swipe',+ },+ config: { features: { compare: true } },+ });+ renderComponent(props);+ await act(async () => { await flushPromises(); });+ expect(props.compareMapUi.create).toHaveBeenCalled();+ });++ it('chains onto an in-flight processingPromise in compare mode', async () => {+ getActiveLayers.mockReturnValue([]);+ getLayers.mockReturnValue([]);+ let resolvePrev;+ const prevPromise = new Promise((resolve) => { resolvePrev = resolve; });+ const props = buildProps({+ action: { type: layerConstants.TOGGLE_OVERLAY_GROUPS },+ compare: {+ active: true, activeString: 'active', isCompareA: true, mode: 'swipe',+ },+ config: { features: { compare: true } },+ });+ props.ui.processingPromise = prevPromise;+ renderComponent(props);+ expect(props.compareMapUi.create).not.toHaveBeenCalled();+ resolvePrev();+ await act(async () => { await flushPromises(); });+ expect(props.compareMapUi.create).toHaveBeenCalled();+ });+ });++ // ── updateProjection — projectionTrigger === 0 (no-op) ───────────────────++ describe('projectionTrigger — no-op when 0', () => {+ it('does not call updateMapUI when projectionTrigger is 0', () => {+ const props = buildProps({ projectionTrigger: 0 });+ renderComponent(props);+ expect(props.updateMapUI).not.toHaveBeenCalled();+ });+ });++ // ── updateProjection — with start=true (projectionTrigger === 1) ──────────++ describe('updateProjection — start=true (projectionTrigger === 1)', () => {+ it('sets ui.selected from ui.proj[proj.id]', () => {+ const props = buildProps({ projectionTrigger: 1 });+ renderComponent(props);+ expect(props.ui.selected).toBe(props.ui.proj.geographic);+ });++ it('calls updateMapUI with the ui object', () => {+ const props = buildProps({ projectionTrigger: 1 });+ renderComponent(props);+ expect(props.updateMapUI).toHaveBeenCalledWith(props.ui, expect.any(Number));+ });++ it('calls mapObj.updateSize()', () => {+ const props = buildProps({ projectionTrigger: 1 });+ renderComponent(props);+ expect(props.ui.selected.updateSize).toHaveBeenCalled();+ });++ it('calls updateExtent and onResize (addControl) after projection update', () => {+ const props = buildProps({ projectionTrigger: 1 });+ renderComponent(props);+ expect(props.updateExtent).toHaveBeenCalled();+ expect(props.ui.selected.addControl).toHaveBeenCalled();+ });++ it('fits to models.map.extent when it is set', () => {+ const props = buildProps({+ projectionTrigger: 1,+ models: { map: { extent: [0, 0, 10, 10] } },+ });+ renderComponent(props);+ expect(props.ui.selected.getView().fit).toHaveBeenCalledWith(+ [0, 0, 10, 10],+ expect.objectContaining({ constrainResolution: false }),+ );+ });++ it('uses getLeadingExtent for geographic projection when no models.map.extent', () => {+ getLeadingExtent.mockReturnValue([0, 0, 20, 20]);+ const props = buildProps({+ projectionTrigger: 1,+ models: { map: {} },+ proj: { id: 'geographic', selected: { id: 'geographic' } },+ });+ renderComponent(props);+ expect(props.ui.selected.getView().fit).toHaveBeenCalled();+ });++ it('calls fitToLeadingExtent callback after fit for geographic projection', () => {+ getLeadingExtent.mockReturnValue([0, 0, 20, 20]);+ const props = buildProps({+ projectionTrigger: 1,+ models: { map: {} },+ proj: { id: 'geographic', selected: { id: 'geographic' } },+ });+ renderComponent(props);+ const fitCall = props.ui.selected.getView().fit.mock.calls[0][1];+ fitCall.callback();+ expect(props.fitToLeadingExtent).toHaveBeenCalled();+ });++ it('calls setRotation callback for non-geographic projection when extent exists', () => {+ const props = buildProps({+ projectionTrigger: 1,+ models: { map: { extent: [0, 0, 10, 10], rotation: 0.5 } },+ proj: { id: 'arctic', selected: { id: 'arctic' } },+ });+ renderComponent(props);+ const arcticMap = props.ui.proj.arctic;+ const fitCall = arcticMap.getView().fit.mock.calls[0][1];+ fitCall.callback();+ expect(arcticMap.getView().setRotation).toHaveBeenCalledWith(0.5);+ });++ it('calls setRotation directly (no fit) for non-geographic when no extent but rotation exists', () => {+ getLeadingExtent.mockReturnValue(null);+ const props = buildProps({+ projectionTrigger: 1,+ models: { map: { rotation: 0.5 } },+ proj: { id: 'arctic', selected: { id: 'arctic' } },+ });+ renderComponent(props);+ expect(props.ui.proj.arctic.getView().setRotation).toHaveBeenCalledWith(0.5);+ });++ it('does NOT call setRotation for geographic projection', () => {+ getLeadingExtent.mockReturnValue(null);+ const props = buildProps({+ projectionTrigger: 1,+ models: { map: { rotation: 0.5 } },+ proj: { id: 'geographic', selected: { id: 'geographic' } },+ });+ renderComponent(props);+ expect(props.ui.selected.getView().setRotation).not.toHaveBeenCalled();+ });++ it('restores previousCenter on the map when it is set', () => {+ const props = buildProps({ projectionTrigger: 1 });+ props.ui.proj.geographic.center = [10, 20];+ renderComponent(props);+ expect(props.ui.selected.setCenter).toHaveBeenCalledWith([10, 20]);+ });++ it('hides the OLD map element before switching (hideMap)', () => {+ const oldEl = document.createElement('div');+ oldEl.id = 'map-geographic';+ document.body.appendChild(oldEl);++ const newEl = document.createElement('div');+ newEl.id = 'map-arctic';+ document.body.appendChild(newEl);++ const props = buildProps({+ projectionTrigger: 1,+ proj: { id: 'arctic', selected: { id: 'arctic' } },+ });++ renderComponent(props);++ expect(oldEl.style.display).toBe('none');++ document.body.removeChild(oldEl);+ document.body.removeChild(newEl);+ });++ it('shows the NEW map element after switching (showMap)', () => {+ const oldEl = document.createElement('div');+ oldEl.id = 'map-geographic';+ document.body.appendChild(oldEl);++ const newEl = document.createElement('div');+ newEl.id = 'map-arctic';+ newEl.style.display = 'none';+ document.body.appendChild(newEl);++ const props = buildProps({+ projectionTrigger: 1,+ proj: { id: 'arctic', selected: { id: 'arctic' } },+ });++ renderComponent(props);++ expect(newEl.style.display).toBe('block');++ document.body.removeChild(oldEl);+ document.body.removeChild(newEl);+ });+ });++ // ── updateProjection — without start (projectionTrigger > 1) ─────────────++ describe('updateProjection — start=false (projectionTrigger > 1)', () => {+ it('calls updateExtent and onResize but does NOT call fit', () => {+ const props = buildProps({ projectionTrigger: 2 });+ renderComponent(props);+ expect(props.updateExtent).toHaveBeenCalled();+ expect(props.ui.selected.getView().fit).not.toHaveBeenCalled();+ });++ it('uses current view rotation (not models.map.rotation) when start is false', () => {+ const props = buildProps({+ projectionTrigger: 2,+ proj: { id: 'arctic', selected: { id: 'arctic' } },+ models: { map: { rotation: 99 } },+ });+ props.ui.proj.arctic.getView().getRotation.mockReturnValue(0.3);+ renderComponent(props);+ expect(props.updateMapUI).toHaveBeenCalledWith(props.ui, 0.3);+ });+ });++ // ── renderedPalettes useEffect ────────────────────────────────────────────++ describe('renderedPalettes useEffect', () => {+ it('does NOT reload when palette count stays the same', async () => {+ const props = buildProps({+ renderedPalettes: { palette1: {} },+ action: { type: 'UNKNOWN' },+ });+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ rerender(<UpdateProjection {...props} renderedPalettes={{ palette1: { updated: true } }} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ });++ it('reloads when a new palette is added', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const props = buildProps({+ renderedPalettes: {},+ action: { type: 'UNKNOWN' },+ });+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ rerender(<UpdateProjection {...props} renderedPalettes={{ palette1: {} }} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });++ it('skips reload when ui.selected is falsy', async () => {+ const props = buildProps({+ renderedPalettes: {},+ action: { type: 'UNKNOWN' },+ });+ props.ui.selected = null;+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ rerender(<UpdateProjection {...props} renderedPalettes={{ palette1: {} }} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ });+ });++ // ── activeLayers useEffect ────────────────────────────────────────────────++ describe('activeLayers useEffect', () => {+ it('reloads when a new layer is added (length change)', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }, { id: 'layer-2' }]);+ const initialLayers = [{ id: 'layer-1', type: 'tile' }];+ const props = buildProps({ activeLayers: initialLayers, action: { type: 'UNKNOWN' } });+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ const updatedLayers = [+ { id: 'layer-1', type: 'tile' },+ { id: 'layer-2', type: 'tile' },+ ];+ rerender(<UpdateProjection {...props} activeLayers={updatedLayers} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });++ it('does NOT reload when layer count is unchanged and no new L2 date ranges', async () => {+ const layers = [{ id: 'layer-1', type: 'tile' }];+ const props = buildProps({ activeLayers: layers, action: { type: 'UNKNOWN' } });+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ rerender(<UpdateProjection {...props} activeLayers={[...layers]} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ });++ it('reloads when an L2 layer gains new date ranges (and prev was undefined)', async () => {+ getLayers.mockReturnValue([{ id: 'L2-layer' }]);+ const initialLayers = [{ id: 'L2-layer', granuleDateRanges: undefined }];+ const props = buildProps({ activeLayers: initialLayers, action: { type: 'UNKNOWN' } });+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ const updatedLayers = [{ id: 'L2-layer', granuleDateRanges: ['2023-01-01'] }];+ rerender(<UpdateProjection {...props} activeLayers={updatedLayers} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).toHaveBeenCalled();+ });++ it('skips reload when ui.selected is falsy', async () => {+ const props = buildProps({ activeLayers: [], action: { type: 'UNKNOWN' } });+ props.ui.selected = null;+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ rerender(<UpdateProjection {...props} activeLayers={[{ id: 'new-layer', type: 'tile' }]} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ });++ it('skips reload on A↔B tab switch (activeString change while compare is active)', async () => {+ getLayers.mockReturnValue([{ id: 'layer-1' }]);+ const initialLayers = [{ id: 'layer-1', type: 'tile' }];+ const compare = {+ active: true, activeString: 'active', isCompareA: true, mode: 'swipe',+ };+ const props = buildProps({+ activeLayers: initialLayers,+ compare,+ action: { type: 'UNKNOWN' },+ });+ const { rerender } = renderComponent(props);+ await act(async () => { await flushPromises(); });+ jest.clearAllMocks();+ loadLayersWithSlots.mockResolvedValue(undefined);+ const updatedCompare = { ...compare, activeString: 'activeB' };+ rerender(<UpdateProjection {...props} compare={updatedCompare} />);+ await act(async () => { await flushPromises(); });+ expect(loadLayersWithSlots).not.toHaveBeenCalled();+ });+ });++ // ── flyToNewExtent ────────────────────────────────────────────────────────++ describe('flyToNewExtent (via LOCATION_POP_ACTION)', () => {+ beforeEach(() => { jest.useFakeTimers(); });+ afterEach(() => { jest.useRealTimers(); });++ it('computes the midpoint coordinate correctly and calls fly', async () => {+ util.fromQueryString.mockReturnValue({ v: '0,0,10,10' });+ const props = buildProps({+ action: { type: LOCATION_POP_ACTION, payload: { search: '' } },+ map: { extent: [0, 0, 10, 10] },+ });+ renderComponent(props);+ jest.advanceTimersByTime(200);+ await act(async () => { await flushPromises(); });+ expect(fly).toHaveBeenCalledWith(+ expect.anything(),+ props.proj,+ [5, 5],+ props.isKioskModeActive,+ expect.any(Number),+ 0,+ );+ });+ });});