Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Added more unit tests for modules/ directory

Jason Hurley74afb71d63f9
diff --git a/web/js/modules/image-download/util.test.js b/web/js/modules/image-download/util.test.js
index a59a53d1b..630774e5d 100644
--- a/web/js/modules/image-download/util.test.js
+++ b/web/js/modules/image-download/util.test.js
@@ -1,8 +1,26 @@
import {
bboxWMS13,
imageUtilCalculateResolution,
+ imageUtilEstimateResolution,
+ imageUtilGetConversionFactor,
+ imageUtilGetLayers,
+ imageUtilGetLayerOpacities,
+ imageUtilGetLayerWrap,
getLatestIntervalTime,
getDownloadUrl,
+ getTruncatedGranuleDates,
+ getDimensions,
+ getPercentageFromPixel,
+ getPixelFromPercentage,
+ imageSizeValid,
+ hasNonDownloadableVisibleLayer,
+ getNonDownloadableLayers,
+ getNamesOfNondownloadableLayers,
+ getNonDownloadableLayerWarning,
+ getAlertMessageIfCrossesDateline,
+ imageUtilGetCoordsFromPixelValues,
+ imageUtilGetPixelValuesFromCoords,
+ GRANULE_LIMIT,
} from './util';
const geoResolutions = [
@@ -171,6 +189,8 @@ const mockLayerDefsSubdaily = [
},
];
+// ------- bboxWMS13 -------
+
test('bboxWMS13 [imagedownload-bbox]', () => {
const coords = [[11, 22], [33, 44]];
const bboxGeo = bboxWMS13(coords, 'EPSG:4326');
@@ -179,12 +199,148 @@ test('bboxWMS13 [imagedownload-bbox]', () => {
expect(bboxArctic).toBe('11,22,33,44');
});
+// ------- imageUtilCalculateResolution -------
+
test('Default km resolution Calculation [imagedownload-default-resolution]', () => {
const zoom = 5;
const isGeo = true;
expect(imageUtilCalculateResolution(zoom, isGeo, geoResolutions)).toBe('4');
});
+test('Resolution calculation with negative zoom clamps to 0 [imagedownload-resolution-negative-zoom]', () => {
+ expect(imageUtilCalculateResolution(-1, true, geoResolutions)).toBe('40');
+});
+
+test('Resolution calculation with zoom beyond max clamps to last resolution [imagedownload-resolution-zoom-overflow]', () => {
+ expect(imageUtilCalculateResolution(999, true, geoResolutions)).toBe('0.125');
+});
+
+test('Resolution calculation for polar projection [imagedownload-resolution-polar]', () => {
+ const polarResolutions = [500, 250, 125, 62.5, 31.25];
+ expect(imageUtilCalculateResolution(1, false, polarResolutions)).toBe('1');
+});
+
+test('Resolution calculation bumps up at geo zoom 3 [imagedownload-resolution-zoom3]', () => {
+ expect(imageUtilCalculateResolution(3, true, geoResolutions)).toBe('20');
+});
+
+test('Resolution calculation bumps up at geo zoom 4 [imagedownload-resolution-zoom4]', () => {
+ expect(imageUtilCalculateResolution(4, true, geoResolutions)).toBe('4');
+});
+
+test('Resolution calculation bumps up at geo zoom 6 [imagedownload-resolution-zoom6]', () => {
+ expect(imageUtilCalculateResolution(6, true, geoResolutions)).toBe('2');
+});
+
+test('Resolution calculation bumps up at geo zoom 7 [imagedownload-resolution-zoom7]', () => {
+ expect(imageUtilCalculateResolution(7, true, geoResolutions)).toBe('1');
+});
+
+test('Resolution calculation bumps up at polar zoom 1 [imagedownload-resolution-polar-zoom1]', () => {
+ const polarResolutions = [500, 250, 125, 62.5, 31.25];
+ expect(imageUtilCalculateResolution(1, false, polarResolutions)).toBe('1');
+});
+
+test('Resolution calculation bumps up at polar zoom 2 [imagedownload-resolution-polar-zoom2]', () => {
+ const polarResolutions = [500, 250, 125, 62.5, 31.25];
+ expect(imageUtilCalculateResolution(2, false, polarResolutions)).toBe('1');
+});
+
+// ------- imageUtilEstimateResolution -------
+
+test('imageUtilEstimateResolution for geo projection [imagedownload-estimate-resolution-geo]', () => {
+ const result = imageUtilEstimateResolution(0.017578125, false);
+ expect(typeof result).toBe('number');
+});
+
+test('imageUtilEstimateResolution for polar projection [imagedownload-estimate-resolution-polar]', () => {
+ const result = imageUtilEstimateResolution(0.017578125, true);
+ expect(typeof result).toBe('number');
+});
+
+// ------- imageUtilGetConversionFactor -------
+
+test('imageUtilGetConversionFactor returns polar constant for geographic [imagedownload-conversion-geo]', () => {
+ expect(imageUtilGetConversionFactor('geographic')).toBeCloseTo(0.002197265625);
+});
+
+test('imageUtilGetConversionFactor returns geo constant for non-geographic [imagedownload-conversion-polar]', () => {
+ expect(imageUtilGetConversionFactor('arctic')).toBe(256.0);
+});
+
+// ------- imageUtilGetLayerWrap -------
+
+test('imageUtilGetLayerWrap returns x for wrapX layers [imagedownload-wrap-x]', () => {
+ const layers = [{ wrapX: true }, { wrapadjacentdays: true }, {}];
+ expect(imageUtilGetLayerWrap(layers)).toEqual(['x', 'day', 'none']);
+});
+
+// ------- imageUtilGetLayerOpacities -------
+
+test('imageUtilGetLayerOpacities returns empty array when all opacities are 1 [imagedownload-opacities-full]', () => {
+ const layers = [{ opacity: 1 }, { opacity: 1 }];
+ expect(imageUtilGetLayerOpacities(layers)).toEqual([]);
+});
+
+test('imageUtilGetLayerOpacities returns array when a layer has non-1 opacity [imagedownload-opacities-partial]', () => {
+ const layers = [{ opacity: 0.5 }, { opacity: 1 }];
+ expect(imageUtilGetLayerOpacities(layers)).toEqual([0.5, '']);
+});
+
+test('imageUtilGetLayerOpacities handles layer with no opacity key [imagedownload-opacities-missing]', () => {
+ const layers = [{ opacity: 0.5 }, {}];
+ expect(imageUtilGetLayerOpacities(layers)).toEqual([0.5, '']);
+});
+
+// ------- imageUtilGetLayers -------
+
+test('imageUtilGetLayers returns layer id by default [imagedownload-layers-default]', () => {
+ const layers = [{
+ id: 'LayerA',
+ projections: { geographic: {} },
+ }];
+ expect(imageUtilGetLayers(layers, 'geographic', undefined)).toEqual(['LayerA']);
+});
+
+test('imageUtilGetLayers uses downloadId when present [imagedownload-layers-downloadId]', () => {
+ const layers = [{
+ id: 'LayerA',
+ downloadId: 'LayerA_Download',
+ projections: { geographic: {} },
+ }];
+ expect(imageUtilGetLayers(layers, 'geographic', undefined)).toEqual(['LayerA_Download']);
+});
+
+test('imageUtilGetLayers uses projection id when present [imagedownload-layers-projid]', () => {
+ const layers = [{
+ id: 'LayerA',
+ projections: { geographic: { id: 'LayerA_Geo' } },
+ }];
+ expect(imageUtilGetLayers(layers, 'geographic', undefined)).toEqual(['LayerA_Geo']);
+});
+
+test('imageUtilGetLayers uses projection layer when present [imagedownload-layers-projlayer]', () => {
+ const layers = [{
+ id: 'LayerA',
+ projections: { geographic: { layer: 'LayerA_Layer' } },
+ }];
+ expect(imageUtilGetLayers(layers, 'geographic', undefined)).toEqual(['LayerA_Layer']);
+});
+
+test('imageUtilGetLayers appends disabled palette info [imagedownload-layers-disabled-palette]', () => {
+ const layers = [{
+ id: 'LayerA',
+ projections: { geographic: {} },
+ }];
+ const activePalettes = {
+ LayerA: { maps: [{ disabled: [0, 1] }] },
+ };
+ const result = imageUtilGetLayers(layers, 'geographic', activePalettes);
+ expect(result[0]).toContain('disabled=0-1');
+});
+
+// ------- getLatestIntervalTime -------
+
test('Date time snapping when no subdaily layers present [imagedownload-time-snap-no-subdaily]', () => {
const mockDate = new Date('2019-09-15T18:32:40Z');
const expectedTime = new Date('2019-09-15T00:00:00Z');
@@ -199,6 +355,218 @@ test('Date time snapping with subdaily layers present [imagedownload-time-snap-s
expect(snappedDateTime.getTime()).toBe(expectedTime.getTime());
});
+test('Date time snapping returns dateTime unchanged when TEMPO layer present [imagedownload-time-snap-tempo]', () => {
+ const mockDate = new Date('2019-09-15T18:32:40Z');
+ const tempoLayerDefs = [{
+ id: 'TEMPO_NO2_Vertical_Column',
+ period: 'subdaily',
+ dateRanges: [{ startDate: '2019-01-01T00:00:00Z', endDate: '2019-12-31T00:00:00Z', dateInterval: '60' }],
+ projections: { geographic: {} },
+ opacity: 1,
+ }];
+ const result = getLatestIntervalTime(tempoLayerDefs, mockDate);
+ expect(result).toBe(mockDate);
+});
+
+// ------- getTruncatedGranuleDates -------
+
+test('getTruncatedGranuleDates returns empty string when no granule layers [imagedownload-granule-none]', () => {
+ const result = getTruncatedGranuleDates(mockLayerDefs);
+ expect(result.value).toBe('');
+ expect(result.truncated).toBe(false);
+});
+
+test('getTruncatedGranuleDates returns formatted dates for granule layer [imagedownload-granule-dates]', () => {
+ const layerDefs = [{
+ id: 'GranuleLayer',
+ granuleDates: ['2021-01-01T00Z', '2021-01-02T12:00Z'],
+ projections: { geographic: {} },
+ }];
+ const result = getTruncatedGranuleDates(layerDefs);
+ expect(result.truncated).toBe(false);
+ expect(result.value).toContain('2021-01-01');
+});
+
+test('getTruncatedGranuleDates truncates when over GRANULE_LIMIT [imagedownload-granule-truncated]', () => {
+ const dates = Array.from({ length: GRANULE_LIMIT + 5 }, (_, i) => `2021-01-${String(i + 1).padStart(2, '0')}T00Z`);
+ const layerDefs = [
+ { id: 'GranuleLayer1', granuleDates: dates, projections: { geographic: {} } },
+ { id: 'GranuleLayer2', granuleDates: ['2021-02-01T00Z'], projections: { geographic: {} } },
+ ];
+ const result = getTruncatedGranuleDates(layerDefs);
+ expect(result.truncated).toBe(true);
+});
+
+// ------- getDimensions -------
+
+test('getDimensions returns correct width and height for geographic [imagedownload-dimensions-geo]', () => {
+ const bounds = [[0, 0], [1, 1]];
+ const result = getDimensions('geographic', bounds, 1);
+ expect(result).toHaveProperty('width');
+ expect(result).toHaveProperty('height');
+ expect(result.width).toBeGreaterThan(0);
+ expect(result.height).toBeGreaterThan(0);
+});
+
+test('getDimensions returns correct width and height for polar [imagedownload-dimensions-polar]', () => {
+ const bounds = [[0, 0], [1000000, 1000000]];
+ const result = getDimensions('arctic', bounds, 1);
+ expect(result.width).toBeGreaterThan(0);
+ expect(result.height).toBeGreaterThan(0);
+});
+
+// ------- getPercentageFromPixel -------
+
+test('getPercentageFromPixel calculates correct percentage [imagedownload-percent-from-pixel]', () => {
+ expect(getPercentageFromPixel(1000, 250)).toBe(25);
+});
+
+// ------- getPixelFromPercentage -------
+
+test('getPixelFromPercentage calculates correct pixel [imagedownload-pixel-from-percent]', () => {
+ expect(getPixelFromPercentage(1000, 25)).toBe(250);
+});
+
+// ------- imageSizeValid -------
+
+test('imageSizeValid returns false when both dimensions are 0 [imagedownload-size-valid-zero]', () => {
+ expect(imageSizeValid(0, 0, 8200)).toBe(false);
+});
+
+test('imageSizeValid returns false when a dimension exceeds maxSize [imagedownload-size-valid-exceed]', () => {
+ expect(imageSizeValid(9000, 100, 8200)).toBe(false);
+ expect(imageSizeValid(100, 9000, 8200)).toBe(false);
+});
+
+test('imageSizeValid returns true for valid dimensions [imagedownload-size-valid-ok]', () => {
+ expect(imageSizeValid(500, 500, 8200)).toBe(true);
+});
+
+// ------- hasNonDownloadableVisibleLayer -------
+
+test('hasNonDownloadableVisibleLayer returns true when a layer has disableSnapshot [imagedownload-has-non-dl-true]', () => {
+ expect(hasNonDownloadableVisibleLayer([
+ { disableSnapshot: true }, { disableSnapshot: false },
+ ])).toBe(true);
+});
+
+test('hasNonDownloadableVisibleLayer returns false when no layers have disableSnapshot [imagedownload-has-non-dl-false]', () => {
+ expect(hasNonDownloadableVisibleLayer([{ disableSnapshot: false }, {}])).toBe(false);
+});
+
+// ------- getNonDownloadableLayers -------
+
+test('getNonDownloadableLayers filters to only disableSnapshot layers [imagedownload-get-non-dl-layers]', () => {
+ const layers = [{ id: 'A', disableSnapshot: true }, { id: 'B' }, { id: 'C', disableSnapshot: false }];
+ expect(getNonDownloadableLayers(layers)).toEqual([{ id: 'A', disableSnapshot: true }]);
+});
+
+test('getNonDownloadableLayers returns empty array when none disabled [imagedownload-get-non-dl-empty]', () => {
+ expect(getNonDownloadableLayers([{ id: 'A' }, { id: 'B' }])).toEqual([]);
+});
+
+// ------- getNamesOfNondownloadableLayers -------
+
+test('getNamesOfNondownloadableLayers returns empty string for empty array [imagedownload-names-empty]', () => {
+ expect(getNamesOfNondownloadableLayers([])).toBe('');
+});
+
+test('getNamesOfNondownloadableLayers returns title when present [imagedownload-names-title]', () => {
+ expect(getNamesOfNondownloadableLayers([{ title: 'Layer A', id: 'layer-a' }])).toBe('Layer A');
+});
+
+test('getNamesOfNondownloadableLayers falls back to id when no title [imagedownload-names-id]', () => {
+ expect(getNamesOfNondownloadableLayers([{ id: 'layer-a' }])).toBe('layer-a');
+});
+
+test('getNamesOfNondownloadableLayers comma-separates multiple layers [imagedownload-names-multi]', () => {
+ const layers = [{ title: 'Layer A' }, { title: 'Layer B' }];
+ expect(getNamesOfNondownloadableLayers(layers)).toBe('Layer A, Layer B');
+});
+
+// ------- getNonDownloadableLayerWarning -------
+
+test('getNonDownloadableLayerWarning returns empty string for empty array [imagedownload-warning-empty]', () => {
+ expect(getNonDownloadableLayerWarning([])).toBe('');
+});
+
+test('getNonDownloadableLayerWarning returns singular form for one layer [imagedownload-warning-single]', () => {
+ const result = getNonDownloadableLayerWarning([{ title: 'Layer A' }]);
+ expect(result).toContain('layer');
+ expect(result).toContain('this');
+ expect(result).not.toContain('layers');
+});
+
+test('getNonDownloadableLayerWarning returns plural form for multiple layers [imagedownload-warning-plural]', () => {
+ const result = getNonDownloadableLayerWarning([{ title: 'Layer A' }, { title: 'Layer B' }]);
+ expect(result).toContain('layers');
+ expect(result).toContain('these');
+});
+
+// ------- getAlertMessageIfCrossesDateline -------
+
+test('getAlertMessageIfCrossesDateline returns empty string when no crossing [imagedownload-dateline-none]', () => {
+ const date = new Date('2021-01-15T00:00:00Z');
+ const proj = { selected: { id: 'geographic', maxExtent: [-180, -90, 180, 90] } };
+ const result = getAlertMessageIfCrossesDateline(date, [-100, 0], [100, 50], proj);
+ expect(result).toBe('');
+});
+
+test('getAlertMessageIfCrossesDateline returns empty string for non-geographic projection [imagedownload-dateline-non-geo]', () => {
+ const date = new Date('2021-01-15T00:00:00Z');
+ const proj = { selected: { id: 'arctic', maxExtent: [-4194304, -4194304, 4194304, 4194304] } };
+ const result = getAlertMessageIfCrossesDateline(date, [-200, 0], [200, 50], proj);
+ expect(result).toBe('');
+});
+
+test('getAlertMessageIfCrossesDateline detects next day crossing [imagedownload-dateline-next]', () => {
+ const date = new Date('2021-01-15T00:00:00Z');
+ const proj = { selected: { id: 'geographic', maxExtent: [-180, -90, 180, 90] } };
+ const result = getAlertMessageIfCrossesDateline(date, [-200, 0], [100, 50], proj);
+ expect(result).toContain('next day');
+});
+
+test('getAlertMessageIfCrossesDateline detects prev day crossing [imagedownload-dateline-prev]', () => {
+ const date = new Date('2021-01-15T00:00:00Z');
+ const proj = { selected: { id: 'geographic', maxExtent: [-180, -90, 180, 90] } };
+ const result = getAlertMessageIfCrossesDateline(date, [-100, 0], [200, 50], proj);
+ expect(result).toContain('previous day');
+});
+
+test('getAlertMessageIfCrossesDateline detects both datelines crossing [imagedownload-dateline-both]', () => {
+ const date = new Date('2021-01-15T00:00:00Z');
+ const proj = { selected: { id: 'geographic', maxExtent: [-180, -90, 180, 90] } };
+ const result = getAlertMessageIfCrossesDateline(date, [-200, 0], [200, 50], proj);
+ expect(result).toContain('both datelines');
+});
+
+// ------- imageUtilGetCoordsFromPixelValues -------
+
+test('imageUtilGetCoordsFromPixelValues calls map correctly [imagedownload-coords-from-pixels]', () => {
+ const mockMap = {
+ getCoordinateFromPixel: jest.fn((px) => px),
+ };
+ const pixels = { x: 10.7, y: 20.3, x2: 30.9, y2: 40.1 };
+ const result = imageUtilGetCoordsFromPixelValues(pixels, mockMap);
+ expect(mockMap.getCoordinateFromPixel).toHaveBeenCalledWith([10, 40]);
+ expect(mockMap.getCoordinateFromPixel).toHaveBeenCalledWith([30, 20]);
+ expect(result).toHaveLength(2);
+});
+
+// ------- imageUtilGetPixelValuesFromCoords -------
+
+test('imageUtilGetPixelValuesFromCoords calls map correctly [imagedownload-pixels-from-coords]', () => {
+ const mockMap = {
+ getPixelFromCoordinate: jest.fn()
+ .mockReturnValueOnce([15.4, 25.6])
+ .mockReturnValueOnce([35.2, 45.8]),
+ };
+ const result = imageUtilGetPixelValuesFromCoords([0, 0], [1, 1], mockMap);
+ expect(result).toEqual({ x: 15, y: 46, x2: 35, y2: 26 });
+});
+
+// ------- getDownloadUrl -------
+
test('Download URL [imagedownload-url]', () => {
const url = 'http://localhost:3002/api/v1/snapshot';
const proj = {
@@ -243,3 +611,93 @@ test('Download URL [imagedownload-url]', () => {
'&MARKER=2.7117,-19.1609,71.173,-39.0961';
expect(dlURL.includes(expectedURL)).toBe(true);
});
+
+test('Download URL includes WORLDFILE param when isWorldfile is true [imagedownload-url-worldfile]', () => {
+ const url = 'http://localhost:3002/api/v1/snapshot';
+ const proj = { id: 'geographic', selected: { crs: 'EPSG:4326' } };
+ const lonlats = [[-10, -10], [10, 10]];
+ const dimensions = { width: 200, height: 200 };
+ const dateTime = new Date('2019-06-24T00:00:00Z');
+ const dlURL = getDownloadUrl(
+ url, proj, mockLayerDefs, lonlats, dimensions, dateTime, false, true, [], undefined,
+ );
+ expect(dlURL).toContain('WORLDFILE=true');
+});
+
+test('Download URL uses specified fileType format [imagedownload-url-filetype]', () => {
+ const url = 'http://localhost:3002/api/v1/snapshot';
+ const proj = { id: 'geographic', selected: { crs: 'EPSG:4326' } };
+ const lonlats = [[-10, -10], [10, 10]];
+ const dimensions = { width: 200, height: 200 };
+ const dateTime = new Date('2019-06-24T00:00:00Z');
+ const dlURL = getDownloadUrl(url, proj, mockLayerDefs, lonlats, dimensions, dateTime, 'image/png', false, [], undefined);
+ expect(dlURL).toContain('FORMAT=image/png');
+});
+
+test('Download URL omits MARKER param when no markers provided [imagedownload-url-no-markers]', () => {
+ const url = 'http://localhost:3002/api/v1/snapshot';
+ const proj = { id: 'geographic', selected: { crs: 'EPSG:4326' } };
+ const lonlats = [[-10, -10], [10, 10]];
+ const dimensions = { width: 200, height: 200 };
+ const dateTime = new Date('2019-06-24T00:00:00Z');
+ const dlURL = getDownloadUrl(
+ url, proj, mockLayerDefs, lonlats, dimensions, dateTime, false, false, [], undefined,
+ );
+ expect(dlURL).not.toContain('MARKER=');
+});
+
+test('Download URL includes OPACITIES when layer opacity is not 1 [imagedownload-url-opacities]', () => {
+ const url = 'http://localhost:3002/api/v1/snapshot';
+ const proj = { id: 'geographic', selected: { crs: 'EPSG:4326' } };
+ const lonlats = [[-10, -10], [10, 10]];
+ const dimensions = { width: 200, height: 200 };
+ const dateTime = new Date('2019-06-24T00:00:00Z');
+ const layersWithOpacity = [{ ...mockLayerDefs[0], opacity: 0.5 }];
+ const dlURL = getDownloadUrl(
+ url, proj, layersWithOpacity, lonlats, dimensions, dateTime, false, false, [], undefined,
+ );
+ expect(dlURL).toContain('OPACITIES=');
+});
+
+test('Download URL includes KMZ OrbitTrack split layers [imagedownload-url-kmz-orbittracks]', () => {
+ const url = 'http://localhost:3002/api/v1/snapshot';
+ const proj = { id: 'geographic', selected: { crs: 'EPSG:4326' } };
+ const lonlats = [[-10, -10], [10, 10]];
+ const dimensions = { width: 200, height: 200 };
+ const dateTime = new Date('2019-06-24T00:00:00Z');
+ const orbitLayers = [{
+ id: 'OrbitTracks_Aqua_Ascending',
+ projections: { geographic: {} },
+ wrapadjacentdays: false,
+ wrapX: false,
+ opacity: 1,
+ }];
+ const dlURL = getDownloadUrl(
+ url, proj, orbitLayers, lonlats, dimensions, dateTime,
+ 'application/vnd.google-earth.kmz', false, [], undefined,
+ );
+ expect(dlURL).toContain('OrbitTracks_Aqua_Ascending_Lines');
+ expect(dlURL).toContain('OrbitTracks_Aqua_Ascending_Points');
+});
+
+test('Download URL includes granule_dates when granuleDates present [imagedownload-url-granule-dates]', () => {
+ const url = 'http://localhost:3002/api/v1/snapshot';
+ const proj = { id: 'geographic', selected: { crs: 'EPSG:4326' } };
+ const lonlats = [[-10, -10], [10, 10]];
+ const dimensions = { width: 200, height: 200 };
+ const dateTime = new Date('2019-06-24T00:00:00Z');
+ const granuleLayers = [{
+ ...mockLayerDefs[0],
+ granuleDates: ['2021-01-01T12:00Z'],
+ }];
+ const dlURL = getDownloadUrl(
+ url, proj, granuleLayers, lonlats, dimensions, dateTime, false, false, [], undefined,
+ );
+ expect(dlURL).toContain('granule_dates=');
+});
+
+// ------- GRANULE_LIMIT -------
+
+test('GRANULE_LIMIT is 30 [imagedownload-granule-limit]', () => {
+ expect(GRANULE_LIMIT).toBe(30);
+});
diff --git a/web/js/modules/key-press/actions.test.js b/web/js/modules/key-press/actions.test.js
index 22bc698b0..92d01ea5f 100644
--- a/web/js/modules/key-press/actions.test.js
+++ b/web/js/modules/key-press/actions.test.js
@@ -1,3 +1,83 @@
-test('actions module test', () => {
+// import { KEY_PRESS_ACTION as ANIMATION_KEY_PRESS_ACTION } from '../animation/constants';
+import { TOUR_KEY_PRESS_CLOSE } from '../tour/constants';
+import { TOGGLE_DISTRACTION_FREE_MODE } from '../ui/constants';
+import { triggerTodayButton } from '../date/actions';
+import { CLOSE as CLOSE_MODAL } from '../modal/constants';
+import keyPress from './actions';
+jest.mock('../date/actions', () => ({
+ triggerTodayButton: jest.fn(() => ({ type: 'TRIGGER_TODAY_BUTTON' })),
+}));
+
+describe('keyPress action', () => {
+ it('dispatches the correct action for ESC key when tour is active', () => {
+ const dispatch = jest.fn();
+ const getState = () => ({
+ modal: { id: 'TEST_MODAL', isOpen: true },
+ animation: { isActive: false },
+ tour: { active: true },
+ ui: { isDistractionFreeModeActive: false },
+ });
+
+ keyPress(27, false, false, false)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: TOUR_KEY_PRESS_CLOSE });
+ });
+
+ it('dispatches the correct action for SHIFT + D when not in input and distraction free mode is toggled', () => {
+ const dispatch = jest.fn();
+ const getState = () => ({
+ modal: { id: 'TEST_MODAL', isOpen: true },
+ animation: { isActive: false },
+ tour: { active: false },
+ ui: { isDistractionFreeModeActive: false },
+ });
+
+ keyPress(68, true, false, false)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: TOGGLE_DISTRACTION_FREE_MODE });
+ expect(dispatch).toHaveBeenCalledWith({ type: CLOSE_MODAL });
+ });
+
+ it('dispatches the correct action for SHIFT + T when not in input', () => {
+ const dispatch = jest.fn();
+ const getState = () => ({
+ modal: { id: 'TEST_MODAL', isOpen: true },
+ animation: { isActive: false },
+ tour: { active: false },
+ ui: { isDistractionFreeModeActive: false },
+ });
+
+ keyPress(84, true, false, false)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith(triggerTodayButton());
+ });
+
+ it('dispatches the correct action for ESC key when in distraction free mode', () => {
+ const dispatch = jest.fn();
+ const getState = () => ({
+ modal: { id: 'TEST_MODAL', isOpen: true },
+ animation: { isActive: false },
+ tour: { active: false },
+ ui: { isDistractionFreeModeActive: true },
+ });
+
+ keyPress(27, false, false, false)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: TOGGLE_DISTRACTION_FREE_MODE });
+ });
+
+ it('dispatches the correct action for ESC key when not in distraction free mode', () => {
+ const dispatch = jest.fn();
+ const getState = () => ({
+ modal: { id: 'TEST_MODAL', isOpen: true },
+ animation: { isActive: false },
+ tour: { active: false },
+ ui: { isDistractionFreeModeActive: false },
+ });
+
+ keyPress(27, false, false, false)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: CLOSE_MODAL });
+ });
});
diff --git a/web/js/modules/layers/actions.test.js b/web/js/modules/layers/actions.test.js
index 2bce5bb0e..4e425feef 100644
--- a/web/js/modules/layers/actions.test.js
+++ b/web/js/modules/layers/actions.test.js
@@ -1,15 +1,63 @@
import configureMockStore from 'redux-mock-store';
import { thunk } from 'redux-thunk';
import fixtures from '../../fixtures';
-import { addLayer, getLayers } from './selectors';
import {
- removeLayer, removeGroup, toggleOverlayGroups,
+ removeLayer,
+ removeGroup,
+ toggleOverlayGroups,
+ reorderLayers,
+ reorderOverlayGroups,
+ toggleVisibility,
+ toggleGroupVisibility,
+ toggleGroupCollapsed,
+ setOpacity,
+ hideLayers,
+ showLayers,
+ addLayer as addLayerAction,
+ initSecondLayerGroup,
+ syncSecondLayerGroup,
+ addTEMPODateRanges,
+ addGranuleDateRanges,
+ updateCollection,
+ activateLayersForEventCategory,
+ updateGranuleLayerState,
+ updateGranuleLayerOptions,
+ resetGranuleLayerDates,
+ changeGranuleSatelliteInstrumentGroup,
+ updateBandCombination,
} from './actions';
import * as LAYER_CONSTANTS from './constants';
+import { getOverlayGroups, getLayersFromGroups } from './util';
+import {
+ addLayer,
+ activateLayersForEventCategory as activateLayersForEventCategorySelector,
+ findEventLayers,
+ getLayers,
+ getGranuleLayer,
+} from './selectors';
+import { getGranuleFootprints } from '../../map/granule/util';
+
+jest.mock('./selectors', () => ({
+ ...jest.requireActual('./selectors'),
+ activateLayersForEventCategory: jest.fn(),
+ findEventLayers: jest.fn(),
+ getGranuleLayer: jest.fn(),
+}));
+
+jest.mock('./util', () => ({
+ ...jest.requireActual('./util'),
+ getOverlayGroups: jest.fn(),
+ getLayersFromGroups: jest.fn(),
+}));
+
+jest.mock('../../map/granule/util', () => ({
+ getGranuleFootprints: jest.fn(),
+}));
const mockStore = configureMockStore([thunk]);
const config = fixtures.config();
-function getState(layers) {
+
+function getState(layers, overrides = {}) {
return {
config,
proj: { id: 'geographic', selected: config.projections.geographic },
@@ -31,15 +79,21 @@ function getState(layers) {
},
activeB: {
layers,
+ granuleLayers: {},
},
granuleFootprints: {},
+ layerConfig: config.layers,
},
compare: {
activeString: 'active',
+ active: false,
+ ...overrides.compare,
},
+ ...overrides,
};
}
-function addMockLayer(layerId, layerArray, proj) {
+
+function addMockLayer(layerId, layerArray) {
return addLayer(
layerId,
layerArray,
@@ -54,6 +108,7 @@ describe('Layer actions', () => {
let store;
beforeEach(() => {
+ jest.clearAllMocks();
layers = [];
layers = addLayer('terra-cr', [], config.layers, {}, 0);
layers = addMockLayer('aqua-cr', layers);
@@ -62,52 +117,749 @@ describe('Layer actions', () => {
store = mockStore(getState(layers));
});
- test('REMOVE_LAYER action removes layer by id [layers-action-remove-layer-by-id]', () => {
+ test('initSecondLayerGroup returns correct action object [layers-action-init-second-group]', () => {
+ const action = initSecondLayerGroup();
+ expect(action).toEqual({ type: LAYER_CONSTANTS.INIT_SECOND_LAYER_GROUP });
+ });
+
+ test('syncSecondLayerGroup returns correct action object [layers-action-sync-second-group]', () => {
+ const ids = ['terra-cr', 'aqua-cr'];
+ const action = syncSecondLayerGroup(ids);
+ expect(action).toEqual({
+ type: LAYER_CONSTANTS.SYNC_SECOND_LAYER_GROUP,
+ lastExitALayerIds: ids,
+ });
+ });
+
+ test('updateCollection returns correct action object [layers-action-update-collection]', () => {
+ const collection = { id: 'C1234', title: 'Test Collection' };
+ const action = updateCollection(collection);
+ expect(action).toEqual({
+ type: LAYER_CONSTANTS.UPDATE_COLLECTION,
+ payload: collection,
+ });
+ });
+
+ test('REMOVE_LAYER removes layer by id [layers-action-remove-layer-by-id]', () => {
const def = layers[0];
store.dispatch(removeLayer('aqua-aod'));
const actionResponse = store.getActions()[0];
- const responseLayers = [layers[1], layers[2], layers[3]];
-
- const expectedPayload = {
+ expect(actionResponse).toEqual({
type: LAYER_CONSTANTS.REMOVE_LAYER,
activeString: 'active',
layersToRemove: [def],
- layers: responseLayers,
+ layers: [layers[1], layers[2], layers[3]],
granuleLayers: {},
- };
- expect(actionResponse).toEqual(expectedPayload);
+ });
});
test('REMOVE_LAYER does nothing on non-existent id [layers-action-remove-layer-no-id]', () => {
store.dispatch(removeLayer('INVALID TEST LAYER ID'));
- const actionResponse = store.getActions()[0];
- const expectedPayload = undefined;
- expect(actionResponse).toEqual(expectedPayload);
+ expect(store.getActions()[0]).toBeUndefined();
});
test('REMOVE_GROUP removes each layer in group [layers-action-remove-group]', () => {
store.dispatch(removeGroup(['terra-aod', 'aqua-aod']));
- const actionResponse = store.getActions()[0];
- const expectedPayload = {
+ expect(store.getActions()[0]).toEqual({
type: LAYER_CONSTANTS.REMOVE_GROUP,
activeString: 'active',
layersToRemove: [layers[0], layers[1]],
layers: [layers[2], layers[3]],
granuleLayers: {},
- };
- expect(actionResponse).toEqual(expectedPayload);
+ });
+ });
+
+ test('REORDER_LAYERS dispatches correct action [layers-action-reorder-layers]', () => {
+ const reordered = [layers[3], layers[2], layers[1], layers[0]];
+ store.dispatch(reorderLayers(reordered));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.REORDER_LAYERS,
+ activeString: 'active',
+ layers: reordered,
+ });
});
- test('TOGGLE_OVERLAY_GROUPS when grouped, toggling ungroups layers [layers-action-toggle-group]', () => {
+ test('REORDER_OVERLAY_GROUPS dispatches correct action [layers-action-reorder-overlay-groups]', () => {
+ const groups = [{ groupName: 'AOD', layers: ['aqua-aod', 'terra-aod'], collapsed: false }];
+ store.dispatch(reorderOverlayGroups(layers, groups));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.REORDER_OVERLAY_GROUPS,
+ activeString: 'active',
+ layers,
+ overlayGroups: groups,
+ });
+ });
+
+ test('TOGGLE_LAYER_VISIBILITY dispatches correct action [layers-action-toggle-visibility]', () => {
+ store.dispatch(toggleVisibility('aqua-aod', false));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.TOGGLE_LAYER_VISIBILITY,
+ id: 'aqua-aod',
+ visible: false,
+ activeString: 'active',
+ });
+ });
+
+ test('TOGGLE_LAYER_VISIBILITY dispatches correct action when setting visible true [layers-action-toggle-visibility-true]', () => {
+ store.dispatch(toggleVisibility('terra-cr', true));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.TOGGLE_LAYER_VISIBILITY,
+ id: 'terra-cr',
+ visible: true,
+ activeString: 'active',
+ });
+ });
+
+ test('TOGGLE_OVERLAY_GROUP_VISIBILITY dispatches correct action [layers-action-toggle-group-visibility]', () => {
+ store.dispatch(toggleGroupVisibility(['aqua-aod', 'terra-aod'], false));
+ const actionResponse = store.getActions()[0];
+ expect(actionResponse.type).toBe(LAYER_CONSTANTS.TOGGLE_OVERLAY_GROUP_VISIBILITY);
+ expect(actionResponse.activeString).toBe('active');
+ const updatedAqua = actionResponse.layers.find((l) => l.id === 'aqua-aod');
+ const updatedTerra = actionResponse.layers.find((l) => l.id === 'terra-aod');
+ expect(updatedAqua.visible).toBe(false);
+ expect(updatedTerra.visible).toBe(false);
+ });
+
+ test('TOGGLE_OVERLAY_GROUP_VISIBILITY only modifies layers in the given ids [layers-action-toggle-group-visibility-partial]', () => {
+ store.dispatch(toggleGroupVisibility(['aqua-aod'], true));
+ const actionResponse = store.getActions()[0];
+ const untouched = actionResponse.layers.find((l) => l.id === 'terra-aod');
+ expect(untouched.visible).toBe(true);
+ });
+
+ test('TOGGLE_COLLAPSE_OVERLAY_GROUP dispatches correct action [layers-action-toggle-group-collapsed]', () => {
+ store.dispatch(toggleGroupCollapsed('AOD', true));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.TOGGLE_COLLAPSE_OVERLAY_GROUP,
+ groupName: 'AOD',
+ activeString: 'active',
+ collapsed: true,
+ });
+ });
+
+ test('TOGGLE_COLLAPSE_OVERLAY_GROUP dispatches correct action when expanding [layers-action-toggle-group-collapsed-false]', () => {
+ store.dispatch(toggleGroupCollapsed('AOD', false));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.TOGGLE_COLLAPSE_OVERLAY_GROUP,
+ groupName: 'AOD',
+ activeString: 'active',
+ collapsed: false,
+ });
+ });
+
+ test('UPDATE_OPACITY dispatches correct action [layers-action-set-opacity]', () => {
+ store.dispatch(setOpacity('aqua-aod', 0.5));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.UPDATE_OPACITY,
+ id: 'aqua-aod',
+ opacity: 0.5,
+ activeString: 'active',
+ });
+ });
+
+ test('setOpacity coerces opacity to number [layers-action-set-opacity-coerce]', () => {
+ store.dispatch(setOpacity('aqua-aod', '0.3'));
+ expect(store.getActions()[0].opacity).toBe(0.3);
+ });
+
+ test('setOpacity does nothing on non-existent id [layers-action-set-opacity-no-id]', () => {
+ store.dispatch(setOpacity('INVALID LAYER ID', 0.5));
+ expect(store.getActions()[0]).toBeUndefined();
+ });
+
+ test('hideLayers dispatches TOGGLE_LAYER_VISIBILITY false for each layer [layers-action-hide-layers]', () => {
+ store.dispatch(hideLayers([layers[0], layers[1]]));
+ const actions = store.getActions();
+ expect(actions).toHaveLength(2);
+ expect(actions[0].type).toBe(LAYER_CONSTANTS.TOGGLE_LAYER_VISIBILITY);
+ expect(actions[0].visible).toBe(false);
+ expect(actions[1].visible).toBe(false);
+ });
+
+ test('hideLayers sets the correct layer ids [layers-action-hide-layers-ids]', () => {
+ store.dispatch(hideLayers([layers[0], layers[1]]));
+ const actions = store.getActions();
+ expect(actions[0].id).toBe(layers[0].id);
+ expect(actions[1].id).toBe(layers[1].id);
+ });
+
+ test('showLayers dispatches TOGGLE_LAYER_VISIBILITY true for each layer [layers-action-show-layers]', () => {
+ store.dispatch(showLayers([layers[0], layers[1]]));
+ const actions = store.getActions();
+ expect(actions).toHaveLength(2);
+ expect(actions[0].type).toBe(LAYER_CONSTANTS.TOGGLE_LAYER_VISIBILITY);
+ expect(actions[0].visible).toBe(true);
+ expect(actions[1].visible).toBe(true);
+ });
+
+ test('showLayers sets the correct layer ids [layers-action-show-layers-ids]', () => {
+ store.dispatch(showLayers([layers[0], layers[1]]));
+ const actions = store.getActions();
+ expect(actions[0].id).toBe(layers[0].id);
+ expect(actions[1].id).toBe(layers[1].id);
+ });
+
+ test('ADD_LAYER dispatches correct action [layers-action-add-layer]', () => {
+ store.dispatch(addLayerAction('terra-cr'));
+ const actionResponse = store.getActions()[0];
+ expect(actionResponse.type).toBe(LAYER_CONSTANTS.ADD_LAYER);
+ expect(actionResponse.id).toBe('terra-cr');
+ expect(actionResponse.activeString).toBe('active');
+ });
+
+ test('ADD_LAYER dispatches with a layers array [layers-action-add-layer-has-layers]', () => {
+ store.dispatch(addLayerAction('terra-cr'));
+ const actionResponse = store.getActions()[0];
+ expect(Array.isArray(actionResponse.layers)).toBe(true);
+ });
+
+ test('TOGGLE_OVERLAY_GROUPS when grouped uses getLayersFromGroups when prevLayers is empty [layers-action-toggle-group]', () => {
+ getLayersFromGroups.mockReturnValue(layers);
store.dispatch(toggleOverlayGroups());
const actionResponse = store.getActions()[0];
- const expectedPayload = {
+ expect(actionResponse).toEqual({
type: LAYER_CONSTANTS.TOGGLE_OVERLAY_GROUPS,
activeString: 'active',
groupOverlays: false,
layers,
overlayGroups: [],
+ });
+ });
+
+ test('TOGGLE_OVERLAY_GROUPS when grouped uses prevLayers when non-empty [layers-action-toggle-group-prev-layers]', () => {
+ const prevLayerState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ groupOverlays: true,
+ prevLayers: layers,
+ },
+ },
+ };
+ const prevLayerStore = mockStore(prevLayerState);
+ prevLayerStore.dispatch(toggleOverlayGroups());
+ const actionResponse = prevLayerStore.getActions()[0];
+ expect(actionResponse.type).toBe(LAYER_CONSTANTS.TOGGLE_OVERLAY_GROUPS);
+ expect(actionResponse.groupOverlays).toBe(false);
+ expect(actionResponse.layers).toEqual(layers);
+ });
+
+ test('TOGGLE_OVERLAY_GROUPS when ungrouped re-groups layers [layers-action-toggle-group-enable]', () => {
+ const regroupedLayers = [layers[0], layers[1]];
+ const groups = [{ groupName: 'AOD', layers: ['aqua-aod', 'terra-aod'], collapsed: false }];
+ getOverlayGroups.mockReturnValue(groups);
+ getLayersFromGroups.mockReturnValue(regroupedLayers);
+ const ungroupedState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ groupOverlays: false,
+ prevLayers: [],
+ overlayGroups: [],
+ },
+ },
+ };
+ const ungroupedStore = mockStore(ungroupedState);
+ ungroupedStore.dispatch(toggleOverlayGroups());
+ const actionResponse = ungroupedStore.getActions()[0];
+ expect(actionResponse.type).toBe(LAYER_CONSTANTS.TOGGLE_OVERLAY_GROUPS);
+ expect(actionResponse.groupOverlays).toBe(true);
+ expect(actionResponse.layers).toEqual(regroupedLayers);
+ expect(actionResponse.overlayGroups).toEqual(groups);
+ expect(actionResponse.prevLayers).toEqual(layers);
+ });
+
+ test('activateLayersForEventCategory dispatches ADD_LAYERS_FOR_EVENT [layers-action-activate-layers-for-event-category]', () => {
+ const originalLayer = { id: 'terra-cr', group: 'baselayers' };
+ const eventLayer = { id: 'MODIS_Terra_Thermal_Anomalies_All', group: 'overlays', eventLayer: true };
+ activateLayersForEventCategorySelector.mockReturnValue([originalLayer, eventLayer]);
+ findEventLayers.mockReturnValue([eventLayer]);
+ getOverlayGroups.mockReturnValue([]);
+ store.dispatch(activateLayersForEventCategory('fires'));
+ const [action] = store.getActions();
+ expect(action.type).toBe(LAYER_CONSTANTS.ADD_LAYERS_FOR_EVENT);
+ expect(action.activeString).toBe('active');
+ expect(action.layers).toEqual([originalLayer, eventLayer]);
+ expect(action.eventLayers).toEqual([eventLayer]);
+ });
+
+ test('activateLayersForEventCategory sets overlayGroups collapsed true [layers-action-activate-layers-for-event-category-collapsed]', () => {
+ const eventLayer = { id: 'MODIS_Terra_Thermal_Anomalies_All', group: 'overlays', eventLayer: true };
+ const group = { groupName: 'Fires', layers: [eventLayer.id], collapsed: false };
+ activateLayersForEventCategorySelector.mockReturnValue([eventLayer]);
+ findEventLayers.mockReturnValue([eventLayer]);
+ getOverlayGroups.mockReturnValue([group]);
+ store.dispatch(activateLayersForEventCategory('fires'));
+ const [action] = store.getActions();
+ expect(action.overlayGroups[0].collapsed).toBe(true);
+ });
+
+ test('ADD_TEMPO_DATE_RANGES dispatches correct action [layers-action-add-tempo-date-ranges]', () => {
+ const layer = { id: 'TEMPO_NO2' };
+ const ranges = [['2021-01-01', '2021-01-02']];
+ store.dispatch(addTEMPODateRanges(layer, ranges, 'active'));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.ADD_TEMPO_DATE_RANGES,
+ activeString: 'active',
+ id: 'TEMPO_NO2',
+ tempoDateRanges: ranges,
+ });
+ });
+
+ test('ADD_TEMPO_DATE_RANGES dispatches with activeB string [layers-action-add-tempo-date-ranges-active-b]', () => {
+ const layer = { id: 'TEMPO_NO2' };
+ const ranges = [['2021-01-01', '2021-01-02']];
+ store.dispatch(addTEMPODateRanges(layer, ranges, 'activeB'));
+ expect(store.getActions()[0].activeString).toBe('activeB');
+ });
+
+ test('addGranuleDateRanges dispatches ADD_GRANULE_DATE_RANGES for active side [layers-action-add-granule-date-ranges]', () => {
+ const layerWithGranule = { ...layers[0], granuleDateRanges: null };
+ const stateWithGranule = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ layers: [layerWithGranule, ...layers.slice(1)],
+ },
+ activeB: {
+ layers: [layerWithGranule, ...layers.slice(1)],
+ granuleLayers: {},
+ },
+ },
+ };
+ const granuleStore = mockStore(stateWithGranule);
+ const ranges = [['2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z']];
+ granuleStore.dispatch(addGranuleDateRanges({ id: layerWithGranule.id }, ranges));
+ const actions = granuleStore.getActions();
+ expect(actions[0].type).toBe(LAYER_CONSTANTS.ADD_GRANULE_DATE_RANGES);
+ expect(actions[0].id).toBe(layerWithGranule.id);
+ expect(actions[0].activeString).toBe('active');
+ expect(actions[0].granuleDateRanges).toEqual(ranges);
+ });
+
+ test('addGranuleDateRanges skips dispatch when layer not found [layers-action-add-granule-date-ranges-no-layer]', () => {
+ store.dispatch(addGranuleDateRanges({ id: 'NONEXISTENT_LAYER' }, []));
+ expect(store.getActions()).toHaveLength(0);
+ });
+
+ test('addGranuleDateRanges skips dispatch when ranges are equal [layers-action-add-granule-date-ranges-dedup]', () => {
+ const ranges = [['2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z']];
+ const layerWithRanges = { ...layers[0], granuleDateRanges: ranges };
+ const stateWithRanges = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ layers: [layerWithRanges, ...layers.slice(1)],
+ },
+ },
+ };
+ const dedupStore = mockStore(stateWithRanges);
+ dedupStore.dispatch(addGranuleDateRanges({ id: layerWithRanges.id }, ranges));
+ expect(dedupStore.getActions()).toHaveLength(0);
+ });
+
+ test('addGranuleDateRanges syncs to activeB in compare mode [layers-action-add-granule-date-ranges-compare]', () => {
+ const ranges = [['2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z']];
+ const layerWithGranule = { ...layers[0], granuleDateRanges: null };
+ const compareState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ layers: [layerWithGranule, ...layers.slice(1)],
+ },
+ activeB: {
+ layers: [layerWithGranule, ...layers.slice(1)],
+ granuleLayers: {},
+ },
+ },
+ compare: { activeString: 'active', active: true },
+ };
+ const compareStore = mockStore(compareState);
+ compareStore.dispatch(addGranuleDateRanges({ id: layerWithGranule.id }, ranges));
+ const actions = compareStore.getActions();
+ expect(actions.length).toBeGreaterThanOrEqual(2);
+ expect(actions[0].activeString).toBe('active');
+ expect(actions[1].activeString).toBe('activeB');
+ });
+
+ test('addGranuleDateRanges syncs from activeB to active in compare mode [layers-action-add-granule-date-ranges-compare-b-side]', () => {
+ const ranges = [['2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z']];
+ const layerWithGranule = { ...layers[0], granuleDateRanges: null };
+ const compareState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ layers: [layerWithGranule, ...layers.slice(1)],
+ },
+ activeB: {
+ layers: [layerWithGranule, ...layers.slice(1)],
+ granuleLayers: {},
+ },
+ },
+ compare: { activeString: 'activeB', active: true },
+ };
+ const compareStore = mockStore(compareState);
+ compareStore.dispatch(addGranuleDateRanges({ id: layerWithGranule.id }, ranges));
+ const actions = compareStore.getActions();
+ expect(actions.length).toBeGreaterThanOrEqual(2);
+ expect(actions[0].activeString).toBe('activeB');
+ expect(actions[1].activeString).toBe('active');
+ });
+
+ test('addGranuleDateRanges skips other side when layer absent from it [layers-action-add-granule-date-ranges-missing-side]', () => {
+ const ranges = [['2021-01-01T00:00:00Z', '2021-01-02T00:00:00Z']];
+ const layerWithGranule = { ...layers[0], granuleDateRanges: null };
+ const compareState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ layers: [layerWithGranule, ...layers.slice(1)],
+ },
+ activeB: {
+ layers: layers.slice(1),
+ granuleLayers: {},
+ },
+ },
+ compare: { activeString: 'active', active: true },
+ };
+ const compareStore = mockStore(compareState);
+ compareStore.dispatch(addGranuleDateRanges({ id: layerWithGranule.id }, ranges));
+ expect(compareStore.getActions()).toHaveLength(1);
+ expect(compareStore.getActions()[0].activeString).toBe('active');
+ });
+
+ test('RESET_GRANULE_LAYER_OPTIONS dispatches correct action [layers-action-reset-granule-layer-dates]', () => {
+ store.dispatch(resetGranuleLayerDates('aqua-aod'));
+ expect(store.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.RESET_GRANULE_LAYER_OPTIONS,
+ id: 'aqua-aod',
+ activeKey: 'active',
+ });
+ });
+
+ test('CHANGE_GRANULE_SATELLITE_INSTRUMENT_GROUP dispatches correct action [layers-action-change-granule-satellite-group]', () => {
+ const mockGeometry = { type: 'FeatureCollection', features: [] };
+ const granuleState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ granuleLayers: { 'aqua-aod': { geometry: mockGeometry } },
+ },
+ },
+ };
+ getGranuleLayer.mockReturnValue({ geometry: mockGeometry });
+ const granuleStore = mockStore(granuleState);
+ granuleStore.dispatch(changeGranuleSatelliteInstrumentGroup('aqua-aod', 'Aqua / MODIS'));
+ expect(granuleStore.getActions()[0]).toEqual({
+ type: LAYER_CONSTANTS.CHANGE_GRANULE_SATELLITE_INSTRUMENT_GROUP,
+ granulePlatform: 'Aqua / MODIS',
+ geometry: mockGeometry,
+ activeKey: 'active',
+ });
+ });
+
+ test('UPDATE_GRANULE_LAYER_OPTIONS dispatches for each matching platform layer [layers-action-update-granule-layer-options]', () => {
+ const dates = ['2021-01-01', '2021-01-02'];
+ const def = { subtitle: 'Aqua / MODIS' };
+ const count = 20;
+ const granuleState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ granuleLayers: { 'aqua-aod': { count, dates, granulePlatform: 'Aqua / MODIS' } },
+ granulePlatform: 'Aqua / MODIS',
+ },
+ },
+ };
+ const granuleStore = mockStore(granuleState);
+ granuleStore.dispatch(updateGranuleLayerOptions(dates, def, count));
+ const actions = granuleStore.getActions();
+ expect(actions.length).toBeGreaterThanOrEqual(1);
+ actions.forEach((action) => {
+ expect(action.type).toBe(LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_OPTIONS);
+ expect(action.dates).toEqual(dates);
+ expect(action.count).toBe(count);
+ expect(action.activeKey).toBe('active');
+ });
+ });
+
+ test('UPDATE_GRANULE_LAYER_OPTIONS dispatches no actions when no matching platform layers [layers-action-update-granule-layer-options-no-match]', () => {
+ const granuleState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: {
+ ...getState(layers).layers.active,
+ granuleLayers: {},
+ granulePlatform: 'Aqua / MODIS',
+ },
+ },
+ };
+ const granuleStore = mockStore(granuleState);
+ granuleStore.dispatch(updateGranuleLayerOptions(['2021-01-01'], { subtitle: 'Terra / MODIS' }, 10));
+ expect(granuleStore.getActions()).toHaveLength(0);
+ });
+
+ test('updateGranuleLayerState dispatches only ADD_GRANULE_LAYER_DATES when no existing layer [layers-action-update-granule-layer-state-new]', () => {
+ const granuleDates = ['2021-01-03T00:00:00Z', '2021-01-02T00:00:00Z'];
+ const mockFootprints = { type: 'FeatureCollection', features: [] };
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ count: 20,
+ granuleDates,
+ reorderedGranules: null,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ getGranuleFootprints.mockReturnValue(mockFootprints);
+ getGranuleLayer.mockReturnValue(null);
+ store.dispatch(updateGranuleLayerState(mockLayer));
+ const actions = store.getActions();
+ expect(actions).toHaveLength(1);
+ expect(actions[0]).toEqual({
+ type: LAYER_CONSTANTS.ADD_GRANULE_LAYER_DATES,
+ id: 'aqua-aod',
+ activeKey: 'active',
+ dates: granuleDates,
+ granuleFootprints: mockFootprints,
+ granulePlatform: 'Aqua / MODIS',
+ count: 20,
+ });
+ });
+
+ test('updateGranuleLayerState dispatches UPDATE_GRANULE_LAYER_GEOMETRY and ADD_GRANULE_LAYER_DATES when layer exists [layers-action-update-granule-layer-state-existing]', () => {
+ const granuleDates = ['2021-01-03T00:00:00Z'];
+ const mockFootprints = { type: 'FeatureCollection', features: [] };
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ count: 20,
+ granuleDates,
+ reorderedGranules: null,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ const existingState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: { ...getState(layers).layers.active, granulePlatform: 'Aqua / MODIS' },
+ granuleFootprints: mockFootprints,
+ },
+ };
+ getGranuleFootprints.mockReturnValue(mockFootprints);
+ getGranuleLayer.mockReturnValue({ id: 'aqua-aod' });
+ const existingStore = mockStore(existingState);
+ existingStore.dispatch(updateGranuleLayerState(mockLayer));
+ const actions = existingStore.getActions();
+ expect(actions).toHaveLength(2);
+ expect(actions[0].type).toBe(LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_GEOMETRY);
+ expect(actions[1].type).toBe(LAYER_CONSTANTS.ADD_GRANULE_LAYER_DATES);
+ });
+
+ test('updateGranuleLayerState uses reorderedGranules when provided [layers-action-update-granule-layer-state-reordered]', () => {
+ const granuleDates = ['2021-01-03T00:00:00Z', '2021-01-01T00:00:00Z'];
+ const reorderedGranules = ['2021-01-01T00:00:00Z', '2021-01-03T00:00:00Z'];
+ const mockFootprints = { type: 'FeatureCollection', features: [] };
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ count: 20,
+ granuleDates,
+ reorderedGranules,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ getGranuleFootprints.mockReturnValue(mockFootprints);
+ getGranuleLayer.mockReturnValue({ id: 'aqua-aod' });
+ const existingState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: { ...getState(layers).layers.active, granulePlatform: 'Aqua / MODIS' },
+ granuleFootprints: mockFootprints,
+ },
+ };
+ const existingStore = mockStore(existingState);
+ existingStore.dispatch(updateGranuleLayerState(mockLayer));
+ const geometryAction = existingStore.getActions().find(
+ (a) => a.type === LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_GEOMETRY,
+ );
+ expect(geometryAction.dates).toEqual(reorderedGranules);
+ });
+
+ test('updateGranuleLayerState sets dates to empty array when most recent date is out of range [layers-action-update-granule-layer-state-out-of-range]', () => {
+ const granuleDates = ['2031-01-01T00:00:00Z', '2021-01-01T00:00:00Z'];
+ const mockFootprints = { type: 'FeatureCollection', features: [] };
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ count: 20,
+ granuleDates,
+ reorderedGranules: null,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ const existingState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: { ...getState(layers).layers.active, granulePlatform: 'Aqua / MODIS' },
+ granuleFootprints: mockFootprints,
+ },
+ };
+ getGranuleFootprints.mockReturnValue(mockFootprints);
+ getGranuleLayer.mockReturnValue({ id: 'aqua-aod' });
+ const outOfRangeStore = mockStore(existingState);
+ outOfRangeStore.dispatch(updateGranuleLayerState(mockLayer));
+ const geometryAction = outOfRangeStore.getActions().find(
+ (a) => a.type === LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_GEOMETRY,
+ );
+ expect(geometryAction.dates).toEqual([]);
+ });
+
+ test('updateGranuleLayerState UPDATE_GRANULE_LAYER_GEOMETRY uses incoming geometry when active platform matches [layers-action-update-granule-geometry-active-platform]', () => {
+ const granuleDates = ['2021-01-01T00:00:00Z'];
+ const newFootprints = { type: 'FeatureCollection', features: [{ id: 'old' }] };
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ count: 10,
+ granuleDates,
+ reorderedGranules: null,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ const matchingState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: { ...getState(layers).layers.active, granulePlatform: 'Aqua / MODIS' },
+ granuleFootprints: { type: 'FeatureCollection', features: [{ id: 'old' }] },
+ },
+ };
+ getGranuleFootprints.mockReturnValue(newFootprints);
+ getGranuleLayer.mockReturnValue({ id: 'aqua-aod' });
+ const matchingStore = mockStore(matchingState);
+ matchingStore.dispatch(updateGranuleLayerState(mockLayer));
+ const geometryAction = matchingStore.getActions().find(
+ (a) => a.type === LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_GEOMETRY,
+ );
+ expect(geometryAction.granuleFootprints).toEqual(newFootprints);
+ });
+
+ test('updateGranuleLayerState UPDATE_GRANULE_LAYER_GEOMETRY uses existing global geometry when platform does not match [layers-action-update-granule-geometry-inactive-platform]', () => {
+ const granuleDates = ['2021-01-01T00:00:00Z'];
+ const newFootprints = { type: 'FeatureCollection', features: [{ id: 'new' }] };
+ const existingGlobalFootprints = { type: 'FeatureCollection', features: [{ id: 'global' }] };
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ count: 10,
+ granuleDates,
+ reorderedGranules: null,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ const nonMatchingState = {
+ ...getState(layers),
+ layers: {
+ ...getState(layers).layers,
+ active: { ...getState(layers).layers.active, granulePlatform: 'Terra / MODIS' },
+ granuleFootprints: existingGlobalFootprints,
+ },
+ };
+ getGranuleFootprints.mockReturnValue(newFootprints);
+ getGranuleLayer.mockReturnValue({ id: 'aqua-aod' });
+ const nonMatchingStore = mockStore(nonMatchingState);
+ nonMatchingStore.dispatch(updateGranuleLayerState(mockLayer));
+ const geometryAction = nonMatchingStore.getActions().find(
+ (a) => a.type === LAYER_CONSTANTS.UPDATE_GRANULE_LAYER_GEOMETRY,
+ );
+ expect(geometryAction.granuleFootprints).toEqual(existingGlobalFootprints);
+ });
+
+ test('updateGranuleLayerState ADD_GRANULE_LAYER_DATES always uses layer.wv.granuleDates not reorderedGranules [layers-action-add-granule-layer-dates-uses-granule-dates]', () => {
+ const granuleDates = ['2021-03-01T00:00:00Z', '2021-02-01T00:00:00Z'];
+ const reorderedGranules = ['2021-02-01T00:00:00Z', '2021-03-01T00:00:00Z'];
+ const mockFootprints = { type: 'FeatureCollection', features: [] };
+ const mockLayer = {
+ wv: {
+ id: 'aqua-aod',
+ count: 5,
+ granuleDates,
+ reorderedGranules,
+ def: { endDate: '2030-01-01T00:00:00Z', subtitle: 'Aqua / MODIS' },
+ },
+ };
+ getGranuleFootprints.mockReturnValue(mockFootprints);
+ getGranuleLayer.mockReturnValue(null);
+ store.dispatch(updateGranuleLayerState(mockLayer));
+ const datesAction = store.getActions().find(
+ (a) => a.type === LAYER_CONSTANTS.ADD_GRANULE_LAYER_DATES,
+ );
+ expect(datesAction.dates).toEqual(granuleDates);
+ expect(datesAction.granuleFootprints).toEqual(mockFootprints);
+ expect(datesAction.granulePlatform).toBe('Aqua / MODIS');
+ expect(datesAction.id).toBe('aqua-aod');
+ expect(datesAction.count).toBe(5);
+ expect(datesAction.activeKey).toBe('active');
+ });
+
+ test('UPDATE_DDV_LAYER dispatches correct action with id, activeString, layers, and layerIndex [layers-action-update-band-combination]', () => {
+ const bandCombo = { r: 'B04', g: 'B03', b: 'B02' };
+ const selectedPreset = 'natural-color';
+ const layerIndex = 2;
+ store.dispatch(updateBandCombination('aqua-aod', bandCombo, layerIndex, selectedPreset));
+ const actionResponse = store.getActions()[0];
+ expect(actionResponse.type).toBe(LAYER_CONSTANTS.UPDATE_DDV_LAYER);
+ expect(actionResponse.id).toBe('aqua-aod');
+ expect(actionResponse.activeString).toBe('active');
+ expect(actionResponse.layerIndex).toBe(layerIndex);
+ expect(Array.isArray(actionResponse.layers)).toBe(true);
+ });
+
+ test('UPDATE_DDV_LAYER dispatches with correct layerIndex [layers-action-update-band-combination-layer-index]', () => {
+ const bandCombo = { r: 'B04', g: 'B03', b: 'B02' };
+ store.dispatch(updateBandCombination('aqua-aod', bandCombo, 0, null));
+ expect(store.getActions()[0].layerIndex).toBe(0);
+ });
+
+ test('UPDATE_DDV_LAYER dispatches with null selectedPreset [layers-action-update-band-combination-null-preset]', () => {
+ const bandCombo = { r: 'B04', g: 'B03', b: 'B02' };
+ store.dispatch(updateBandCombination('aqua-aod', bandCombo, 1, null));
+ const actionResponse = store.getActions()[0];
+ expect(actionResponse.type).toBe(LAYER_CONSTANTS.UPDATE_DDV_LAYER);
+ expect(actionResponse.id).toBe('aqua-aod');
+ });
+
+ test('UPDATE_DDV_LAYER uses activeString from compare state [layers-action-update-band-combination-active-string]', () => {
+ const compareState = {
+ ...getState(layers),
+ compare: { activeString: 'activeB', active: true },
};
- expect(actionResponse).toEqual(expectedPayload);
+ const compareStore = mockStore(compareState);
+ compareStore.dispatch(updateBandCombination('aqua-aod', {}, 0, null));
+ expect(compareStore.getActions()[0].activeString).toBe('activeB');
});
});
diff --git a/web/js/modules/layers/reducers.test.js b/web/js/modules/layers/reducers.test.js
index 2bef0d465..466b2f3e3 100644
--- a/web/js/modules/layers/reducers.test.js
+++ b/web/js/modules/layers/reducers.test.js
@@ -14,11 +14,26 @@ import {
ADD_LAYERS_FOR_EVENT,
REORDER_OVERLAY_GROUPS,
REMOVE_GROUP,
+ SYNC_SECOND_LAYER_GROUP,
+ SET_FILTER_RANGE,
+ CLEAR_VECTORSTYLE,
+ ADD_GRANULE_LAYER_DATES,
+ UPDATE_GRANULE_LAYER_OPTIONS,
+ UPDATE_GRANULE_LAYER_GEOMETRY,
+ CHANGE_GRANULE_SATELLITE_INSTRUMENT_GROUP,
+ UPDATE_DDV_LAYER,
+ UPDATE_COLLECTION,
+ ADD_GRANULE_DATE_RANGES,
+ ADD_TEMPO_DATE_RANGES,
} from './constants';
+import {
+ SET_VECTORSTYLE,
+} from '../vector-styles/constants';
import {
SET_CUSTOM as SET_CUSTOM_PALETTE,
CLEAR_CUSTOM as CLEAR_CUSTOM_PALETTE,
SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP,
+ SET_DISABLED_CLASSIFICATION,
} from '../palettes/constants';
const config = fixtures.config();
@@ -144,6 +159,30 @@ describe('layer Reducer tests', () => {
expect(initialState.active).toEqual(response.activeB);
});
+ test('SYNC_SECOND_LAYER_GROUP copies current layer state [layers-reducer-sync-second-layer-group]', () => {
+ const response = layerReducer(initialState, {
+ type: SYNC_SECOND_LAYER_GROUP,
+ });
+ expect(initialState.activeB.layers).toEqual([]);
+ expect(initialState.active).toEqual(response.active);
+ });
+
+ test('SET_FILTER_RANGE updates filter range [layers-reducer-set-filter-range]', () => {
+ const response = layerReducer(initialState, {
+ type: SET_FILTER_RANGE,
+ });
+ expect(initialState.activeB.layers).toEqual([]);
+ expect(initialState.active).toEqual(response.active);
+ });
+
+ test('CLEAR_VECTORSTYLE clears vector style [layers-reducer-clear-vectorstyle]', () => {
+ const response = layerReducer(initialState, {
+ type: CLEAR_VECTORSTYLE,
+ });
+ expect(initialState.activeB.layers).toEqual([]);
+ expect(initialState.active).toEqual(response.active);
+ });
+
test('TOGGLE_LAYER_VISIBILITY action toggles layer state visibility [layers-reducer-toggle-visibility]', () => {
const response = layerReducer(initialState, {
type: TOGGLE_LAYER_VISIBILITY,
@@ -249,4 +288,327 @@ describe('layer Reducer tests', () => {
});
expect(getTestLayer(response.active.layers).opacity).toEqual(0.4);
});
+
+ test('TOGGLE_LAYER_VISIBILITY returns unchanged state when layer id not found [layers-reducer-toggle-visibility-not-found]', () => {
+ const response = layerReducer(initialState, {
+ type: TOGGLE_LAYER_VISIBILITY,
+ id: 'non-existent-layer',
+ visible: false,
+ activeString: 'active',
+ });
+ expect(response).toEqual(initialState);
+ });
+
+ test('TOGGLE_COLLAPSE_OVERLAY_GROUP returns unchanged state when group not found [layers-reducer-collapse-group-not-found]', () => {
+ const response = layerReducer(initialState, {
+ type: TOGGLE_COLLAPSE_OVERLAY_GROUP,
+ groupName: 'NonExistentGroup',
+ activeString: 'active',
+ collapsed: true,
+ });
+ expect(response).toEqual(initialState);
+ });
+
+ test('SYNC_SECOND_LAYER_GROUP adds new A layers not present in B [layers-reducer-sync-second-layer-group-adds-layers]', () => {
+ const stateWithB = {
+ ...initialState,
+ activeB: {
+ ...initialState.activeB,
+ layers: [initialLayers[0]],
+ },
+ };
+ const response = layerReducer(stateWithB, {
+ type: SYNC_SECOND_LAYER_GROUP,
+ lastExitALayerIds: [],
+ });
+ expect(response.activeB.layers.length).toEqual(3);
+ expect(response.activeB.layers.map((l) => l.id)).toContain('aqua-cr');
+ expect(response.activeB.layers.map((l) => l.id)).toContain('terra-cr');
+ });
+
+ test('SYNC_SECOND_LAYER_GROUP does not re-add layers that were in lastExitALayerIds [layers-reducer-sync-second-layer-group-respects-last-exit]', () => {
+ const stateWithB = {
+ ...initialState,
+ activeB: {
+ ...initialState.activeB,
+ layers: [initialLayers[0]],
+ },
+ };
+ const response = layerReducer(stateWithB, {
+ type: SYNC_SECOND_LAYER_GROUP,
+ lastExitALayerIds: ['aqua-cr'],
+ });
+ const bIds = response.activeB.layers.map((l) => l.id);
+ expect(bIds).not.toContain('aqua-cr');
+ expect(bIds).toContain('terra-cr');
+ });
+
+ test('ADD_LAYERS_FOR_EVENT sets eventLayers when provided [layers-reducer-add-layer-for-event-with-event-layers]', () => {
+ const mockEventLayers = ['layer-event-1'];
+ const response = layerReducer(initialState, {
+ type: ADD_LAYERS_FOR_EVENT,
+ activeString: 'active',
+ layers: initialLayers,
+ overlayGroups: initialGroups,
+ eventLayers: mockEventLayers,
+ });
+ expect(response.eventLayers).toEqual(mockEventLayers);
+ });
+
+ test('REORDER_OVERLAY_GROUPS with undefined eventLayers pushes nothing to eventLayers [layers-reducer-reorder-overlay-groups-no-event-layers]', () => {
+ const response = layerReducer(initialState, {
+ type: REORDER_OVERLAY_GROUPS,
+ activeString: 'active',
+ layers: initialLayers,
+ overlayGroups: initialGroups,
+ });
+ expect(response.eventLayers).toEqual([]);
+ });
+
+ test('SET_VECTORSTYLE sets custom vectorStyleId on the layer [layers-reducer-set-vectorstyle]', () => {
+ const response = layerReducer(initialState, {
+ type: SET_VECTORSTYLE,
+ id: 'terra-cr',
+ activeString: 'active',
+ vectorStyleId: 'my-vector-style',
+ });
+ expect(getTestLayer(response.active.layers).custom).toEqual('my-vector-style');
+ });
+
+ test('CLEAR_VECTORSTYLE clears custom on a layer [layers-reducer-clear-vectorstyle-layer]', () => {
+ const stateWithCustom = update(initialState, {
+ active: {
+ layers: {
+ 2: { custom: { $set: 'some-style' } },
+ },
+ },
+ });
+ const response = layerReducer(stateWithCustom, {
+ type: CLEAR_VECTORSTYLE,
+ id: 'terra-cr',
+ activeString: 'active',
+ });
+ expect(getTestLayer(response.active.layers).custom).toEqual('some-style');
+ });
+
+ test('SET_DISABLED_CLASSIFICATION merges props onto the target layer [layers-reducer-set-disabled-classification]', () => {
+ const response = layerReducer(initialState, {
+ type: SET_DISABLED_CLASSIFICATION,
+ id: 'terra-cr',
+ activeString: 'active',
+ props: { disabledClassification: [0, 1] },
+ });
+ expect(getTestLayer(response.active.layers).disabledClassification).toEqual([0, 1]);
+ });
+
+ test('SET_DISABLED_CLASSIFICATION returns unchanged state when layer not found [layers-reducer-set-disabled-classification-not-found]', () => {
+ const response = layerReducer(initialState, {
+ type: SET_DISABLED_CLASSIFICATION,
+ id: 'non-existent-layer',
+ activeString: 'active',
+ props: { disabledClassification: [0] },
+ });
+ expect(response).toEqual(initialState);
+ });
+
+ test('CLEAR_CUSTOM_PALETTE returns unchanged state when layer not found [layers-reducer-clear-custom-palette-not-found]', () => {
+ const response = layerReducer(initialState, {
+ type: 'CLEAR_CUSTOM',
+ id: 'non-existent-layer',
+ activeString: 'active',
+ });
+ expect(response).toEqual(initialState);
+ });
+
+ test('SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP returns unchanged state when layer not found [layers-reducer-update-palettes-not-found]', () => {
+ const response = layerReducer(initialState, {
+ type: SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP,
+ id: 'non-existent-layer',
+ activeString: 'active',
+ props: { squash: true },
+ });
+ expect(response).toEqual(initialState);
+ });
+
+ test('ADD_GRANULE_LAYER_DATES adds granule layer entry to active state [layers-reducer-add-granule-layer-dates]', () => {
+ const granuleDates = ['2021-01-01', '2021-01-02'];
+ const granuleFootprints = { type: 'FeatureCollection', features: [] };
+ const response = layerReducer(initialState, {
+ type: ADD_GRANULE_LAYER_DATES,
+ id: 'terra-cr',
+ activeKey: 'active',
+ dates: granuleDates,
+ granuleFootprints,
+ granulePlatform: 'Terra',
+ count: 2,
+ });
+ expect(response.active.granuleLayers['terra-cr']).toBeDefined();
+ expect(response.active.granuleLayers['terra-cr'].dates).toEqual(granuleDates);
+ expect(response.active.granuleLayers['terra-cr'].granulePlatform).toEqual('Terra');
+ expect(response.active.granuleLayers['terra-cr'].count).toEqual(2);
+ expect(response.active.granuleFootprints).toEqual(granuleFootprints);
+ expect(response.active.granulePlatform).toEqual('Terra');
+ });
+
+ test('UPDATE_GRANULE_LAYER_OPTIONS merges count and dates into existing granule layer [layers-reducer-update-granule-layer-options]', () => {
+ const initialWithGranule = update(initialState, {
+ active: {
+ granuleLayers: {
+ $merge: {
+ 'terra-cr': { dates: [], count: 0, granuleFootprints: {}, granulePlatform: 'Terra' },
+ },
+ },
+ },
+ });
+ const newDates = ['2022-05-01'];
+ const response = layerReducer(initialWithGranule, {
+ type: UPDATE_GRANULE_LAYER_OPTIONS,
+ id: 'terra-cr',
+ activeKey: 'active',
+ count: 5,
+ dates: newDates,
+ });
+ expect(response.active.granuleLayers['terra-cr'].count).toEqual(5);
+ expect(response.active.granuleLayers['terra-cr'].dates).toEqual(newDates);
+ });
+
+ test('UPDATE_GRANULE_LAYER_GEOMETRY updates geometry and footprints for granule layer [layers-reducer-update-granule-layer-geometry]', () => {
+ const initialWithGranule = update(initialState, {
+ active: {
+ granuleLayers: {
+ $merge: {
+ 'terra-cr': { dates: [], count: 0, granuleFootprints: {}, granulePlatform: 'Terra' },
+ },
+ },
+ },
+ });
+ const newFootprints = { type: 'FeatureCollection', features: [{ id: 1 }] };
+ const newDates = ['2022-06-01'];
+ const response = layerReducer(initialWithGranule, {
+ type: UPDATE_GRANULE_LAYER_GEOMETRY,
+ id: 'terra-cr',
+ activeKey: 'active',
+ dates: newDates,
+ granuleFootprints: newFootprints,
+ count: 3,
+ });
+ expect(response.active.granuleLayers['terra-cr'].granuleFootprints).toEqual(newFootprints);
+ expect(response.active.granuleLayers['terra-cr'].count).toEqual(3);
+ expect(response.active.granuleFootprints).toEqual(newFootprints);
+ });
+
+ test('CHANGE_GRANULE_SATELLITE_INSTRUMENT_GROUP sets granulePlatform and geometry [layers-reducer-change-granule-satellite]', () => {
+ const geometry = { type: 'FeatureCollection', features: [] };
+ const response = layerReducer(initialState, {
+ type: CHANGE_GRANULE_SATELLITE_INSTRUMENT_GROUP,
+ activeKey: 'active',
+ granulePlatform: 'Aqua',
+ geometry,
+ });
+ expect(response.active.granulePlatform).toEqual('Aqua');
+ expect(response.active.granuleFootprints).toEqual(geometry);
+ });
+
+ test('ADD_GRANULE_DATE_RANGES sets granuleDateRanges on the target layer [layers-reducer-add-granule-date-ranges]', () => {
+ const dateRanges = [{ startDate: '2020-01-01', endDate: '2020-12-31' }];
+ const response = layerReducer(initialState, {
+ type: ADD_GRANULE_DATE_RANGES,
+ id: 'terra-cr',
+ activeString: 'active',
+ granuleDateRanges: dateRanges,
+ });
+ expect(getTestLayer(response.active.layers).granuleDateRanges).toEqual(dateRanges);
+ });
+
+ test('ADD_GRANULE_DATE_RANGES returns unchanged state when layer not found [layers-reducer-add-granule-date-ranges-not-found]', () => {
+ const response = layerReducer(initialState, {
+ type: ADD_GRANULE_DATE_RANGES,
+ id: 'non-existent-layer',
+ activeString: 'active',
+ granuleDateRanges: [],
+ });
+ expect(response).toEqual(initialState);
+ });
+
+ test('ADD_TEMPO_DATE_RANGES sets tempoDateRanges on the target layer [layers-reducer-add-tempo-date-ranges]', () => {
+ const tempoRanges = [{ startDate: '2023-01-01', endDate: '2023-06-30' }];
+ const response = layerReducer(initialState, {
+ type: ADD_TEMPO_DATE_RANGES,
+ id: 'terra-cr',
+ activeString: 'active',
+ tempoDateRanges: tempoRanges,
+ });
+ expect(getTestLayer(response.active.layers).tempoDateRanges).toEqual(tempoRanges);
+ });
+
+ test('ADD_TEMPO_DATE_RANGES returns unchanged state when layer not found [layers-reducer-add-tempo-date-ranges-not-found]', () => {
+ const response = layerReducer(initialState, {
+ type: ADD_TEMPO_DATE_RANGES,
+ id: 'non-existent-layer',
+ activeString: 'active',
+ tempoDateRanges: [],
+ });
+ expect(response).toEqual(initialState);
+ });
+
+ test('UPDATE_COLLECTION initializes a new collection entry when id does not exist [layers-reducer-update-collection-new]', () => {
+ const payload = [{
+ id: 'new-collection-layer',
+ date: '2021-01-01',
+ type: 'cmr',
+ version: '006',
+ projection: 'geographic',
+ }];
+ const response = layerReducer(initialState, {
+ type: UPDATE_COLLECTION,
+ payload,
+ });
+ expect(response.collections['new-collection-layer']).toBeDefined();
+ expect(response.collections['new-collection-layer'].dates).toHaveLength(1);
+ expect(response.collections['new-collection-layer'].dates[0].version).toEqual('006');
+ });
+
+ test('UPDATE_COLLECTION pushes a new date entry when collection id already exists [layers-reducer-update-collection-existing]', () => {
+ const stateWithCollection = update(initialState, {
+ collections: {
+ $merge: {
+ 'existing-collection': {
+ dates: [{ date: '2020-01-01', type: 'cmr', version: '005', projection: 'geographic' }],
+ },
+ },
+ },
+ });
+ const payload = [{
+ id: 'existing-collection',
+ date: '2021-06-01',
+ type: 'cmr',
+ version: '006',
+ projection: 'geographic',
+ }];
+ const response = layerReducer(stateWithCollection, {
+ type: UPDATE_COLLECTION,
+ payload,
+ });
+ expect(response.collections['existing-collection'].dates).toHaveLength(2);
+ expect(response.collections['existing-collection'].dates[1].date).toEqual('2021-06-01');
+ });
+
+ test('UPDATE_DDV_LAYER moves the target layer to the specified index [layers-reducer-update-ddv-layer]', () => {
+ const layersCopy = initialLayers.map((l) => ({ ...l }));
+ const response = layerReducer(initialState, {
+ type: UPDATE_DDV_LAYER,
+ activeString: 'active',
+ id: 'terra-cr',
+ layerIndex: 0,
+ layers: layersCopy,
+ });
+ expect(response.active.layers[0].id).toEqual('terra-cr');
+ });
+
+ test('unknown action type returns unchanged state [layers-reducer-default]', () => {
+ const response = layerReducer(initialState, {
+ type: 'UNKNOWN_ACTION_TYPE',
+ });
+ expect(response).toEqual(initialState);
+ });
});
diff --git a/web/js/modules/layers/selectors.test.js b/web/js/modules/layers/selectors.test.js
index 986f0ddbf..f22ac0dd7 100644
--- a/web/js/modules/layers/selectors.test.js
+++ b/web/js/modules/layers/selectors.test.js
@@ -9,6 +9,23 @@ import {
pushToBottom,
moveBefore,
getFutureLayerEndDate,
+ hasSubDaily,
+ getSubDaily,
+ hasMeasurementSetting,
+ hasMeasurementSource,
+ getTitles,
+ getFilteredOverlayGroups,
+ getActiveLayers,
+ getActiveOverlayGroups,
+ getActiveVisibleLayersAtDate,
+ getCollections,
+ findEventLayers,
+ replaceSubGroup,
+ makeGetDescription,
+ getSmallestIntervalValue,
+ activateLayersForEventCategory,
+ getZotsForActiveLayers,
+ getMaxZoomLevelLayerCollection,
} from './selectors';
const config = fixtures.config();
@@ -25,6 +42,169 @@ function getState(layers) {
date: { selected: new Date(Date.UTC(2014, 0, 1)) },
};
}
+function getDescriptionState(layerOverrides = {}, measurementOverrides = {}) {
+ return {
+ config: {
+ layers: {
+ 'terra-aod': {
+ id: 'terra-aod',
+ layergroup: 'AOD',
+ ...layerOverrides,
+ },
+ 'orbital-track': {
+ id: 'orbital-track',
+ layergroup: 'Orbital Track',
+ },
+ },
+ measurements: {
+ 'Aerosol Optical Depth': {
+ sources: {
+ MODIS_Terra: {
+ description: 'aerosol-optical-depth/v3',
+ settings: ['terra-aod'],
+ ...measurementOverrides,
+ },
+ },
+ },
+ 'Featured Aerosol': {
+ sources: {
+ MODIS_Terra: {
+ description: 'featured/aerosol',
+ settings: ['terra-aod'],
+ },
+ },
+ },
+ },
+ },
+ };
+}
+
+function getIntervalState(layers) {
+ return {
+ layers: {
+ active: { layers },
+ },
+ compare: { activeString: 'active' },
+ };
+}
+
+function getEventState(activeLayers, categoryLayers) {
+ return {
+ config: {
+ ...config,
+ naturalEvents: {
+ layers: {
+ geographic: {
+ fires: categoryLayers,
+ },
+ },
+ },
+ },
+ proj: { id: 'geographic', selected: config.projections.geographic },
+ layers: {
+ active: { layers: activeLayers },
+ layerConfig: config.layers,
+ },
+ compare: { isCompareA: true, activeString: 'active' },
+ date: { selected: new Date(Date.UTC(2014, 0, 1)) },
+ };
+}
+
+function makeView(zoom) {
+ return { getView: () => ({ getZoom: () => zoom }) };
+}
+
+const emptyNotifications = { object: { layerNotices: [] } };
+
+function getZotState({ activeLayers, zoom, notifications = emptyNotifications, sources = {} }) {
+ return {
+ config: {
+ ...config,
+ sources,
+ },
+ proj: { id: 'geographic', selected: config.projections.geographic },
+ layers: {
+ active: { layers: activeLayers },
+ },
+ compare: { isCompareA: true, activeString: 'active' },
+ date: { selected: new Date(Date.UTC(2014, 0, 1)) },
+ map: { ui: { selected: makeView(zoom) } },
+ notifications,
+ };
+}
+// A layer with no matrixSet so getZoomLevel always returns null,
+// and minZoom at or below the current zoom so underZoom is not triggered.
+function makeSimpleLayer(id, projection = 'geographic', minZoom = 0) {
+ return {
+ id,
+ group: 'overlays',
+ visible: true,
+ opacity: 1,
+ minZoom,
+ projections: {
+ [projection]: { matrixSet: undefined, source: 'GIBS:geographic' },
+ },
+ };
+}
+
+// A layer with a matrixSet backed by a resolutions array so overZoom can trigger.
+function makeZoomableLayer(id, resolutionCount, minZoom = 0) {
+ return {
+ id,
+ group: 'overlays',
+ visible: true,
+ opacity: 1,
+ type: 'wmts',
+ minZoom,
+ projections: {
+ geographic: { matrixSet: 'EPSG4326_2km', source: 'GIBS:geographic' },
+ },
+ };
+}
+
+function makeZoomableSources(resolutionCount) {
+ return {
+ 'GIBS:geographic': {
+ matrixSets: {
+ EPSG4326_2km: {
+ resolutions: Array(resolutionCount).fill(0.5),
+ },
+ },
+ },
+ };
+}
+
+function makeLayer(id, proj, matrixSet, source, type = 'wmts') {
+ return {
+ id,
+ type,
+ projections: {
+ [proj]: { matrixSet, source },
+ },
+ };
+}
+
+function makeSources(sourceName, matrixSetName, resolutionCount) {
+ return {
+ [sourceName]: {
+ matrixSets: {
+ [matrixSetName]: {
+ resolutions: Array(resolutionCount).fill(0.5),
+ },
+ },
+ },
+ };
+}
+
+const realNow = util.now.bind(util);
+
+beforeAll(() => {
+ util.now = realNow;
+});
+
+afterEach(() => {
+ util.now = realNow;
+});
test('adds base layer', () => {
let layers = addLayer('terra-cr', [], config.layers, {}, 0);
@@ -396,3 +576,838 @@ test('get future layer end date is 5 days after mock current date', () => {
expect(testDateHours).toEqual(hoursCompareFuture);
expect(testDateDays).toEqual(daysCompareFuture);
});
+
+// ─── hasSubDaily ─────────────────────────────────────────────────────────────
+test('hasSubDaily returns true when a subdaily layer is present', () => {
+ const layers = [{ period: 'daily' }, { period: 'subdaily' }];
+ expect(hasSubDaily(layers)).toBe(true);
+});
+
+test('hasSubDaily returns false when no subdaily layer is present', () => {
+ const layers = [{ period: 'daily' }, { period: 'monthly' }];
+ expect(hasSubDaily(layers)).toBe(false);
+});
+
+test('hasSubDaily returns false for empty array', () => {
+ expect(hasSubDaily([])).toBe(false);
+});
+
+test('hasSubDaily returns false for null/undefined', () => {
+ expect(hasSubDaily(null)).toBe(false);
+ expect(hasSubDaily(undefined)).toBe(false);
+});
+
+// ─── getSubDaily ─────────────────────────────────────────────────────────────
+test('getSubDaily returns only subdaily layers', () => {
+ const layers = [{ id: 'a', period: 'daily' }, { id: 'b', period: 'subdaily' }];
+ const result = getSubDaily(layers);
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('b');
+});
+
+test('getSubDaily returns empty array when no subdaily layers', () => {
+ const layers = [{ id: 'a', period: 'daily' }];
+ expect(getSubDaily(layers)).toEqual([]);
+});
+
+test('getSubDaily returns empty array for null input', () => {
+ expect(getSubDaily(null)).toEqual([]);
+});
+
+// ─── getFutureLayerEndDate – month and year intervals ────────────────────────
+test('getFutureLayerEndDate adds months correctly', () => {
+ const now = util.now();
+ const expected = new Date(now);
+ expected.setUTCMonth(expected.getUTCMonth() + 3);
+ const result = getFutureLayerEndDate({ futureTime: '3M' });
+ expect(result.getUTCMonth()).toBe(util.roundTimeQuarterHour(expected).getUTCMonth());
+});
+
+test('getFutureLayerEndDate adds years correctly', () => {
+ const now = util.now();
+ const expected = new Date(now);
+ expected.setUTCFullYear(expected.getUTCFullYear() + 1);
+ const result = getFutureLayerEndDate({ futureTime: '1Y' });
+ expect(result.getUTCFullYear()).toBe(util.roundTimeQuarterHour(expected).getUTCFullYear());
+});
+
+// ─── dateRange – debugGIBS / ignoreDateRange shortcuts ───────────────────────
+test('dateRange returns epoch-to-now when debugGIBS is true', () => {
+ const layers = addLayer('terra-cr', [], config.layers);
+ const result = dateRange({}, layers, { debugGIBS: true });
+ expect(result.start).toEqual(new Date(Date.UTC(1970, 0, 1)));
+});
+
+test('dateRange returns epoch-to-now when ignoreDateRange is true', () => {
+ const layers = addLayer('terra-cr', [], config.layers);
+ const result = dateRange({}, layers, { ignoreDateRange: true });
+ expect(result.start).toEqual(new Date(Date.UTC(1970, 0, 1)));
+});
+
+// ─── dateRange – specific layer id lookup ────────────────────────────────────
+test('dateRange with specific layer id returns range for that layer only', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('terra-aod', layers, config.layers);
+ const result = dateRange({ layer: 'terra-cr' }, layers);
+ expect(result).toBeTruthy();
+ expect(result.start).toBeDefined();
+});
+
+test('dateRange returns undefined when specific layer id not found in active list', () => {
+ const layers = addLayer('terra-cr', [], config.layers);
+ const result = dateRange({ layer: 'nonexistent-layer' }, layers);
+ expect(result).toBeUndefined();
+});
+
+// ─── dateRange – futureTime with endDate branch ──────────────────────────────
+test('dateRange handles layer with futureTime and endDate', () => {
+ const layersConfig = {
+ future_with_end: {
+ id: 'future_with_end',
+ group: 'overlays',
+ projections: { geographic: {} },
+ startDate: '2020-01-01',
+ endDate: '2030-01-01',
+ futureTime: '10D',
+ ongoing: true,
+ },
+ };
+ const layers = addLayer('future_with_end', [], layersConfig);
+ const result = dateRange({}, layers);
+ expect(result).toBeTruthy();
+ expect(result.end).toEqual(new Date(Date.UTC(2030, 0, 1)));
+});
+
+test('dateRange handles layer with futureTime and no endDate', () => {
+ const layersConfig = {
+ future_no_end: {
+ id: 'future_no_end',
+ group: 'overlays',
+ projections: { geographic: {} },
+ startDate: '2020-01-01',
+ futureTime: '7D',
+ },
+ };
+ const layers = addLayer('future_no_end', [], layersConfig);
+ const result = dateRange({}, layers);
+ console.log(result.end.getTime(), Date.now());
+ expect(result).toBeTruthy();
+ expect(result.end.getTime()).toBeGreaterThan(Date.now());
+});
+
+// ─── pushToBottom – error on inactive layer ───────────────────────────────────
+test('pushToBottom throws when layer is not active', () => {
+ const layers = addLayer('terra-cr', [], config.layers);
+ expect(() => pushToBottom('non-existent', layers)).toThrow();
+});
+
+// ─── pushToBottom – overlay uses layerSplit ───────────────────────────────────
+test('pushToBottom moves overlay to correct position using layerSplit', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers);
+ layers = addLayer('terra-aod', layers, config.layers);
+ layers = addLayer('aqua-aod', layers, config.layers);
+ const overlayCount = layers.filter((l) => l.group === 'overlays').length;
+ layers = pushToBottom('terra-aod', layers, overlayCount + 1);
+ const ids = getLayers(getState(layers)).map((x) => x.id);
+ expect(ids).toContain('terra-aod');
+});
+
+// ─── moveBefore – error cases ─────────────────────────────────────────────────
+test('moveBefore throws when source layer is not active', () => {
+ const layers = addLayer('terra-cr', [], config.layers);
+ layers.push({ id: 'aqua-cr', group: 'baselayers' });
+ expect(() => moveBefore('non-existent', 'aqua-cr', layers)).toThrow();
+});
+
+test('moveBefore throws when target layer is not active', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers);
+ expect(() => moveBefore('terra-cr', 'non-existent', layers)).toThrow();
+});
+
+test('moveBefore moves source after target when source comes after target', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers);
+ layers = addLayer('terra-aod', layers, config.layers);
+ layers = addLayer('aqua-aod', layers, config.layers);
+ moveBefore('aqua-aod', 'terra-aod', layers);
+ const ids = getLayers(getState(layers)).map((x) => x.id);
+ expect(ids.indexOf('aqua-aod')).toBeLessThan(ids.indexOf('terra-aod'));
+});
+
+// ─── replaceSubGroup ──────────────────────────────────────────────────────────
+test('replaceSubGroup calls moveBefore when nextLayerId is provided', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers);
+ layers = addLayer('terra-aod', layers, config.layers);
+ layers = addLayer('aqua-aod', layers, config.layers);
+ const result = replaceSubGroup('aqua-cr', 'terra-cr', layers, 2);
+ const ids = getLayers(getState(result)).map((x) => x.id);
+ expect(ids.indexOf('aqua-cr')).toBeLessThan(ids.indexOf('terra-cr'));
+});
+
+test('replaceSubGroup calls pushToBottom when nextLayerId is null', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers);
+ const result = replaceSubGroup('aqua-cr', null, layers, 1);
+ expect(result.map((l) => l.id)).toContain('aqua-cr');
+});
+
+// ─── getActiveLayers – embed mode filters hidden layers ───────────────────────
+test('getActiveLayers in embed mode returns only visible layers', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers, { visible: false });
+ const state = {
+ ...getState(layers),
+ embed: { isEmbedModeActive: true },
+ };
+ const result = getActiveLayers(state);
+ expect(result.every((l) => l.visible)).toBe(true);
+ expect(result.find((l) => l.id === 'aqua-cr')).toBeUndefined();
+});
+
+test('getActiveLayers in embed mode returns all layers when all are visible', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers);
+ const state = {
+ ...getState(layers),
+ embed: { isEmbedModeActive: true },
+ };
+ const result = getActiveLayers(state);
+ expect(result).toHaveLength(2);
+});
+
+// ─── getActiveVisibleLayersAtDate ─────────────────────────────────────────────
+test('getActiveVisibleLayersAtDate returns renderable layers at date', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('aqua-cr', layers, config.layers);
+ layers = addLayer('terra-aod', layers, config.layers);
+ const state = getState(layers);
+ const result = getActiveVisibleLayersAtDate(state, new Date(Date.UTC(2014, 0, 1)));
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+});
+
+// ─── getCollections ───────────────────────────────────────────────────────────
+test('getCollections returns undefined when layer id not in collections', () => {
+ const layersState = { collections: {} };
+ const result = getCollections(layersState, '2021-01-01', null, { id: 'terra-cr' }, 'geographic');
+ expect(result).toBeUndefined();
+});
+
+test('getCollections returns matching entry by dailyDate and projection', () => {
+ const layersState = {
+ collections: {
+ 'terra-cr': {
+ dates: [
+ { date: '2021-01-01', projection: 'geographic', type: 'cmr', version: '006' },
+ { date: '2021-01-02', projection: 'geographic', type: 'cmr', version: '006' },
+ ],
+ },
+ },
+ };
+ const result = getCollections(layersState, '2021-01-01', null, { id: 'terra-cr' }, 'geographic');
+ expect(result).toBeDefined();
+ expect(result.date).toBe('2021-01-01');
+});
+
+test('getCollections returns matching entry by subdailyDate', () => {
+ const layersState = {
+ collections: {
+ 'terra-cr': {
+ dates: [
+ { date: '2021-01-01T12:00:00Z', projection: 'geographic', type: 'cmr', version: '006' },
+ ],
+ },
+ },
+ };
+ const result = getCollections(layersState, null, '2021-01-01T12:00:00Z', { id: 'terra-cr' }, 'geographic');
+ expect(result).toBeDefined();
+});
+
+test('getCollections returns undefined when date does not match', () => {
+ const layersState = {
+ collections: {
+ 'terra-cr': {
+ dates: [
+ { date: '2021-01-01', projection: 'geographic', type: 'cmr', version: '006' },
+ ],
+ },
+ },
+ };
+ const result = getCollections(layersState, '2022-06-01', null, { id: 'terra-cr' }, 'geographic');
+ expect(result).toBeUndefined();
+});
+
+// ─── getFilteredOverlayGroups ─────────────────────────────────────────────────
+test('getFilteredOverlayGroups removes Reference group', () => {
+ const overlayGroups = [
+ { groupName: 'AOD', layers: ['terra-aod'] },
+ { groupName: 'Reference', layers: ['mask'] },
+ ];
+ const overlays = [{ id: 'terra-aod' }];
+ const result = getFilteredOverlayGroups(overlayGroups, overlays);
+ expect(result.find((g) => g.groupName === 'Reference')).toBeUndefined();
+ expect(result.find((g) => g.groupName === 'AOD')).toBeDefined();
+});
+
+test('getFilteredOverlayGroups filters out layers not in active overlays', () => {
+ const overlayGroups = [
+ { groupName: 'AOD', layers: ['terra-aod', 'aqua-aod'] },
+ ];
+ const overlays = [{ id: 'terra-aod' }];
+ const result = getFilteredOverlayGroups(overlayGroups, overlays);
+ expect(result[0].layers).toEqual(['terra-aod']);
+});
+
+// ─── getActiveOverlayGroups ───────────────────────────────────────────────────
+test('getActiveOverlayGroups returns groups with layers valid for projection', () => {
+ let layers = addLayer('terra-cr', [], config.layers);
+ layers = addLayer('terra-aod', layers, config.layers);
+ const state = {
+ ...getState(layers),
+ layers: {
+ active: {
+ layers,
+ overlayGroups: [{ groupName: 'AOD', layers: ['terra-aod'] }],
+ },
+ },
+ };
+ const result = getActiveOverlayGroups(state);
+ expect(result).toHaveLength(1);
+ expect(result[0].groupName).toBe('AOD');
+});
+
+test('getActiveOverlayGroups in embed mode filters Reference groups and hidden layers', () => {
+ let layers = addLayer('terra-aod', [], config.layers);
+ layers = addLayer('terra-cr', layers, config.layers, { visible: false });
+ const state = {
+ ...getState(layers),
+ embed: { isEmbedModeActive: true },
+ layers: {
+ active: {
+ layers,
+ overlayGroups: [
+ { groupName: 'AOD', layers: ['terra-aod'] },
+ { groupName: 'Reference', layers: ['terra-cr'] },
+ ],
+ },
+ },
+ };
+ const result = getActiveOverlayGroups(state);
+ expect(result.find((g) => g.groupName === 'Reference')).toBeUndefined();
+});
+
+// ─── hasMeasurementSetting ────────────────────────────────────────────────────
+test('hasMeasurementSetting returns true for valid non-orbital-track layer in projection', () => {
+ const mockConfig = {
+ layers: {
+ 'terra-aod': {
+ id: 'terra-aod',
+ layergroup: 'AOD',
+ projections: { geographic: {} },
+ },
+ },
+ };
+ const source = { settings: ['terra-aod'] };
+ const current = { id: 'some-measurement' };
+ const result = hasMeasurementSetting(current, source, mockConfig, 'geographic');
+ expect(result).toBe(true);
+});
+
+test('hasMeasurementSetting returns undefined when layer not in config', () => {
+ const mockConfig = { layers: {} };
+ const source = { settings: ['nonexistent-layer'] };
+ const current = { id: 'some-measurement' };
+ const result = hasMeasurementSetting(current, source, mockConfig, 'geographic');
+ expect(result).toBeUndefined();
+});
+
+test('hasMeasurementSetting returns undefined when layer not in requested projection', () => {
+ const mockConfig = {
+ layers: {
+ 'terra-aod': {
+ id: 'terra-aod',
+ layergroup: 'AOD',
+ projections: { arctic: {} },
+ },
+ },
+ };
+ const source = { settings: ['terra-aod'] };
+ const current = { id: 'some-measurement' };
+ const result = hasMeasurementSetting(current, source, mockConfig, 'geographic');
+ expect(result).toBeUndefined();
+});
+
+test('hasMeasurementSetting returns true for orbital-track layer when current id matches', () => {
+ const mockConfig = {
+ layers: {
+ 'orbital-track': {
+ id: 'orbital-track',
+ layergroup: 'Orbital Track',
+ projections: { geographic: {} },
+ },
+ },
+ };
+ const source = { settings: ['orbital-track'] };
+ const current = { id: 'orbital-track' };
+ const result = hasMeasurementSetting(current, source, mockConfig, 'geographic');
+ expect(result).toBe(true);
+});
+
+test('hasMeasurementSetting returns undefined for orbital-track when current id does not match', () => {
+ const mockConfig = {
+ layers: {
+ 'orbital-track': {
+ id: 'orbital-track',
+ layergroup: 'Orbital Track',
+ projections: { geographic: {} },
+ },
+ },
+ };
+ const source = { settings: ['orbital-track'] };
+ const current = { id: 'some-other-measurement' };
+ const result = hasMeasurementSetting(current, source, mockConfig, 'geographic');
+ expect(result).toBeUndefined();
+});
+
+// ─── hasMeasurementSource ─────────────────────────────────────────────────────
+test('hasMeasurementSource returns true when at least one source has a valid setting', () => {
+ const mockConfig = {
+ layers: {
+ 'terra-aod': {
+ id: 'terra-aod',
+ layergroup: 'AOD',
+ projections: { geographic: {} },
+ },
+ },
+ };
+ const current = {
+ id: 'aod-measurement',
+ sources: {
+ MODIS_Terra: { settings: ['terra-aod'] },
+ },
+ };
+ const result = hasMeasurementSource(current, mockConfig, 'geographic');
+ expect(result).toBe(true);
+});
+
+test('hasMeasurementSource returns undefined when no sources have valid settings', () => {
+ const mockConfig = { layers: {} };
+ const current = {
+ id: 'aod-measurement',
+ sources: {
+ MODIS_Terra: { settings: ['nonexistent'] },
+ },
+ };
+ const result = hasMeasurementSource(current, mockConfig, 'geographic');
+ expect(result).toBeUndefined();
+});
+
+// ─── getTitles ────────────────────────────────────────────────────────────────
+test('getTitles returns layer title, subtitle, and tags', () => {
+ const result = getTitles(config, 'terra-cr', 'geographic');
+ expect(result.title).toBeDefined();
+ expect(result.subtitle).toBeDefined();
+ expect(result.tags).toBeDefined();
+});
+
+test('getTitles throws when layerId does not exist in config', () => {
+ expect(() => getTitles(config, 'nonexistent-layer', 'geographic')).toThrow();
+});
+
+// ─── findEventLayers ──────────────────────────────────────────────────────────
+test('findEventLayers returns ids of layers in newLayers not in originalLayers', () => {
+ const original = [{ id: 'terra-cr' }, { id: 'aqua-cr' }];
+ const next = [{ id: 'terra-cr' }, { id: 'aqua-cr' }, { id: 'modis-fires' }];
+ const result = findEventLayers(original, next);
+ expect(result).toEqual(['modis-fires']);
+});
+
+test('findEventLayers returns empty array when no new layers added', () => {
+ const original = [{ id: 'terra-cr' }];
+ const next = [{ id: 'terra-cr' }];
+ expect(findEventLayers(original, next)).toEqual([]);
+});
+
+test('makeGetDescription returns description for a valid layer', () => {
+ const getDescription = makeGetDescription();
+ const state = getDescriptionState();
+ const result = getDescription(state, { layer: { id: 'terra-aod' } });
+ expect(result).toBe('aerosol-optical-depth/v3');
+});
+
+test('makeGetDescription returns undefined when layerId is not provided', () => {
+ const getDescription = makeGetDescription();
+ const state = getDescriptionState();
+ const result = getDescription(state, { layer: null });
+ expect(result).toBeUndefined();
+});
+
+test('makeGetDescription returns undefined for Orbital Track layers', () => {
+ const getDescription = makeGetDescription();
+ const state = getDescriptionState();
+ const result = getDescription(state, { layer: { id: 'orbital-track' } });
+ expect(result).toBeUndefined();
+});
+
+test('makeGetDescription ignores Featured measurements when resolving description', () => {
+ const getDescription = makeGetDescription();
+ const state = getDescriptionState();
+ const result = getDescription(state, { layer: { id: 'terra-aod' } });
+ expect(result).not.toBe('featured/aerosol');
+ expect(result).toBe('aerosol-optical-depth/v3');
+});
+
+test('makeGetDescription returns undefined when layer exists in config but has no matching measurement source', () => {
+ const getDescription = makeGetDescription();
+ const state = {
+ config: {
+ layers: {
+ 'terra-aod': { id: 'terra-aod', layergroup: 'AOD' },
+ },
+ measurements: {
+ 'Some Measurement': {
+ sources: {
+ MODIS_Terra: {
+ description: 'some/path',
+ settings: ['aqua-aod'],
+ },
+ },
+ },
+ },
+ },
+ };
+ const result = getDescription(state, { layer: { id: 'terra-aod' } });
+ expect(result).toBeUndefined();
+});
+
+test('each makeGetDescription() call creates an independent memoized selector', () => {
+ const getDescriptionA = makeGetDescription();
+ const getDescriptionB = makeGetDescription();
+ const state = getDescriptionState();
+ expect(getDescriptionA).not.toBe(getDescriptionB);
+ expect(getDescriptionA(state, { layer: { id: 'terra-aod' } }))
+ .toBe(getDescriptionB(state, { layer: { id: 'terra-aod' } }));
+});
+
+test('returns 1440 (default) when there are no layers', () => {
+ const state = getIntervalState([]);
+ expect(getSmallestIntervalValue(state)).toBe(1440);
+});
+
+test('returns 1440 (default) when no layers have subdaily period', () => {
+ const state = getIntervalState([
+ { id: 'terra-cr', period: 'daily', dateRanges: [{ dateInterval: '1' }] },
+ { id: 'aqua-cr', period: 'monthly', dateRanges: [{ dateInterval: '30' }] },
+ ]);
+ expect(getSmallestIntervalValue(state)).toBe(1440);
+});
+
+test('returns the interval of a single subdaily layer', () => {
+ const state = getIntervalState([
+ { id: 'viirs-subdaily', period: 'subdaily', dateRanges: [{ dateInterval: '10' }] },
+ ]);
+ expect(getSmallestIntervalValue(state)).toBe(10);
+});
+
+test('returns the smallest interval across multiple subdaily layers', () => {
+ const state = getIntervalState([
+ { id: 'layer-a', period: 'subdaily', dateRanges: [{ dateInterval: '60' }] },
+ { id: 'layer-b', period: 'subdaily', dateRanges: [{ dateInterval: '10' }] },
+ { id: 'layer-c', period: 'subdaily', dateRanges: [{ dateInterval: '30' }] },
+ ]);
+ expect(getSmallestIntervalValue(state)).toBe(10);
+});
+
+test('ignores non-subdaily layers when selecting smallest interval', () => {
+ const state = getIntervalState([
+ { id: 'daily-layer', period: 'daily', dateRanges: [{ dateInterval: '1' }] },
+ { id: 'subdaily-layer', period: 'subdaily', dateRanges: [{ dateInterval: '20' }] },
+ ]);
+ expect(getSmallestIntervalValue(state)).toBe(20);
+});
+
+test('returns 1440 when subdaily layer has no dateRanges', () => {
+ const state = getIntervalState([
+ { id: 'subdaily-no-range', period: 'subdaily' },
+ ]);
+ expect(getSmallestIntervalValue(state)).toBe(1440);
+});
+
+test('returns 1440 when subdaily layer dateRanges is empty', () => {
+ const state = getIntervalState([
+ { id: 'subdaily-empty-range', period: 'subdaily', dateRanges: [] },
+ ]);
+ expect(getSmallestIntervalValue(state)).toBe(1440);
+});
+
+test('handles string interval values by coercing to number', () => {
+ const state = getIntervalState([
+ { id: 'layer-a', period: 'subdaily', dateRanges: [{ dateInterval: '5' }] },
+ ]);
+ const result = getSmallestIntervalValue(state);
+ expect(result).toBe(5);
+ expect(typeof result).toBe('number');
+});
+
+test('does not update smallestDelta when interval is larger than current smallest', () => {
+ const state = getIntervalState([
+ { id: 'layer-a', period: 'subdaily', dateRanges: [{ dateInterval: '10' }] },
+ { id: 'layer-b', period: 'subdaily', dateRanges: [{ dateInterval: '120' }] },
+ ]);
+ expect(getSmallestIntervalValue(state)).toBe(10);
+});
+
+test('returns active layers unchanged when category has no layers defined for projection', () => {
+ let activeLayers = addLayer('terra-cr', [], config.layers);
+ activeLayers = addLayer('terra-aod', activeLayers, config.layers);
+ const state = getEventState(activeLayers, undefined);
+ const result = activateLayersForEventCategory(state, 'fires');
+ expect(result.map((l) => l.id)).toEqual(activeLayers.map((l) => l.id));
+});
+
+test('turns off all current layers before applying event category layers', () => {
+ let activeLayers = addLayer('terra-cr', [], config.layers);
+ activeLayers = addLayer('terra-aod', activeLayers, config.layers);
+ const state = getEventState(activeLayers, [['terra-cr', true]]);
+ const result = activateLayersForEventCategory(state, 'fires');
+ const terAod = result.find((l) => l.id === 'terra-aod');
+ expect(terAod.visible).toBe(false);
+});
+
+test('turns on a layer that already exists in the active list', () => {
+ let activeLayers = addLayer('terra-cr', [], config.layers);
+ activeLayers = addLayer('terra-aod', activeLayers, config.layers);
+ const state = getEventState(activeLayers, [['terra-cr', true]]);
+ const result = activateLayersForEventCategory(state, 'fires');
+ const terraCr = result.find((l) => l.id === 'terra-cr');
+ expect(terraCr.visible).toBe(true);
+});
+
+test('keeps a layer hidden when category specifies it as not visible', () => {
+ let activeLayers = addLayer('terra-cr', [], config.layers);
+ activeLayers = addLayer('terra-aod', activeLayers, config.layers);
+ const state = getEventState(activeLayers, [['terra-cr', false]]);
+ const result = activateLayersForEventCategory(state, 'fires');
+ const terraCr = result.find((l) => l.id === 'terra-cr');
+ expect(terraCr.visible).toBe(false);
+});
+
+test('adds a layer that does not yet exist in the active list', () => {
+ const activeLayers = addLayer('terra-cr', [], config.layers);
+ const state = getEventState(activeLayers, [['terra-aod', true]]);
+ const result = activateLayersForEventCategory(state, 'fires');
+ const newLayer = result.find((l) => l.id === 'terra-aod');
+ expect(newLayer).toBeDefined();
+ expect(newLayer.visible).toBe(true);
+});
+
+test('adds a new layer with visible set to false when category specifies hidden', () => {
+ const activeLayers = addLayer('terra-cr', [], config.layers);
+ const state = getEventState(activeLayers, [['terra-aod', false]]);
+ const result = activateLayersForEventCategory(state, 'fires');
+ const newLayer = result.find((l) => l.id === 'terra-aod');
+ expect(newLayer).toBeDefined();
+ expect(newLayer.visible).toBe(false);
+});
+
+test('handles multiple category layers — turning on existing and adding new', () => {
+ let activeLayers = addLayer('terra-cr', [], config.layers);
+ activeLayers = addLayer('aqua-cr', activeLayers, config.layers);
+ const state = getEventState(activeLayers, [
+ ['terra-cr', true],
+ ['terra-aod', true],
+ ]);
+ const result = activateLayersForEventCategory(state, 'fires');
+ expect(result.find((l) => l.id === 'terra-cr').visible).toBe(true);
+ expect(result.find((l) => l.id === 'aqua-cr').visible).toBe(false);
+ expect(result.find((l) => l.id === 'terra-aod')).toBeDefined();
+ expect(result.find((l) => l.id === 'terra-aod').visible).toBe(true);
+});
+
+test('returns an array', () => {
+ const activeLayers = addLayer('terra-cr', [], config.layers);
+ const state = getEventState(activeLayers, [['terra-cr', true]]);
+ const result = activateLayersForEventCategory(state, 'fires');
+ expect(Array.isArray(result)).toBe(true);
+});
+
+test('does not mutate the original active layers array', () => {
+ let activeLayers = addLayer('terra-cr', [], config.layers);
+ activeLayers = addLayer('terra-aod', activeLayers, config.layers);
+ const originalIds = activeLayers.map((l) => l.id);
+ const state = getEventState(activeLayers, [['terra-cr', true]]);
+ activateLayersForEventCategory(state, 'fires');
+ expect(activeLayers.map((l) => l.id)).toEqual(originalIds);
+});
+
+test('returns an empty object when no layers are active', () => {
+ const state = getZotState({ activeLayers: [], zoom: 5 });
+ expect(getZotsForActiveLayers(state)).toEqual({});
+});
+
+test('returns an empty object when no zot conditions are met', () => {
+ const layer = makeSimpleLayer('terra-aod');
+ const state = getZotState({ activeLayers: [layer], zoom: 3 });
+ const result = getZotsForActiveLayers(state);
+ expect(result['terra-aod']).toBeUndefined();
+});
+
+test('includes a layer entry when overZoom is triggered', () => {
+ const resolutionCount = 4; // zoomLimit = 3
+ const layer = makeZoomableLayer('terra-aod', resolutionCount);
+ const sources = makeZoomableSources(resolutionCount);
+ const state = getZotState({ activeLayers: [layer], zoom: 5, sources });
+ const result = getZotsForActiveLayers(state);
+ expect(result['terra-aod']).toBeDefined();
+ expect(result['terra-aod'].overZoomValue).toBeGreaterThan(0);
+});
+
+test('overZoomValue is calculated as zoom minus zoomLimit rounded to 2 decimals', () => {
+ const resolutionCount = 4; // zoomLimit = 3
+ const layer = makeZoomableLayer('terra-aod', resolutionCount);
+ const sources = makeZoomableSources(resolutionCount);
+ const state = getZotState({ activeLayers: [layer], zoom: 5, sources });
+ const result = getZotsForActiveLayers(state);
+ expect(result['terra-aod'].overZoomValue).toBe(2); // 5 - 3 = 2
+});
+
+test('does not include a layer entry when zoom is exactly at the zoomLimit', () => {
+ const resolutionCount = 4; // zoomLimit = 3
+ const layer = makeZoomableLayer('terra-aod', resolutionCount);
+ const sources = makeZoomableSources(resolutionCount);
+ const state = getZotState({ activeLayers: [layer], zoom: 3, sources });
+ const result = getZotsForActiveLayers(state);
+ expect(result['terra-aod']).toBeUndefined();
+});
+
+test('includes a layer entry when underZoom is triggered (minZoom > zoom)', () => {
+ const layer = makeSimpleLayer('terra-aod', 'geographic', 8);
+ const state = getZotState({ activeLayers: [layer], zoom: 4 });
+ const result = getZotsForActiveLayers(state);
+ expect(result['terra-aod']).toBeDefined();
+ expect(result['terra-aod'].underZoomValue).toBeGreaterThan(0);
+});
+
+test('underZoomValue is calculated as minZoom minus zoom rounded to 2 decimals', () => {
+ const layer = makeSimpleLayer('terra-aod', 'geographic', 8);
+ const state = getZotState({ activeLayers: [layer], zoom: 5 });
+ const result = getZotsForActiveLayers(state);
+ expect(result['terra-aod'].underZoomValue).toBe(3); // 8 - 5 = 3
+});
+
+test('does not include a layer entry when underZoomValue is zero', () => {
+ const layer = makeSimpleLayer('terra-aod', 'geographic', 5);
+ const state = getZotState({ activeLayers: [layer], zoom: 5 });
+ const result = getZotsForActiveLayers(state);
+ expect(result['terra-aod']).toBeUndefined();
+});
+
+test('skips layers that are not available in the current projection', () => {
+ const layer = makeSimpleLayer('arctic-layer', 'arctic', 0);
+ const state = getZotState({ activeLayers: [layer], zoom: 10 });
+ const result = getZotsForActiveLayers(state);
+ expect(result['arctic-layer']).toBeUndefined();
+});
+
+test('returns entries for multiple layers with independent zot conditions', () => {
+ const resolutionCount = 4;
+ const overZoomedLayer = makeZoomableLayer('layer-a', resolutionCount, 0);
+ const underZoomedLayer = makeSimpleLayer('layer-b', 'geographic', 10);
+ const normalLayer = makeSimpleLayer('layer-c', 'geographic', 0);
+ const sources = makeZoomableSources(resolutionCount);
+ const state = getZotState({
+ activeLayers: [overZoomedLayer, underZoomedLayer, normalLayer],
+ zoom: 6,
+ sources,
+ });
+ const result = getZotsForActiveLayers(state);
+ expect(result['layer-a']).toBeDefined();
+ expect(result['layer-b']).toBeDefined();
+ expect(result['layer-c']).toBeUndefined();
+});
+
+test('returns fallback zoom when layers array is empty', () => {
+ expect(getMaxZoomLevelLayerCollection([], 8, 'geographic', {})).toBe(8);
+});
+
+test('returns fallback zoom when layer has no matrixSet', () => {
+ const layer = makeLayer('layer-a', 'geographic', undefined, 'GIBS:geographic');
+ const sources = makeSources('GIBS:geographic', 'EPSG4326_2km', 6);
+ expect(getMaxZoomLevelLayerCollection([layer], 8, 'geographic', sources)).toBe(8);
+});
+
+test('returns fallback zoom when layer type is vector', () => {
+ const layer = makeLayer('layer-a', 'geographic', 'EPSG4326_2km', 'GIBS:geographic', 'vector');
+ const sources = makeSources('GIBS:geographic', 'EPSG4326_2km', 6);
+ expect(getMaxZoomLevelLayerCollection([layer], 8, 'geographic', sources)).toBe(8);
+});
+
+test('returns fallback zoom when resolutions array is missing', () => {
+ const layer = makeLayer('layer-a', 'geographic', 'EPSG4326_2km', 'GIBS:geographic');
+ const sources = { 'GIBS:geographic': { matrixSets: { EPSG4326_2km: {} } } };
+ expect(getMaxZoomLevelLayerCollection([layer], 8, 'geographic', sources)).toBe(8);
+});
+
+test('returns fallback zoom when sources is undefined', () => {
+ const layer = makeLayer('layer-a', 'geographic', 'EPSG4326_2km', 'GIBS:geographic');
+ expect(getMaxZoomLevelLayerCollection([layer], 8, 'geographic', undefined)).toBe(8);
+});
+
+test('returns correct zoomLimit for a single qualifying layer', () => {
+ const layer = makeLayer('layer-a', 'geographic', 'EPSG4326_2km', 'GIBS:geographic');
+ const sources = makeSources('GIBS:geographic', 'EPSG4326_2km', 6); // zoomLimit = 5
+ expect(getMaxZoomLevelLayerCollection([layer], 8, 'geographic', sources)).toBe(5);
+});
+
+test('returns the smallest zoomLimit across multiple qualifying layers', () => {
+ const layerA = makeLayer('layer-a', 'geographic', 'EPSG4326_2km', 'GIBS:geographic');
+ const layerB = makeLayer('layer-b', 'geographic', 'EPSG4326_500m', 'GIBS:geographic');
+ const sources = {
+ 'GIBS:geographic': {
+ matrixSets: {
+ EPSG4326_2km: { resolutions: Array(6).fill(0.5) }, // zoomLimit = 5
+ EPSG4326_500m: { resolutions: Array(9).fill(0.25) }, // zoomLimit = 8
+ },
+ },
+ };
+ expect(getMaxZoomLevelLayerCollection([layerA, layerB], 10, 'geographic', sources)).toBe(5);
+});
+
+test('ignores non-qualifying layers when computing the minimum', () => {
+ const qualifyingLayer = makeLayer('layer-a', 'geographic', 'EPSG4326_2km', 'GIBS:geographic');
+ const vectorLayer = makeLayer('layer-b', 'geographic', 'EPSG4326_2km', 'GIBS:geographic', 'vector');
+ const sources = makeSources('GIBS:geographic', 'EPSG4326_2km', 6); // zoomLimit = 5
+ expect(getMaxZoomLevelLayerCollection([qualifyingLayer, vectorLayer], 10, 'geographic', sources)).toBe(5);
+});
+
+test('applies zoomOffset of 1 for arctic projection', () => {
+ const layer = makeLayer('layer-a', 'arctic', 'EPSG3413_2km', 'GIBS:arctic');
+ const sources = makeSources('GIBS:arctic', 'EPSG3413_2km', 6); // zoomLimit = 5 + 1 = 6
+ expect(getMaxZoomLevelLayerCollection([layer], 10, 'arctic', sources)).toBe(6);
+});
+
+test('applies zoomOffset of 1 for antarctic projection', () => {
+ const layer = makeLayer('layer-a', 'antarctic', 'EPSG3031_2km', 'GIBS:antarctic');
+ const sources = makeSources('GIBS:antarctic', 'EPSG3031_2km', 6); // zoomLimit = 5 + 1 = 6
+ expect(getMaxZoomLevelLayerCollection([layer], 10, 'antarctic', sources)).toBe(6);
+});
+
+test('does not apply zoomOffset for geographic projection', () => {
+ const layer = makeLayer('layer-a', 'geographic', 'EPSG4326_2km', 'GIBS:geographic');
+ const sources = makeSources('GIBS:geographic', 'EPSG4326_2km', 6); // zoomLimit = 5 + 0 = 5
+ expect(getMaxZoomLevelLayerCollection([layer], 10, 'geographic', sources)).toBe(5);
+});
+
+test('returns fallback zoom when all layers are non-qualifying', () => {
+ const layerA = makeLayer('layer-a', 'geographic', undefined, 'GIBS:geographic');
+ const layerB = makeLayer('layer-b', 'geographic', 'EPSG4326_2km', 'GIBS:geographic', 'vector');
+ const sources = makeSources('GIBS:geographic', 'EPSG4326_2km', 6);
+ expect(getMaxZoomLevelLayerCollection([layerA, layerB], 7, 'geographic', sources)).toBe(7);
+});
+
+test('returns fallback zoom of 0 when passed 0 and no qualifying layers', () => {
+ expect(getMaxZoomLevelLayerCollection([], 0, 'geographic', {})).toBe(0);
+});
diff --git a/web/js/modules/layers/util.test.js b/web/js/modules/layers/util.test.js
index 347b8cde8..679b89d85 100644
--- a/web/js/modules/layers/util.test.js
+++ b/web/js/modules/layers/util.test.js
@@ -8,6 +8,12 @@ import {
isVectorLayerClickable,
hasNonClickableVectorLayer,
hasVectorLayers,
+ adjustStartDates,
+ adjustEndDates,
+ getCacheOptions,
+ mockFutureTimeLayerOptions,
+ getLayersFromGroups,
+ adjustMeasurementsValidUnitConversion,
} from './util';
import { initialState } from './reducers';
import fixtures from '../../fixtures';
@@ -415,3 +421,299 @@ describe('Vector layers', () => {
expect(true1).toBe(true);
});
});
+
+describe('adjustStartDates', () => {
+ const buildConfig = (layerOverrides = {}) => ({
+ timeBounds: {
+ time: '2020-06-15T00:00:00Z',
+ },
+ layers: {
+ 'test-layer': {
+ id: 'test-layer',
+ availability: {
+ rollingWindow: 30,
+ historicalRanges: [
+ { startDate: '2010-01-01T00:00:00Z', endDate: '2015-01-01T00:00:00Z', dateInterval: '1' },
+ { startDate: '2015-01-02T00:00:00Z', endDate: '2019-12-31T00:00:00Z', dateInterval: '1' },
+ ],
+ },
+ startDate: '2000-01-01',
+ dateRanges: [
+ {
+ startDate: '2020-06-01T00:00:00Z',
+ endDate: '2021-01-01T00:00:00Z',
+ dateInterval: '1',
+ },
+ ],
+ ...layerOverrides,
+ },
+ },
+ });
+
+ test('skips layer without rollingWindow [adjust-start-dates-no-rolling-window]', () => {
+ const config = buildConfig({ rollingWindow: undefined });
+ const originalStartDate = config.layers['test-layer'].startDate;
+ adjustStartDates(config);
+ expect(config.layers['test-layer'].startDate).toBe(originalStartDate);
+ });
+
+ test('sets layer startDate from adjustDate when no historicalRanges [adjust-start-dates-no-historical-ranges]', () => {
+ const config = buildConfig();
+ adjustStartDates(config.layers);
+ const layer = config.layers['test-layer'];
+ expect(layer.startDate).toBeDefined();
+ expect(layer.startDate).not.toBe('2000-01-01');
+ });
+});
+
+describe('getCacheOptions', () => {
+ test('returns empty object when not subdaily', () => {
+ const options = getCacheOptions('daily', new Date());
+ expect(options).toEqual({});
+ });
+
+ test('returns expirationAbsolute when subdaily', () => {
+ const options = getCacheOptions('subdaily', new Date());
+ const tenMin = 10 * 60000;
+ const now = new Date().getTime();
+ expect(options).toEqual({ expirationAbsolute: new Date(now + tenMin)});
+ });
+});
+
+describe('adjustEndDates', () => {
+ const buildConfig = (layerOverrides = {}) => ({
+ timeBounds: {
+ time: '2020-06-15T00:00:00Z',
+ },
+ layers: {
+ 'test-layer': {
+ id: 'test-layer',
+ availability: {
+ rollingWindow: 30,
+ historicalRanges: [
+ { startDate: '2010-01-01T00:00:00Z', endDate: '2015-01-01T00:00:00Z', dateInterval: '1' },
+ { startDate: '2015-01-02T00:00:00Z', endDate: '2019-12-31T00:00:00Z', dateInterval: '1' },
+ ],
+ },
+ endDate: '2022-01-01',
+ dateRanges: [
+ {
+ startDate: '2020-06-01T00:00:00Z',
+ endDate: '2021-01-01T00:00:00Z',
+ dateInterval: '1',
+ },
+ ],
+ ...layerOverrides,
+ },
+ },
+ });
+
+ test('skips layer without rollingWindow [adjust-end-dates-no-rolling-window]', () => {
+ const config = buildConfig({ rollingWindow: undefined });
+ const originalEndDate = config.layers['test-layer'].endDate;
+ adjustEndDates(config);
+ expect(config.layers['test-layer'].endDate).toBe(originalEndDate);
+ });
+
+ test('sets layer endDate from adjustDate when no historicalRanges [adjust-end-dates-no-historical-ranges]', () => {
+ const config = buildConfig({ futureTime: '2023-01-01T00:00:00Z' });
+ adjustEndDates(config.layers);
+ const layer = config.layers['test-layer'];
+ expect(layer.endDate).toBeDefined();
+ expect(layer.endDate).not.toBe('2022-01-01');
+ });
+});
+
+describe('mockFutureTimeLayerOptions', () => {
+ test('sets futureTime on target layer when valid parameters provided [mock-future-time-sets-value]', () => {
+ const layers = {
+ 'terra-cr': { id: 'terra-cr' },
+ };
+ mockFutureTimeLayerOptions(layers, 'terra-cr,2030-01-01');
+ expect(layers['terra-cr'].futureTime).toBe('2030-01-01');
+ });
+
+ test('does not modify layer when targetLayerId does not exist in layers [mock-future-time-missing-layer]', () => {
+ const layers = {
+ 'terra-cr': { id: 'terra-cr' },
+ };
+ mockFutureTimeLayerOptions(layers, 'aqua-cr,2030-01-01');
+ expect(layers['terra-cr'].futureTime).toBeUndefined();
+ });
+
+ test('does not set futureTime when mockFutureTime is missing from parameters [mock-future-time-missing-time]', () => {
+ const layers = {
+ 'terra-cr': { id: 'terra-cr' },
+ };
+ mockFutureTimeLayerOptions(layers, 'terra-cr');
+ expect(layers['terra-cr'].futureTime).toBeUndefined();
+ });
+
+ test('does not set futureTime when targetLayerId is missing from parameters [mock-future-time-missing-id]', () => {
+ const layers = {
+ 'terra-cr': { id: 'terra-cr' },
+ };
+ mockFutureTimeLayerOptions(layers, ',2030-01-01');
+ expect(layers['terra-cr'].futureTime).toBeUndefined();
+ });
+
+ test('sets futureTime on correct layer when multiple layers exist [mock-future-time-multiple-layers]', () => {
+ const layers = {
+ 'terra-cr': { id: 'terra-cr' },
+ 'aqua-cr': { id: 'aqua-cr' },
+ };
+ mockFutureTimeLayerOptions(layers, 'aqua-cr,2030-06-15');
+ expect(layers['aqua-cr'].futureTime).toBe('2030-06-15');
+ expect(layers['terra-cr'].futureTime).toBeUndefined();
+ });
+
+ test('overwrites existing futureTime value on target layer [mock-future-time-overwrite]', () => {
+ const layers = {
+ 'terra-cr': { id: 'terra-cr', futureTime: '2025-01-01' },
+ };
+ mockFutureTimeLayerOptions(layers, 'terra-cr,2030-01-01');
+ expect(layers['terra-cr'].futureTime).toBe('2030-01-01');
+ });
+});
+
+describe('getLayersFromGroups', () => {
+ test('returns empty array when groups is falsy [get-layers-from-groups-no-groups]', () => {
+ const result = getLayersFromGroups(globalState, null);
+ expect(result).toEqual([]);
+ });
+
+ test('returns empty array when groups is undefined [get-layers-from-groups-undefined]', () => {
+ const result = getLayersFromGroups(globalState, undefined);
+ expect(result).toEqual([]);
+ });
+
+ test('returns baselayers concatenated when groups is an empty array [get-layers-from-groups-empty-array]', () => {
+ const result = getLayersFromGroups(globalState, []);
+ result.forEach((layer) => {
+ expect(layer.group).toBe('baselayers');
+ });
+ });
+
+ test('returns mapped overlay layers plus baselayers when groups provided [get-layers-from-groups-with-groups]', () => {
+ const overlayGroups = globalState.layers.active.overlayGroups;
+ if (!overlayGroups || !overlayGroups.length) return;
+ const result = getLayersFromGroups(globalState, overlayGroups);
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBeGreaterThan(0);
+ });
+});
+
+describe('adjustMeasurementsValidUnitConversion', () => {
+ test('sets disableUnitConversion on layer when measurement has disableUnitConversion true [adjust-measurements-disable-conversion]', () => {
+ const layerConfig = {
+ id: 'test-layer',
+ layergroup: 'test-group',
+ };
+ const measurementConfig = {
+ measurements: {
+ 'test-group': {
+ disableUnitConversion: true,
+ },
+ },
+ layers: {
+ 'test-layer': layerConfig,
+ },
+ };
+ adjustMeasurementsValidUnitConversion(measurementConfig);
+ expect(layerConfig.disableUnitConversion).toBe(true);
+ });
+
+ test('does not set disableUnitConversion when measurement does not have disableUnitConversion [adjust-measurements-no-disable]', () => {
+ const layerConfig = {
+ id: 'test-layer',
+ layergroup: 'test-group',
+ };
+ const measurementConfig = {
+ measurements: {
+ 'test-group': {},
+ },
+ layers: {
+ 'test-layer': layerConfig,
+ },
+ };
+ adjustMeasurementsValidUnitConversion(measurementConfig);
+ expect(layerConfig.disableUnitConversion).toBeUndefined();
+ });
+
+ test('does not modify layer when layergroup is not present on layer [adjust-measurements-no-layergroup]', () => {
+ const layerConfig = {
+ id: 'test-layer',
+ };
+ const measurementConfig = {
+ measurements: {
+ 'test-group': {
+ disableUnitConversion: true,
+ },
+ },
+ layers: {
+ 'test-layer': layerConfig,
+ },
+ };
+ adjustMeasurementsValidUnitConversion(measurementConfig);
+ expect(layerConfig.disableUnitConversion).toBeUndefined();
+ });
+
+ test('does not modify layer when layergroup has no matching measurement [adjust-measurements-no-matching-measurement]', () => {
+ const layerConfig = {
+ id: 'test-layer',
+ layergroup: 'nonexistent-group',
+ };
+ const measurementConfig = {
+ measurements: {
+ 'test-group': {
+ disableUnitConversion: true,
+ },
+ },
+ layers: {
+ 'test-layer': layerConfig,
+ },
+ };
+ adjustMeasurementsValidUnitConversion(measurementConfig);
+ expect(layerConfig.disableUnitConversion).toBeUndefined();
+ });
+
+ test('processes multiple layers independently [adjust-measurements-multiple-layers]', () => {
+ const layerA = { id: 'layer-a', layergroup: 'group-disable' };
+ const layerB = { id: 'layer-b', layergroup: 'group-allow' };
+ const layerC = { id: 'layer-c' };
+ const measurementConfig = {
+ measurements: {
+ 'group-disable': { disableUnitConversion: true },
+ 'group-allow': {},
+ },
+ layers: {
+ 'layer-a': layerA,
+ 'layer-b': layerB,
+ 'layer-c': layerC,
+ },
+ };
+ adjustMeasurementsValidUnitConversion(measurementConfig);
+ expect(layerA.disableUnitConversion).toBe(true);
+ expect(layerB.disableUnitConversion).toBeUndefined();
+ expect(layerC.disableUnitConversion).toBeUndefined();
+ });
+
+ test('does not set disableUnitConversion when measurement disableUnitConversion is false [adjust-measurements-disable-false]', () => {
+ const layerConfig = {
+ id: 'test-layer',
+ layergroup: 'test-group',
+ };
+ const measurementConfig = {
+ measurements: {
+ 'test-group': {
+ disableUnitConversion: false,
+ },
+ },
+ layers: {
+ 'test-layer': layerConfig,
+ },
+ };
+ adjustMeasurementsValidUnitConversion(measurementConfig);
+ expect(layerConfig.disableUnitConversion).toBeUndefined();
+ });
+});
diff --git a/web/js/modules/link/util.test.js b/web/js/modules/link/util.test.js
index 4072f4f95..955acd1e3 100644
--- a/web/js/modules/link/util.test.js
+++ b/web/js/modules/link/util.test.js
@@ -1,3 +1,171 @@
-test('util module test', () => {
+import {
+ facebookUrlParams,
+ twitterUrlParams,
+ redditUrlParams,
+ emailUrlParams,
+ encode,
+ getPermalink,
+ wrapWithIframe,
+} from './util';
+jest.mock('../date/util', () => ({
+ serializeDate: jest.fn(() => '2024-01-15T00:00:00Z'),
+}));
+
+jest.mock('./constants', () => ({
+ ENCODING_EXCEPTIONS: [],
+}));
+
+describe('facebookUrlParams', () => {
+ test('returns correctly encoded Facebook share URL', () => {
+ const result = facebookUrlParams('123', 'https://example.com', 'https://redirect.com', 'popup');
+ expect(result).toBe(
+ `https://www.facebook.com/dialog/share?app_id=${encodeURIComponent('123')}&href=${encodeURIComponent('https://example.com')}&redirect_uri=${encodeURIComponent('https://redirect.com')}&display=${encodeURIComponent('popup')}`,
+ );
+ });
+
+ test('encodes special characters in all params', () => {
+ const result = facebookUrlParams('app&id', 'url with spaces', 'redir?x=1', 'dis play');
+ expect(result).toContain(encodeURIComponent('app&id'));
+ expect(result).toContain(encodeURIComponent('url with spaces'));
+ expect(result).toContain(encodeURIComponent('redir?x=1'));
+ expect(result).toContain(encodeURIComponent('dis play'));
+ });
+});
+
+describe('twitterUrlParams', () => {
+ test('returns correctly encoded Twitter share URL', () => {
+ const result = twitterUrlParams('https://example.com', 'Check this out!');
+ expect(result).toBe(
+ `https://twitter.com/intent/tweet?url=${encodeURIComponent('https://example.com')}&text=${encodeURIComponent('Check this out!')}`,
+ );
+ });
+});
+
+describe('redditUrlParams', () => {
+ test('returns correctly encoded Reddit share URL', () => {
+ const result = redditUrlParams('https://example.com', 'Interesting Title');
+ expect(result).toBe(
+ `https://www.reddit.com/r/nasa/submit?url=${encodeURIComponent('https://example.com')}&title=${encodeURIComponent('Interesting Title')}`,
+ );
+ });
+
+ test('encodes special characters', () => {
+ const result = redditUrlParams('https://ex.com?q=test', 'Title & More');
+ expect(result).toContain(encodeURIComponent('https://ex.com?q=test'));
+ expect(result).toContain(encodeURIComponent('Title & More'));
+ });
+});
+
+describe('emailUrlParams', () => {
+ test('returns correctly encoded mailto URL', () => {
+ const result = emailUrlParams('Hello World', 'Check this link');
+ expect(result).toBe(
+ `mailto:?subject=${encodeURIComponent('Hello World')}&body=${encodeURIComponent('Check this link')}`,
+ );
+ });
+
+ test('encodes special characters', () => {
+ const result = emailUrlParams('Subject & More', 'Body with\nnewline');
+ expect(result).toContain(encodeURIComponent('Subject & More'));
+ expect(result).toContain(encodeURIComponent('Body with\nnewline'));
+ });
+});
+
+describe('encode', () => {
+ jest.mock('lodash', () => ({
+ each: jest.fn((collection, iteratee) => {
+ for (const key in collection) {
+ if (Object.prototype.hasOwnProperty.call(collection, key)) {
+ iteratee(collection[key], key);
+ }
+ }
+ }),
+ }));
+ test('returns encodeURIComponent result when no exceptions apply', () => {
+ expect(encode('hello world')).toBe(encodeURIComponent('hello world'));
+ });
+
+ test('encodes special URI characters', () => {
+ expect(encode('a=b&c=d')).toBe(encodeURIComponent('a=b&c=d'));
+ });
+});
+
+describe('wrapWithIframe', () => {
+ test('wraps value in an iframe tag', () => {
+ const result = wrapWithIframe('https://example.com');
+ expect(result).toBe(
+ '<iframe src="https://example.com" role="application" sandbox="allow-modals allow-scripts allow-same-origin allow-forms allow-popups" width="100%" height="100%" allow="fullscreen; autoplay;" loading="lazy"></iframe>',
+ );
+ });
+
+ test('uses the provided src value', () => {
+ const result = wrapWithIframe('https://other.com/path');
+ expect(result).toContain('src="https://other.com/path"');
+ });
+});
+
+describe('getPermalink', () => {
+ test('adds time param when no querystring and t= not present', () => {
+ const result = getPermalink('', new Date('2024-01-15'), false);
+ expect(result).toContain('?t=');
+ });
+
+ test('appends time param to existing querystring without t=', () => {
+ // setHref(`${BASE_URL}?layers=MODIS`);
+ const result = getPermalink('?layers=MODIS', new Date('2024-01-15'), false);
+ expect(result).toContain('t=');
+ expect(result).toContain('layers=MODIS');
+ });
+
+ test('adds em=true when isEmbed is true', () => {
+ const result = getPermalink('', new Date(), true);
+ expect(result).toContain('em=true');
+ });
+
+ test('changes em=true to em=false when isEmbed is false', () => {
+ const result = getPermalink('?em=true', new Date(), false);
+ expect(result).toContain('em=false');
+ });
+
+ test('removes &kiosk=true from permalink', () => {
+ const result = getPermalink('?layers=MODIS&kiosk=true&t=2024', new Date(), false);
+ expect(result).not.toContain('kiosk=true');
+ });
+
+ test('removes ?kiosk=true (only param) from permalink', () => {
+ const result = getPermalink('?kiosk=true&t=2024', new Date(), false);
+ expect(result).not.toContain('kiosk=true');
+ });
+
+ test('removes &kiosk=true (only param) from permalink', () => {
+ const result = getPermalink('?kiosk=true&t=2024', new Date(), false);
+ expect(result).not.toContain('kiosk=true');
+ });
+
+ test('removes &e2e=true from permalink', () => {
+ const result = getPermalink('?layers=MODIS&e2e=true&t=2024', new Date(), false);
+ expect(result).not.toContain('e2e=true');
+ });
+
+ test('removes ?e2e=true (only param) from permalink', () => {
+ const result = getPermalink('?e2e=true&t=2024', new Date(), false);
+ expect(result).not.toContain('?e2e=true&');
+ });
+
+ test('removes eic= pattern from permalink', () => {
+ const result = getPermalink('?layers=MODIS&eic=AB&t=2024', new Date(), false);
+ expect(result).not.toContain('eic=');
+ });
+
+ test('cleans up trailing & after eic removal', () => {
+ const result = getPermalink('?t=2024&eic=AB', new Date(), false);
+ expect(result).not.toMatch(/&$/);
+ expect(result).not.toContain('eic=');
+ });
+
+ test('cleans up double && after eic removal', () => {
+ const result = getPermalink('?layers=MODIS&eic=AB&t=2024', new Date(), false);
+ expect(result).not.toContain('&&');
+ });
});
diff --git a/web/js/modules/loading/actions.test.js b/web/js/modules/loading/actions.test.js
index 22bc698b0..56dfa36bc 100644
--- a/web/js/modules/loading/actions.test.js
+++ b/web/js/modules/loading/actions.test.js
@@ -1,3 +1,87 @@
-test('actions module test', () => {
+import {
+ LOADING_GRANULES,
+ MAP_LOADING,
+ startLoading,
+ stopLoading,
+} from './actions';
+import { LOADING_START, LOADING_STOP } from './constants';
+jest.mock('./constants', () => ({
+ LOADING_START: 'LOADING_START',
+ LOADING_STOP: 'LOADING_STOP',
+}));
+
+describe('action constants', () => {
+ it('exports LOADING_GRANULES', () => {
+ expect(LOADING_GRANULES).toBe('LOADING/GRANULES');
+ });
+
+ it('exports MAP_LOADING', () => {
+ expect(MAP_LOADING).toBe('LOADING/MAP_LOADING');
+ });
+});
+
+describe('startLoading', () => {
+ it('dispatches LOADING_START when animation is not playing', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ animation: { isPlaying: false } });
+
+ startLoading('testKey', 'testMsg')(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ type: LOADING_START,
+ key: 'testKey',
+ msg: 'testMsg',
+ });
+ });
+
+ it('does not dispatch when animation is playing', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ animation: { isPlaying: true } });
+
+ startLoading('testKey', 'testMsg')(dispatch, getState);
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('calls getState to retrieve animation state', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ animation: { isPlaying: false } });
+
+ startLoading('anyKey', 'anyMsg')(dispatch, getState);
+
+ expect(getState).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('stopLoading', () => {
+ it('dispatches LOADING_STOP when animation is not playing', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ animation: { isPlaying: false } });
+
+ stopLoading('testKey')(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ type: LOADING_STOP,
+ key: 'testKey',
+ });
+ });
+
+ it('does not dispatch when animation is playing', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ animation: { isPlaying: true } });
+
+ stopLoading('testKey')(dispatch, getState);
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('calls getState to retrieve animation state', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ animation: { isPlaying: false } });
+
+ stopLoading('anyKey')(dispatch, getState);
+
+ expect(getState).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/web/js/modules/loading/reducers.test.js b/web/js/modules/loading/reducers.test.js
index 04cce6a78..5c4da52df 100644
--- a/web/js/modules/loading/reducers.test.js
+++ b/web/js/modules/loading/reducers.test.js
@@ -1,3 +1,124 @@
-test('reducers module test', () => {
+import { initialState, loadingReducer } from './reducers';
+jest.mock('./constants', () => ({
+ LOADING_START: 'LOADING_START',
+ LOADING_STOP: 'LOADING_STOP',
+}));
+
+describe('initialState', () => {
+ it('has an empty msg', () => {
+ expect(initialState.msg).toBe('');
+ });
+
+ it('has isLoading set to false', () => {
+ expect(initialState.isLoading).toBe(false);
+ });
+});
+
+describe('loadingReducer', () => {
+ it('returns initial state when no state is provided', () => {
+ const state = loadingReducer(undefined, {});
+ expect(state).toEqual(initialState);
+ });
+
+ it('returns current state for unknown action type', () => {
+ const state = loadingReducer(initialState, { type: 'UNKNOWN' });
+ expect(state).toEqual(initialState);
+ });
+
+ describe('LOADING_START', () => {
+ it('sets isLoading to true', () => {
+ const state = loadingReducer(initialState, {
+ type: 'LOADING_START',
+ key: 'testKey',
+ msg: 'loading...',
+ });
+ expect(state.isLoading).toBe(true);
+ });
+
+ it('sets msg from action', () => {
+ const state = loadingReducer(initialState, {
+ type: 'LOADING_START',
+ key: 'testKey',
+ msg: 'loading...',
+ });
+ expect(state.msg).toBe('loading...');
+ });
+
+ it('sets the key to true in loadingMap', () => {
+ const state = loadingReducer(initialState, {
+ type: 'LOADING_START',
+ key: 'testKey',
+ msg: 'loading...',
+ });
+ expect(state.loadingMap.testKey).toBe(true);
+ });
+
+ it('merges new key into existing loadingMap', () => {
+ const existingState = {
+ ...initialState,
+ loadingMap: { existingKey: true },
+ };
+ const state = loadingReducer(existingState, {
+ type: 'LOADING_START',
+ key: 'newKey',
+ msg: 'loading...',
+ });
+ expect(state.loadingMap).toEqual({ existingKey: true, newKey: true });
+ });
+ });
+
+ describe('LOADING_STOP', () => {
+ it('sets the key to false in loadingMap', () => {
+ const existingState = {
+ ...initialState,
+ isLoading: true,
+ loadingMap: { testKey: true },
+ };
+ const state = loadingReducer(existingState, {
+ type: 'LOADING_STOP',
+ key: 'testKey',
+ });
+ expect(state.loadingMap.testKey).toBe(false);
+ });
+
+ it('sets isLoading to false when no keys remain true', () => {
+ const existingState = {
+ ...initialState,
+ isLoading: true,
+ loadingMap: { testKey: true },
+ };
+ const state = loadingReducer(existingState, {
+ type: 'LOADING_STOP',
+ key: 'testKey',
+ });
+ expect(state.isLoading).toBe(false);
+ });
+
+ it('keeps isLoading true when other keys are still true', () => {
+ const existingState = {
+ ...initialState,
+ isLoading: true,
+ loadingMap: { keyOne: true, keyTwo: true },
+ };
+ const state = loadingReducer(existingState, {
+ type: 'LOADING_STOP',
+ key: 'keyOne',
+ });
+ expect(state.isLoading).toBe(true);
+ });
+
+ it('merges updated key into existing loadingMap', () => {
+ const existingState = {
+ ...initialState,
+ isLoading: true,
+ loadingMap: { keyOne: true, keyTwo: true },
+ };
+ const state = loadingReducer(existingState, {
+ type: 'LOADING_STOP',
+ key: 'keyOne',
+ });
+ expect(state.loadingMap).toEqual({ keyOne: false, keyTwo: true });
+ });
+ });
});