Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Checking in last collection of unit tests for modules/ directory

Jason Hurley6c6fada2a1ef
diff --git a/web/js/modules/combine-reducers.test.js b/web/js/modules/combine-reducers.test.js
index 74c050bd9..d52cdb0d7 100644
--- a/web/js/modules/combine-reducers.test.js
+++ b/web/js/modules/combine-reducers.test.js
@@ -1,3 +1,250 @@
-test('combine-reducers module test', () => {
+import rootReducer, { getInitialState } from './combine-reducers';
+import { LOCATION_POP_ACTION } from '../redux-location-state-customs';
+jest.mock('redux', () => {
+ const actual = jest.requireActual('redux');
+ return { ...actual, combineReducers: jest.fn(actual.combineReducers) };
+});
+
+jest.mock('./modal/reducers', () => ({
+ modalReducer: (s = {}) => s,
+ modalAboutReducer: (s = {}) => s,
+}));
+jest.mock('./feedback/reducers', () => (s = {}) => s);
+jest.mock('./projection/reducer', () => (s = {}) => s);
+jest.mock('./location-search/reducers', () => ({ locationSearchReducer: (s = {}) => s }));
+jest.mock('./link/reducers', () => ({ shortLink: (s = {}) => s }));
+jest.mock('./natural-events/reducers', () => ({
+ getInitialEventsState: jest.fn(() => ({ events: 'initial' })),
+ requestedEvents: (s = {}) => s,
+ requestedEventSources: (s = {}) => s,
+ eventsReducer: (s = {}) => s,
+ eventRequestResponse: jest.fn(() => ({ status: 'idle' })),
+}));
+jest.mock('./tour/reducers', () => (s = {}) => s);
+jest.mock('./map/reducers', () => (s = {}) => s);
+jest.mock('./notifications/reducers', () => ({
+ notificationsRequest: (s = {}) => s,
+ notificationsReducer: (s = {}) => s,
+}));
+jest.mock('./projection/util', () => ({
+ getProjInitialState: jest.fn(() => ({ projection: 'geographic' })),
+}));
+jest.mock('./compare/reducers', () => ({ compareReducer: (s = {}) => s }));
+jest.mock('./charting/reducers', () => ({ chartingReducer: (s = {}) => s }));
+jest.mock('./sidebar/reducers', () => (s = {}) => s);
+jest.mock('./layers/reducers', () => ({
+ layerReducer: (s = {}) => s,
+ getInitialState: jest.fn(() => ({ layers: [] })),
+}));
+jest.mock('./date/reducers', () => ({
+ dateReducer: (s = {}) => s,
+ getInitialState: jest.fn(() => ({ selected: new Date('2021-01-01') })),
+}));
+jest.mock('./animation/reducers', () => ({ animationReducer: (s = {}) => s }));
+jest.mock('./palettes/reducers', () => ({
+ paletteReducer: (s = {}) => s,
+ getInitialPaletteState: jest.fn(() => ({ rendered: {} })),
+}));
+jest.mock('./vector-styles/reducers', () => ({
+ vectorStyleReducer: (s = {}) => s,
+ getInitialVectorStyleState: jest.fn(() => ({ vectorStyles: {} })),
+}));
+jest.mock('./image-download/reducers', () => ({ imageDownloadReducer: (s = {}) => s }));
+jest.mock('./measure/reducers', () => (s = {}) => s);
+jest.mock('./product-picker/reducers', () => ({
+ productPickerReducer: (s = {}) => s,
+ getInitialState: jest.fn(() => ({ productPicker: {} })),
+}));
+jest.mock('./embed/reducers', () => (s = {}) => s);
+jest.mock('./ui/reducers', () => (s = {}) => s);
+jest.mock('./alerts/reducer', () => ({ alertReducer: (s = {}) => s }));
+jest.mock('./smart-handoff/reducer', () => ({
+ smartHandoffReducer: (s = {}) => s,
+ getInitialState: jest.fn(() => ({ smartHandoffs: {} })),
+}));
+jest.mock('./settings/reducer', () => ({
+ settingsReducer: (s = {}) => s,
+ getInitialState: jest.fn(() => ({ settings: {} })),
+}));
+jest.mock('./screen-size/reducer', () => ({
+ screenSizeReducer: (s = {}) => s,
+ getInitialState: jest.fn(() => ({ screenSize: {} })),
+}));
+jest.mock('./loading/reducers', () => ({ loadingReducer: (s = {}) => s }));
+jest.mock('../redux-location-state-customs', () => ({
+ LOCATION_POP_ACTION: '@@router/LOCATION_CHANGE',
+}));
+
+const mockConfig = { projections: {}, defaults: {} };
+const mockModels = { legacy: true };
+const mockParameters = { key: 'value' };
+
+describe('getInitialState', () => {
+ it('returns an object containing parameters, config, and models as provided', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.parameters).toBe(mockParameters);
+ expect(state.config).toBe(mockConfig);
+ expect(state.models).toBe(mockModels);
+ });
+
+ it('includes date initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.date).toBeDefined();
+ expect(state.date.selected).toEqual(new Date('2021-01-01'));
+ });
+
+ it('includes proj initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.proj).toBeDefined();
+ expect(state.proj.projection).toBe('geographic');
+ });
+
+ it('includes layers initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.layers).toBeDefined();
+ expect(Array.isArray(state.layers.layers)).toBe(true);
+ });
+
+ it('includes events initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.events).toBeDefined();
+ expect(state.events.events).toBe('initial');
+ });
+
+ it('includes settings initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.settings).toBeDefined();
+ });
+
+ it('includes screenSize initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.screenSize).toBeDefined();
+ });
+
+ it('includes requestedEvents with idle status', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.requestedEvents).toEqual({ status: 'idle' });
+ });
+
+ it('includes requestedEventSources with idle status', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.requestedEventSources).toEqual({ status: 'idle' });
+ });
+
+ it('includes smartHandoffs initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.smartHandoffs).toBeDefined();
+ });
+
+ it('includes palettes initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.palettes).toBeDefined();
+ expect(state.palettes.rendered).toBeDefined();
+ });
+
+ it('includes productPicker initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.productPicker).toBeDefined();
+ });
+
+ it('includes vectorStyles initial state', () => {
+ const state = getInitialState(mockModels, mockConfig, mockParameters);
+ expect(state.vectorStyles).toBeDefined();
+ });
+
+ it('passes config to each initializer that requires it', () => {
+ const {
+ getInitialState: getLayersInitialState,
+ } = require('./layers/reducers');
+ const {
+ getInitialState: getDateInitialState,
+ } = require('./date/reducers');
+ const { getProjInitialState } = require('./projection/util');
+
+ getInitialState(mockModels, mockConfig, mockParameters);
+
+ expect(getLayersInitialState).toHaveBeenCalledWith(mockConfig);
+ expect(getDateInitialState).toHaveBeenCalledWith(mockConfig);
+ expect(getProjInitialState).toHaveBeenCalledWith(mockConfig);
+ });
+});
+
+describe('rootReducer (default export)', () => {
+ it('returns a state object for an unknown action', () => {
+ const state = rootReducer(undefined, { type: '@@INIT' });
+ expect(state).toBeDefined();
+ expect(typeof state).toBe('object');
+ });
+
+ it('preserves existing state for an unknown action', () => {
+ const initial = rootReducer(undefined, { type: '@@INIT' });
+ const next = rootReducer(initial, { type: 'UNKNOWN_ACTION' });
+ expect(next).toBeDefined();
+ });
+
+ it('resets state to undefined when APP_RESET is dispatched', () => {
+ const initial = rootReducer(undefined, { type: '@@INIT' });
+ expect(initial).toBeDefined();
+ const afterReset = rootReducer(initial, { type: 'APP_RESET' });
+ expect(afterReset).toBeDefined();
+ });
+
+ it('exposes a lastAction slice reflecting the most recent action', () => {
+ const action = { type: 'SOME_ACTION', payload: 42 };
+ const state = rootReducer(undefined, action);
+ expect(state.lastAction).toEqual(action);
+ });
+
+ it('exposes a location slice defaulting to empty key', () => {
+ const state = rootReducer(undefined, { type: '@@INIT' });
+ expect(state.location).toEqual({ key: '' });
+ });
+
+ it('updates location.key when LOCATION_POP_ACTION is dispatched', () => {
+ const initial = rootReducer(undefined, { type: '@@INIT' });
+ const action = {
+ type: LOCATION_POP_ACTION,
+ payload: { key: 'abc123' },
+ };
+ const next = rootReducer(initial, action);
+ expect(next.location.key).toBe('abc123');
+ });
+
+ it('does not mutate location state for other action types', () => {
+ const initial = rootReducer(undefined, { type: '@@INIT' });
+ const next = rootReducer(initial, { type: 'UNRELATED' });
+ expect(next.location).toEqual({ key: '' });
+ });
+
+ it('contains expected top-level keys in produced state', () => {
+ const state = rootReducer(undefined, { type: '@@INIT' });
+ const expectedKeys = [
+ 'alerts', 'animation', 'config', 'compare', 'charting', 'date',
+ 'embed', 'events', 'feedback', 'imageDownload', 'lastAction',
+ 'layers', 'loading', 'location', 'locationSearch', 'map',
+ 'measure', 'modal', 'modalAbout', 'models', 'notifications',
+ 'notificationsRequest', 'palettes', 'parameters', 'productPicker',
+ 'proj', 'requestedEvents', 'requestedEventSources', 'screenSize',
+ 'settings', 'shortLink', 'sidebar', 'smartHandoffs', 'tour',
+ 'ui', 'vectorStyles',
+ ];
+ expectedKeys.forEach((key) => {
+ expect(state).toHaveProperty(key);
+ });
+ });
+
+ it('handles multiple sequential dispatches without throwing', () => {
+ let state = rootReducer(undefined, { type: '@@INIT' });
+ state = rootReducer(state, { type: 'ACTION_ONE' });
+ state = rootReducer(state, { type: 'ACTION_TWO' });
+ state = rootReducer(state, { type: 'APP_RESET' });
+ state = rootReducer(state, { type: 'ACTION_THREE' });
+ expect(state).toBeDefined();
+ });
+
+ it('lastAction slice reflects APP_RESET action itself during that cycle', () => {
+ const state = rootReducer(undefined, { type: 'APP_RESET' });
+ expect(state.lastAction.type).toBe('APP_RESET');
+ });
});
diff --git a/web/js/modules/location-search/actions.test.js b/web/js/modules/location-search/actions.test.js
index f551643ae..3883267ac 100644
--- a/web/js/modules/location-search/actions.test.js
+++ b/web/js/modules/location-search/actions.test.js
@@ -5,18 +5,26 @@ import {
toggleShowLocationSearch,
toggleReverseGeocodeActive,
setSuggestion,
+ setPlaceMarker,
+ removeMarker,
+ setGeocodeResults,
+ toggleDialogVisible,
+ getSuggestions,
} from './actions';
import {
TOGGLE_REVERSE_GEOCODE,
TOGGLE_SHOW_LOCATION_SEARCH,
CLEAR_SUGGESTIONS,
SET_SUGGESTION,
+ SET_REVERSE_GEOCODE_RESULTS,
+ REMOVE_MARKER,
+ TOGGLE_DIALOG_VISIBLE,
+ SET_MARKER,
} from './constants';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
-// test variables
const isExpanded = true;
const suggestion = [{
isCollection: false,
@@ -25,8 +33,7 @@ const suggestion = [{
}];
describe('Location Search actions', () => {
- test(`toggleShowLocationSearch action returns ${TOGGLE_SHOW_LOCATION_SEARCH} as type and ${
- !isExpanded} as value [locationsearch-actions-toggle]`, () => {
+ test(`toggleShowLocationSearch action returns ${TOGGLE_SHOW_LOCATION_SEARCH} as type and ${!isExpanded} as value [locationsearch-actions-toggle]`, () => {
const expectedAction = {
type: TOGGLE_SHOW_LOCATION_SEARCH,
value: false,
@@ -39,14 +46,37 @@ describe('Location Search actions', () => {
store.dispatch(toggleShowLocationSearch());
expect(store.getActions()[0]).toEqual(expectedAction);
});
- test(`toggleReverseGeocodeActive action returns ${TOGGLE_REVERSE_GEOCODE} as type and ${
- true} as value [locationsearch-actions-reverse-geocode]`, () => {
+
+ test(`toggleShowLocationSearch action returns ${TOGGLE_SHOW_LOCATION_SEARCH} as type and ${true} as value when isExpanded is false [locationsearch-actions-toggle-collapsed]`, () => {
+ const expectedAction = {
+ type: TOGGLE_SHOW_LOCATION_SEARCH,
+ value: true,
+ };
+ const store = mockStore({
+ locationSearch: {
+ isExpanded: false,
+ },
+ });
+ store.dispatch(toggleShowLocationSearch());
+ expect(store.getActions()[0]).toEqual(expectedAction);
+ });
+
+ test(`toggleReverseGeocodeActive action returns ${TOGGLE_REVERSE_GEOCODE} as type and ${true} as value [locationsearch-actions-reverse-geocode]`, () => {
const expectedAction = {
type: TOGGLE_REVERSE_GEOCODE,
value: true,
};
expect(toggleReverseGeocodeActive(true)).toEqual(expectedAction);
});
+
+ test(`toggleReverseGeocodeActive action returns ${TOGGLE_REVERSE_GEOCODE} as type and ${false} as value [locationsearch-actions-reverse-geocode-false]`, () => {
+ const expectedAction = {
+ type: TOGGLE_REVERSE_GEOCODE,
+ value: false,
+ };
+ expect(toggleReverseGeocodeActive(false)).toEqual(expectedAction);
+ });
+
test(`setSuggestion action returns ${SET_SUGGESTION} as type and ${suggestion} as value [locationsearch-actions-set-suggestion]`, () => {
const expectedAction = {
type: SET_SUGGESTION,
@@ -60,6 +90,7 @@ describe('Location Search actions', () => {
store.dispatch(setSuggestion(suggestion));
expect(store.getActions()[0]).toEqual(expectedAction);
});
+
test(`clearSuggestions action returns ${CLEAR_SUGGESTIONS} as type and ${[]} as value [locationsearch-actions-clear-suggestions]`, () => {
const expectedAction = {
type: CLEAR_SUGGESTIONS,
@@ -73,4 +104,126 @@ describe('Location Search actions', () => {
store.dispatch(clearSuggestions());
expect(store.getActions()[0]).toEqual(expectedAction);
});
+
+ test(`removeMarker action returns ${REMOVE_MARKER} as type and coordinates as value [locationsearch-actions-remove-marker]`, () => {
+ const coordinates = { id: 123, longitude: -73.7075, latitude: 41.59 };
+ const expectedAction = {
+ type: REMOVE_MARKER,
+ coordinates,
+ };
+ expect(removeMarker(coordinates)).toEqual(expectedAction);
+ });
+
+ test(`setGeocodeResults action returns ${SET_REVERSE_GEOCODE_RESULTS} as type and results as value [locationsearch-actions-set-geocode-results]`, () => {
+ const results = { address: { LongLabel: 'New York, NY, USA' } };
+ const expectedAction = {
+ type: SET_REVERSE_GEOCODE_RESULTS,
+ results,
+ };
+ expect(setGeocodeResults(results)).toEqual(expectedAction);
+ });
+
+ test(`toggleDialogVisible action dispatches ${TOGGLE_DIALOG_VISIBLE} with value true [locationsearch-actions-toggle-dialog-visible-true]`, () => {
+ const expectedAction = {
+ type: TOGGLE_DIALOG_VISIBLE,
+ value: true,
+ };
+ const store = mockStore({});
+ store.dispatch(toggleDialogVisible(true));
+ expect(store.getActions()[0]).toEqual(expectedAction);
+ });
+
+ test(`toggleDialogVisible action dispatches ${TOGGLE_DIALOG_VISIBLE} with value false [locationsearch-actions-toggle-dialog-visible-false]`, () => {
+ const expectedAction = {
+ type: TOGGLE_DIALOG_VISIBLE,
+ value: false,
+ };
+ const store = mockStore({});
+ store.dispatch(toggleDialogVisible(false));
+ expect(store.getActions()[0]).toEqual(expectedAction);
+ });
+
+ test(`setPlaceMarker dispatches ${SET_MARKER} with new coordinates when no existing marker matches [locationsearch-actions-set-marker-new]`, () => {
+ const coord = [-73.7075, 41.59];
+ const reverseGeocodeResults = {
+ address: { LongLabel: 'Some Place, NY, USA' },
+ };
+ const store = mockStore({
+ locationSearch: {
+ coordinates: [],
+ },
+ });
+ store.dispatch(setPlaceMarker(coord, reverseGeocodeResults, false));
+ const action = store.getActions()[0];
+ expect(action.type).toEqual(SET_MARKER);
+ expect(action.coordinates.longitude).toEqual(-73.7075);
+ expect(action.coordinates.latitude).toEqual(41.59);
+ expect(action.reverseGeocodeResults).toEqual(reverseGeocodeResults);
+ expect(action.isCoordinatesSearchActive).toEqual(false);
+ expect(action.flyToExistingMarker).toBeUndefined();
+ });
+
+ test(`setPlaceMarker dispatches ${SET_MARKER} with flyToExistingMarker true when marker already exists [locationsearch-actions-set-marker-existing]`, () => {
+ const existingCoord = { id: 999, longitude: -73.7075, latitude: 41.59 };
+ const coord = [-73.7075, 41.59];
+ const reverseGeocodeResults = {
+ address: { LongLabel: 'Some Place, NY, USA' },
+ };
+ const store = mockStore({
+ locationSearch: {
+ coordinates: [existingCoord],
+ },
+ });
+ store.dispatch(setPlaceMarker(coord, reverseGeocodeResults, true));
+ const action = store.getActions()[0];
+ expect(action.type).toEqual(SET_MARKER);
+ expect(action.coordinates).toEqual(existingCoord);
+ expect(action.flyToExistingMarker).toEqual(true);
+ expect(action.isCoordinatesSearchActive).toEqual(true);
+ });
+
+ test('setPlaceMarker logs a warning when reverseGeocodeResults contains an error [locationsearch-actions-set-marker-geocode-error]', () => {
+ const coord = [-73.7075, 41.59];
+ const reverseGeocodeResults = {
+ error: { message: 'Geocode failed', details: 'No results found' },
+ };
+ const store = mockStore({
+ locationSearch: {
+ coordinates: [],
+ },
+ });
+ const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ store.dispatch(setPlaceMarker(coord, reverseGeocodeResults, false));
+ expect(warnSpy).toHaveBeenCalledWith(
+ 'REVERSE GEOCODING WARNING - Geocode failed No results found',
+ );
+ warnSpy.mockRestore();
+ });
+
+ test('setPlaceMarker handles null reverseGeocodeResults without error [locationsearch-actions-set-marker-null-geocode]', () => {
+ const coord = [-73.7075, 41.59];
+ const store = mockStore({
+ locationSearch: {
+ coordinates: [],
+ },
+ });
+ store.dispatch(setPlaceMarker(coord, null, false));
+ const action = store.getActions()[0];
+ expect(action.type).toEqual(SET_MARKER);
+ expect(action.reverseGeocodeResults).toBeNull();
+ });
+
+ test('getSuggestions dispatches requestAction with encoded value [locationsearch-actions-get-suggestions]', () => {
+ const store = mockStore({
+ config: {
+ features: {
+ locationSearch: {
+ url: 'https://example.com/arcgis/',
+ },
+ },
+ },
+ });
+ store.dispatch(getSuggestions('New York'));
+ expect(store.getActions().length).toBeGreaterThanOrEqual(0);
+ });
});
diff --git a/web/js/modules/location-search/reducers.test.js b/web/js/modules/location-search/reducers.test.js
index 55d29a3d6..9b5ccbdec 100644
--- a/web/js/modules/location-search/reducers.test.js
+++ b/web/js/modules/location-search/reducers.test.js
@@ -4,13 +4,16 @@ import {
} from './reducers';
import {
CLEAR_SUGGESTIONS,
+ REMOVE_MARKER,
+ REQUEST_SUGGEST_PLACE_FAILURE,
+ REQUEST_SUGGEST_PLACE_SUCCESS,
SET_MARKER,
+ SET_REVERSE_GEOCODE_RESULTS,
SET_SUGGESTION,
TOGGLE_REVERSE_GEOCODE,
TOGGLE_SHOW_LOCATION_SEARCH,
} from './constants';
-// test variables
const reverseGeocodeResults = {
address: {},
location: {},
@@ -21,6 +24,7 @@ const suggestion = [{
text: 'New York, NY, USA',
}];
const coordinatesObject = { id: 1234, latitude: 72, longitude: 40 };
+const coordinatesObject2 = { id: 5678, latitude: 34, longitude: -118 };
describe('locationSearch', () => {
test('locationSearch should return the initial state [locationstate-reducer-initial-state]', () => {
@@ -28,9 +32,9 @@ describe('locationSearch', () => {
locationSearchState,
);
});
+
test(
- `${TOGGLE_SHOW_LOCATION_SEARCH
- } shows Location Search isExpanded and ` +
+ `${TOGGLE_SHOW_LOCATION_SEARCH} shows Location Search isExpanded and ` +
'should return new state [locationsearch-reducer-toggle]',
() => {
expect(
@@ -44,9 +48,25 @@ describe('locationSearch', () => {
});
},
);
+
test(
- `${TOGGLE_REVERSE_GEOCODE
- } toggles isCoordinateSearchActive to true and ` +
+ `${TOGGLE_SHOW_LOCATION_SEARCH} sets isExpanded to false and ` +
+ 'should return new state [locationsearch-reducer-toggle-false]',
+ () => {
+ expect(
+ locationSearchReducer(locationSearchState, {
+ type: TOGGLE_SHOW_LOCATION_SEARCH,
+ value: false,
+ }),
+ ).toEqual({
+ ...locationSearchState,
+ isExpanded: false,
+ });
+ },
+ );
+
+ test(
+ `${TOGGLE_REVERSE_GEOCODE} toggles isCoordinateSearchActive to true and ` +
'should return new state [locationsearch-reducer-reverse-geocode]',
() => {
expect(
@@ -60,10 +80,58 @@ describe('locationSearch', () => {
});
},
);
+
+ test(
+ `${TOGGLE_REVERSE_GEOCODE} toggles isCoordinateSearchActive to false and ` +
+ 'should return new state [locationsearch-reducer-reverse-geocode-false]',
+ () => {
+ expect(
+ locationSearchReducer(locationSearchState, {
+ type: TOGGLE_REVERSE_GEOCODE,
+ value: false,
+ }),
+ ).toEqual({
+ ...locationSearchState,
+ isCoordinateSearchActive: false,
+ });
+ },
+ );
+
+ test(
+ `${SET_REVERSE_GEOCODE_RESULTS} updates reverseGeocodeResults and ` +
+ 'should return new state [locationsearch-reducer-set-reverse-geocode-results]',
+ () => {
+ expect(
+ locationSearchReducer(locationSearchState, {
+ type: SET_REVERSE_GEOCODE_RESULTS,
+ value: reverseGeocodeResults,
+ }),
+ ).toEqual({
+ ...locationSearchState,
+ reverseGeocodeResults,
+ });
+ },
+ );
+
+ test(
+ `${SET_REVERSE_GEOCODE_RESULTS} sets reverseGeocodeResults to null and ` +
+ 'should return new state [locationsearch-reducer-set-reverse-geocode-results-null]',
+ () => {
+ expect(
+ locationSearchReducer(locationSearchState, {
+ type: SET_REVERSE_GEOCODE_RESULTS,
+ value: null,
+ }),
+ ).toEqual({
+ ...locationSearchState,
+ reverseGeocodeResults: null,
+ });
+ },
+ );
+
test(
- `${SET_MARKER
- } updates coordinates, reverseGeocodeResults ` +
- 'and sets isCoordinateSearchActive to false and should return new state [locationsearch-reducer-set-marker]',
+ `${SET_MARKER} updates coordinates, reverseGeocodeResults ` +
+ 'and sets isCoordinateSearchActive to false and should return new state [locationsearch-reducer-set-marker]',
() => {
expect(
locationSearchReducer(locationSearchState, {
@@ -79,9 +147,72 @@ describe('locationSearch', () => {
});
},
);
+
+ test(
+ `${SET_MARKER} appends to existing coordinates array and ` +
+ 'should return new state [locationsearch-reducer-set-marker-append]',
+ () => {
+ const stateWithExistingCoord = {
+ ...locationSearchState,
+ coordinates: [coordinatesObject],
+ };
+ expect(
+ locationSearchReducer(stateWithExistingCoord, {
+ type: SET_MARKER,
+ coordinates: coordinatesObject2,
+ reverseGeocodeResults,
+ }),
+ ).toEqual({
+ ...stateWithExistingCoord,
+ isCoordinateSearchActive: false,
+ coordinates: [coordinatesObject, coordinatesObject2],
+ reverseGeocodeResults,
+ });
+ },
+ );
+
+ test(
+ `${REMOVE_MARKER} removes matching coordinate by id and ` +
+ 'should return new state [locationsearch-reducer-remove-marker]',
+ () => {
+ const stateWithCoords = {
+ ...locationSearchState,
+ coordinates: [coordinatesObject, coordinatesObject2],
+ };
+ expect(
+ locationSearchReducer(stateWithCoords, {
+ type: REMOVE_MARKER,
+ coordinates: { id: coordinatesObject.id },
+ }),
+ ).toEqual({
+ ...stateWithCoords,
+ coordinates: [coordinatesObject2],
+ });
+ },
+ );
+
test(
- `${SET_SUGGESTION
- } updates suggestions with value and ` +
+ `${REMOVE_MARKER} returns unchanged coordinates when id does not match and ` +
+ 'should return new state [locationsearch-reducer-remove-marker-no-match]',
+ () => {
+ const stateWithCoords = {
+ ...locationSearchState,
+ coordinates: [coordinatesObject],
+ };
+ expect(
+ locationSearchReducer(stateWithCoords, {
+ type: REMOVE_MARKER,
+ coordinates: { id: 9999 },
+ }),
+ ).toEqual({
+ ...stateWithCoords,
+ coordinates: [coordinatesObject],
+ });
+ },
+ );
+
+ test(
+ `${SET_SUGGESTION} updates suggestions with value and ` +
'should return new state [locationsearch-reducer-set-suggestion]',
() => {
expect(
@@ -95,9 +226,49 @@ describe('locationSearch', () => {
});
},
);
+
+ test(
+ `${REQUEST_SUGGEST_PLACE_SUCCESS} updates suggestions from parsed response and ` +
+ 'should return new state [locationsearch-reducer-request-suggest-place-success]',
+ () => {
+ const suggestions = [
+ { text: 'New York, NY, USA', magicKey: 'abc123', isCollection: false },
+ { text: 'New Orleans, LA, USA', magicKey: 'def456', isCollection: false },
+ ];
+ const response = JSON.stringify({ suggestions });
+ expect(
+ locationSearchReducer(locationSearchState, {
+ type: REQUEST_SUGGEST_PLACE_SUCCESS,
+ response,
+ }),
+ ).toEqual({
+ ...locationSearchState,
+ suggestions,
+ });
+ },
+ );
+
+ test(
+ `${REQUEST_SUGGEST_PLACE_FAILURE} resets suggestions to empty array and ` +
+ 'should return new state [locationsearch-reducer-request-suggest-place-failure]',
+ () => {
+ const stateWithSuggestions = {
+ ...locationSearchState,
+ suggestions: [{ text: 'Some Place', magicKey: 'xyz', isCollection: false }],
+ };
+ expect(
+ locationSearchReducer(stateWithSuggestions, {
+ type: REQUEST_SUGGEST_PLACE_FAILURE,
+ }),
+ ).toEqual({
+ ...stateWithSuggestions,
+ suggestions: [],
+ });
+ },
+ );
+
test(
- `${CLEAR_SUGGESTIONS
- } updates suggestions and suggestedPlace with clear value and ` +
+ `${CLEAR_SUGGESTIONS} updates suggestions and suggestedPlace with clear value and ` +
'should return new state [locationsearch-reducer-clear-suggestion]',
() => {
expect(
@@ -112,4 +283,18 @@ describe('locationSearch', () => {
});
},
);
+
+ test(
+ 'unknown action type should return current state [locationsearch-reducer-default]',
+ () => {
+ const currentState = {
+ ...locationSearchState,
+ suggestions: suggestion,
+ coordinates: [coordinatesObject],
+ };
+ expect(
+ locationSearchReducer(currentState, { type: 'UNKNOWN_ACTION' }),
+ ).toEqual(currentState);
+ },
+ );
});
diff --git a/web/js/modules/location-search/util-api.test.js b/web/js/modules/location-search/util-api.test.js
index 57e07571b..3591f888f 100644
--- a/web/js/modules/location-search/util-api.test.js
+++ b/web/js/modules/location-search/util-api.test.js
@@ -1,3 +1,141 @@
-test('util-api module test', () => {
+import {
+ LOCATION_SEARCH_REQUEST_OPTIONS,
+ processMagicKey,
+ reverseGeocode,
+} from './util-api';
+const { REQUEST_OPTIONS, GEOCODE_SUGGEST_CATEGORIES, CONSTANT_REQUEST_PARAMETERS } =
+ LOCATION_SEARCH_REQUEST_OPTIONS;
+
+const config = {
+ features: {
+ locationSearch: {
+ url: 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/',
+ },
+ },
+};
+
+const mockParsedResponse = {
+ candidates: [
+ {
+ address: 'New York, New York',
+ location: { x: -74.006, y: 40.7128 },
+ },
+ ],
+};
+
+beforeEach(() => {
+ global.fetch = jest.fn(() =>
+ Promise.resolve({
+ text: () => Promise.resolve(JSON.stringify(mockParsedResponse)),
+ }),
+ );
+});
+
+afterEach(() => {
+ jest.resetAllMocks();
+});
+
+describe('LOCATION_SEARCH_REQUEST_OPTIONS', () => {
+ test('REQUEST_OPTIONS has method GET and redirect follow [util-api-request-options]', () => {
+ expect(REQUEST_OPTIONS).toEqual({
+ method: 'GET',
+ redirect: 'follow',
+ });
+ });
+
+ test('CONSTANT_REQUEST_PARAMETERS equals f=json&langCode=en [util-api-constant-request-params]', () => {
+ expect(CONSTANT_REQUEST_PARAMETERS).toEqual('f=json&langCode=en');
+ });
+
+ test('GEOCODE_SUGGEST_CATEGORIES is an array [util-api-categories-is-array]', () => {
+ expect(Array.isArray(GEOCODE_SUGGEST_CATEGORIES)).toBe(true);
+ });
+
+ test('GEOCODE_SUGGEST_CATEGORIES contains expected categories [util-api-categories-content]', () => {
+ expect(GEOCODE_SUGGEST_CATEGORIES).toEqual([
+ 'Address',
+ 'Street Address',
+ 'Populated Place',
+ 'Education',
+ 'Land Features',
+ 'Water Features',
+ 'Museum',
+ 'Tourist Attraction',
+ 'Scientific Research',
+ 'Government Office',
+ 'Business Facility',
+ 'Primary Postal',
+ 'Airport',
+ ]);
+ });
+
+ test('GEOCODE_SUGGEST_CATEGORIES has 13 entries [util-api-categories-length]', () => {
+ expect(GEOCODE_SUGGEST_CATEGORIES).toHaveLength(13);
+ });
+});
+
+describe('processMagicKey', () => {
+ test('processMagicKey calls fetch with the correct URL [util-api-process-magic-key-url]', async () => {
+ const magicKey = 'test1234';
+ await processMagicKey(magicKey, config);
+ expect(global.fetch).toHaveBeenCalledWith(
+ `https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?${CONSTANT_REQUEST_PARAMETERS}&outFields=*&magicKey=${magicKey}=`,
+ REQUEST_OPTIONS,
+ );
+ });
+
+ test('processMagicKey returns parsed JSON response [util-api-process-magic-key-response]', async () => {
+ const result = await processMagicKey('test1234', config);
+ expect(result).toEqual(mockParsedResponse);
+ });
+
+ test('processMagicKey calls fetch once [util-api-process-magic-key-fetch-once]', async () => {
+ await processMagicKey('test1234', config);
+ expect(global.fetch).toHaveBeenCalledTimes(1);
+ });
+
+ test('processMagicKey handles fetch error gracefully [util-api-process-magic-key-error]', async () => {
+ global.fetch = jest.fn(() => Promise.reject(new Error('Network error')));
+ const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
+ await processMagicKey('test1234', config);
+ expect(consoleSpy).toHaveBeenCalledWith('error', expect.any(Error));
+ consoleSpy.mockRestore();
+ });
+});
+
+describe('reverseGeocode', () => {
+ test('reverseGeocode calls fetch with the correct URL [util-api-reverse-geocode-url]', async () => {
+ const coordinates = [-74.006, 40.7128];
+ await reverseGeocode(coordinates, config);
+ expect(global.fetch).toHaveBeenCalledWith(
+ `https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?${CONSTANT_REQUEST_PARAMETERS}&location=${coordinates}`,
+ REQUEST_OPTIONS,
+ );
+ });
+
+ test('reverseGeocode returns parsed JSON response [util-api-reverse-geocode-response]', async () => {
+ const result = await reverseGeocode([-74.006, 40.7128], config);
+ expect(result).toEqual(mockParsedResponse);
+ });
+
+ test('reverseGeocode calls fetch once [util-api-reverse-geocode-fetch-once]', async () => {
+ await reverseGeocode([-74.006, 40.7128], config);
+ expect(global.fetch).toHaveBeenCalledTimes(1);
+ });
+
+ test('reverseGeocode handles fetch error gracefully [util-api-reverse-geocode-error]', async () => {
+ global.fetch = jest.fn(() => Promise.reject(new Error('Network error')));
+ const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
+ await reverseGeocode([-74.006, 40.7128], config);
+ expect(consoleSpy).toHaveBeenCalledWith('error', expect.any(Error));
+ consoleSpy.mockRestore();
+ });
+
+ test('reverseGeocode passes coordinate array as string in request URL [util-api-reverse-geocode-coordinates-string]', async () => {
+ const coordinates = [-73.7075, 41.59];
+ await reverseGeocode(coordinates, config);
+ const calledUrl = global.fetch.mock.calls[0][0];
+ expect(calledUrl).toContain(`location=${coordinates}`);
+ });
});
diff --git a/web/js/modules/location-search/util.test.js b/web/js/modules/location-search/util.test.js
index 4072f4f95..bbb3ae89a 100644
--- a/web/js/modules/location-search/util.test.js
+++ b/web/js/modules/location-search/util.test.js
@@ -1,3 +1,338 @@
-test('util module test', () => {
+import {
+ animateCoordinates,
+ areCoordinatesWithinExtent,
+ getCoordinatesMarker,
+ getLocalStorageCollapseState,
+ isLocationSearchFeatureEnabled,
+ mapLocationToLocationSearchState,
+ serializeCoordinatesWrapper,
+ setLocalStorageCollapseState,
+} from './util';
+jest.mock('../../util/local-storage', () => ({
+ keys: { LOCATION_SEARCH_COLLAPSED: 'locationSearchCollapsed' },
+ getItem: jest.fn(),
+ setItem: jest.fn(),
+}));
+
+jest.mock('../../map/util', () => ({
+ fly: jest.fn(),
+}));
+
+jest.mock('ol/proj', () => ({
+ transform: jest.fn((coords) => coords),
+}));
+
+jest.mock('ol/extent', () => ({
+ containsCoordinate: jest.fn(),
+}));
+
+jest.mock('ol/Overlay', () => jest.fn().mockImplementation((opts) => ({ ...opts })));
+
+jest.mock('react-dom/client', () => ({
+ createRoot: jest.fn(() => ({
+ render: jest.fn(),
+ unmount: jest.fn(),
+ })),
+}));
+
+jest.mock('../../components/location-search/location-marker', () => 'LocationMarker');
+
+jest.mock('../map/constants', () => ({
+ CRS: { GEOGRAPHIC: 'EPSG:4326' },
+ FULL_MAP_EXTENT: [-180, -90, 180, 90],
+}));
+
+import safeLocalStorage from '../../util/local-storage';
+import { fly } from '../../map/util';
+import { transform } from 'ol/proj';
+import { containsCoordinate } from 'ol/extent';
+import { CRS, FULL_MAP_EXTENT } from '../map/constants';
+
+afterEach(() => {
+ jest.clearAllMocks();
+ transform.mockImplementation((coords) => coords);
+});
+
+describe('getLocalStorageCollapseState', () => {
+ test('returns true when localStorage value is collapsed [util-get-local-storage-collapse-state-true]', () => {
+ safeLocalStorage.getItem.mockReturnValue('collapsed');
+ expect(getLocalStorageCollapseState()).toBe(true);
+ });
+
+ test('returns false when localStorage value is expanded [util-get-local-storage-collapse-state-false]', () => {
+ safeLocalStorage.getItem.mockReturnValue('expanded');
+ expect(getLocalStorageCollapseState()).toBe(false);
+ });
+
+ test('returns false when localStorage value is null [util-get-local-storage-collapse-state-null]', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ expect(getLocalStorageCollapseState()).toBe(false);
+ });
+});
+
+describe('setLocalStorageCollapseState', () => {
+ test('calls safeLocalStorage.setItem with collapsed [util-set-local-storage-collapse-state-collapsed]', () => {
+ setLocalStorageCollapseState('collapsed');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('locationSearchCollapsed', 'collapsed');
+ });
+
+ test('calls safeLocalStorage.setItem with expanded [util-set-local-storage-collapse-state-expanded]', () => {
+ setLocalStorageCollapseState('expanded');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith('locationSearchCollapsed', 'expanded');
+ });
+});
+
+describe('isLocationSearchFeatureEnabled', () => {
+ test('returns true when locationSearch feature and url are present [util-is-location-search-enabled-true]', () => {
+ const config = { features: { locationSearch: { url: 'https://example.com/' } } };
+ expect(isLocationSearchFeatureEnabled(config)).toBe(true);
+ });
+
+ test('returns false when locationSearch feature is missing [util-is-location-search-enabled-no-feature]', () => {
+ const config = { features: {} };
+ expect(isLocationSearchFeatureEnabled(config)).toBe(false);
+ });
+
+ test('returns false when locationSearch url is missing [util-is-location-search-enabled-no-url]', () => {
+ const config = { features: { locationSearch: {} } };
+ expect(isLocationSearchFeatureEnabled(config)).toBe(false);
+ });
+
+ test('returns false when locationSearch url is empty string [util-is-location-search-enabled-empty-url]', () => {
+ const config = { features: { locationSearch: { url: '' } } };
+ expect(isLocationSearchFeatureEnabled(config)).toBe(false);
+ });
+});
+
+describe('animateCoordinates', () => {
+ const map = {};
+ const zoom = 5;
+
+ test('calls fly with untransformed coordinates when proj is geographic [util-animate-coordinates-geographic]', () => {
+ const proj = { selected: { crs: CRS.GEOGRAPHIC } };
+ animateCoordinates(map, proj, [-74, 40], zoom, false);
+ expect(fly).toHaveBeenCalledWith(map, proj, [-74, 40], false, zoom);
+ });
+
+ test('calls transform and fly when proj is not geographic [util-animate-coordinates-non-geographic]', () => {
+ const proj = { selected: { crs: 'EPSG:3413' } };
+ transform.mockReturnValue([-300000, 500000]);
+ animateCoordinates(map, proj, [-74, 40], zoom, false);
+ expect(transform).toHaveBeenCalledWith([-74, 40], CRS.GEOGRAPHIC, 'EPSG:3413');
+ expect(fly).toHaveBeenCalledWith(map, proj, [-300000, 500000], false, zoom);
+ });
+
+ test('passes isKioskModeActive true to fly [util-animate-coordinates-kiosk-mode]', () => {
+ const proj = { selected: { crs: CRS.GEOGRAPHIC } };
+ animateCoordinates(map, proj, [10, 20], zoom, true);
+ expect(fly).toHaveBeenCalledWith(map, proj, [10, 20], true, zoom);
+ });
+});
+
+describe('areCoordinatesWithinExtent', () => {
+ test('uses FULL_MAP_EXTENT and raw coordinates for geographic CRS [util-are-coordinates-within-extent-geographic]', () => {
+ const proj = { selected: { crs: CRS.GEOGRAPHIC, maxExtent: [-180, -90, 180, 90] } };
+ containsCoordinate.mockReturnValue(true);
+ const result = areCoordinatesWithinExtent(proj, [-74, 40]);
+ expect(containsCoordinate).toHaveBeenCalledWith(FULL_MAP_EXTENT, [-74, 40]);
+ expect(result).toBe(true);
+ });
+
+ test('uses maxExtent and transforms coordinates for non-geographic CRS [util-are-coordinates-within-extent-non-geographic]', () => {
+ const maxExtent = [-4000000, -4000000, 4000000, 4000000];
+ const proj = { selected: { crs: 'EPSG:3413', maxExtent } };
+ transform.mockReturnValue([-300000, 500000]);
+ containsCoordinate.mockReturnValue(false);
+ const result = areCoordinatesWithinExtent(proj, [-74, 40]);
+ expect(transform).toHaveBeenCalledWith([-74, 40], CRS.GEOGRAPHIC, 'EPSG:3413');
+ expect(containsCoordinate).toHaveBeenCalledWith(maxExtent, [-300000, 500000]);
+ expect(result).toBe(false);
+ });
+
+ test('returns false when coordinate is outside extent [util-are-coordinates-within-extent-false]', () => {
+ const proj = { selected: { crs: CRS.GEOGRAPHIC, maxExtent: [-180, -90, 180, 90] } };
+ containsCoordinate.mockReturnValue(false);
+ expect(areCoordinatesWithinExtent(proj, [200, 100])).toBe(false);
+ });
+});
+
+describe('serializeCoordinatesWrapper', () => {
+ const geographicProj = {
+ selected: { crs: CRS.GEOGRAPHIC, maxExtent: [-180, -90, 180, 90] },
+ };
+
+ const stateWithMap = (selected = true) => ({
+ map: { ui: { selected } },
+ proj: geographicProj,
+ });
+
+ test('returns joined coordinate string for valid single coordinate in array [util-serialize-coordinates-wrapper-single]', () => {
+ containsCoordinate.mockReturnValue(true);
+ const result = serializeCoordinatesWrapper(
+ [{ longitude: -74, latitude: 40 }],
+ stateWithMap(),
+ );
+ expect(result).toBe('-74,40');
+ });
+
+ test('returns undefined when map.ui.selected is falsy [util-serialize-coordinates-wrapper-no-map]', () => {
+ const result = serializeCoordinatesWrapper(
+ [{ longitude: -74, latitude: 40 }],
+ stateWithMap(false),
+ );
+ expect(result).toBeUndefined();
+ });
+
+ test('returns undefined when coordinate is outside extent [util-serialize-coordinates-wrapper-outside-extent]', () => {
+ containsCoordinate.mockReturnValue(false);
+ const result = serializeCoordinatesWrapper(
+ [{ longitude: -74, latitude: 40 }],
+ stateWithMap(),
+ );
+ expect(result).toBeUndefined();
+ });
+
+ test('returns joined string for valid array of coordinates [util-serialize-coordinates-wrapper-array]', () => {
+ containsCoordinate.mockReturnValue(true);
+ const result = serializeCoordinatesWrapper(
+ [{ longitude: -74, latitude: 40 }, { longitude: -118, latitude: 34 }],
+ stateWithMap(),
+ );
+ expect(result).toBe('-74,40+-118,34');
+ });
+
+ test('filters out invalid coordinates from array [util-serialize-coordinates-wrapper-array-filter]', () => {
+ containsCoordinate
+ .mockReturnValueOnce(true)
+ .mockReturnValueOnce(false);
+ const result = serializeCoordinatesWrapper(
+ [{ longitude: -74, latitude: 40 }, { longitude: 200, latitude: 100 }],
+ stateWithMap(),
+ );
+ expect(result).toBe('-74,40');
+ });
+
+ test('returns undefined for empty array of coordinates [util-serialize-coordinates-wrapper-empty-array]', () => {
+ const result = serializeCoordinatesWrapper([], stateWithMap());
+ expect(result).toBeUndefined();
+ });
+});
+
+describe('mapLocationToLocationSearchState', () => {
+ const baseState = {
+ screenSize: { isMobileDevice: false },
+ };
+ const baseStoreFromLocation = {
+ locationSearch: { coordinates: [], isExpanded: true },
+ };
+
+ beforeEach(() => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ });
+
+ test('parses single coordinate from s parameter [util-map-location-to-state-single]', () => {
+ const result = mapLocationToLocationSearchState(
+ { s: '-74,40' },
+ baseStoreFromLocation,
+ baseState,
+ );
+ expect(result.locationSearch.coordinates).toHaveLength(1);
+ expect(result.locationSearch.coordinates[0].longitude).toBe(-74);
+ expect(result.locationSearch.coordinates[0].latitude).toBe(40);
+ });
+
+ test('parses multiple coordinates from s parameter separated by + [util-map-location-to-state-multiple]', () => {
+ const result = mapLocationToLocationSearchState(
+ { s: '-74,40+-118,34' },
+ baseStoreFromLocation,
+ baseState,
+ );
+ expect(result.locationSearch.coordinates).toHaveLength(2);
+ expect(result.locationSearch.coordinates[0].longitude).toBe(-74);
+ expect(result.locationSearch.coordinates[1].longitude).toBe(-118);
+ });
+
+ test('returns empty coordinates array when s parameter is absent [util-map-location-to-state-no-s]', () => {
+ const result = mapLocationToLocationSearchState(
+ {},
+ baseStoreFromLocation,
+ baseState,
+ );
+ expect(result.locationSearch.coordinates).toEqual([]);
+ });
+
+ test('sets isExpanded to true when not mobile and not collapsed in localStorage [util-map-location-to-state-expanded]', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const result = mapLocationToLocationSearchState(
+ { s: '-74,40' },
+ baseStoreFromLocation,
+ { screenSize: { isMobileDevice: false } },
+ );
+ expect(result.locationSearch.isExpanded).toBe(true);
+ });
+
+ test('sets isExpanded to false when isMobileDevice is true [util-map-location-to-state-mobile]', () => {
+ const result = mapLocationToLocationSearchState(
+ { s: '-74,40' },
+ baseStoreFromLocation,
+ { screenSize: { isMobileDevice: true } },
+ );
+ expect(result.locationSearch.isExpanded).toBe(false);
+ });
+
+ test('sets isExpanded to false when localStorage is collapsed [util-map-location-to-state-collapsed]', () => {
+ safeLocalStorage.getItem.mockReturnValue('collapsed');
+ const result = mapLocationToLocationSearchState(
+ { s: '-74,40' },
+ baseStoreFromLocation,
+ { screenSize: { isMobileDevice: false } },
+ );
+ expect(result.locationSearch.isExpanded).toBe(false);
+ });
+
+ test('each parsed coordinate has an id property [util-map-location-to-state-coordinate-id]', () => {
+ const result = mapLocationToLocationSearchState(
+ { s: '-74,40' },
+ baseStoreFromLocation,
+ baseState,
+ );
+ expect(result.locationSearch.coordinates[0]).toHaveProperty('id');
+ });
+});
+
+describe('getCoordinatesMarker', () => {
+ const coordinatesObject = { id: 1234, longitude: -74, latitude: 40 };
+ const results = { address: { LongLabel: 'New York, NY' } };
+ const removeMarker = jest.fn();
+
+ test('returns a marker object for geographic projection [util-get-coordinates-marker-geographic]', () => {
+ const proj = { selected: { crs: CRS.GEOGRAPHIC } };
+ const marker = getCoordinatesMarker(
+ proj, coordinatesObject, results, removeMarker, false, false,
+ );
+ expect(marker).toBeDefined();
+ });
+
+ test('calls transform for non-geographic projection [util-get-coordinates-marker-non-geographic]', () => {
+ const proj = { selected: { crs: 'EPSG:3413' } };
+ transform.mockReturnValue([-300000, 500000]);
+ getCoordinatesMarker(proj, coordinatesObject, results, removeMarker, false, false);
+ expect(transform).toHaveBeenCalledWith([-74, 40], CRS.GEOGRAPHIC, 'EPSG:3413');
+ });
+
+ test('returns marker with correct id [util-get-coordinates-marker-id]', () => {
+ const proj = { selected: { crs: CRS.GEOGRAPHIC } };
+ const marker = getCoordinatesMarker(
+ proj, coordinatesObject, results, removeMarker, false, false,
+ );
+ expect(marker.id).toBe(coordinatesObject.id);
+ });
+
+ test('passes isMobile and dialogVisible to pin props [util-get-coordinates-marker-props]', () => {
+ const { createRoot } = require('react-dom/client');
+ const proj = { selected: { crs: CRS.GEOGRAPHIC } };
+ getCoordinatesMarker(proj, coordinatesObject, results, removeMarker, true, true);
+ expect(createRoot).toHaveBeenCalled();
+ });
});
diff --git a/web/js/modules/map/actions.test.js b/web/js/modules/map/actions.test.js
index 22bc698b0..d9f8f9410 100644
--- a/web/js/modules/map/actions.test.js
+++ b/web/js/modules/map/actions.test.js
@@ -1,3 +1,139 @@
-test('actions module test', () => {
+import {
+ clearRotate,
+ refreshRotation,
+ changeCursor,
+ updateMapExtent,
+ updateRenderedState,
+ updateMapUI,
+ fitToLeadingExtent,
+} from './actions';
+import {
+ CLEAR_ROTATE,
+ CHANGE_CURSOR,
+ REFRESH_ROTATE,
+ UPDATE_MAP_EXTENT,
+ RENDERED,
+ UPDATE_MAP_UI,
+ FITTED_TO_LEADING_EXTENT,
+} from './constants';
+describe('clearRotate', () => {
+ test(`returns action with type ${CLEAR_ROTATE} [map-actions-clear-rotate]`, () => {
+ expect(clearRotate()).toEqual({ type: CLEAR_ROTATE });
+ });
+
+ test('returns no extra properties [map-actions-clear-rotate-no-extra-props]', () => {
+ const action = clearRotate();
+ expect(Object.keys(action)).toEqual(['type']);
+ });
+});
+
+describe('refreshRotation', () => {
+ test(`returns action with type ${REFRESH_ROTATE} and rotation value [map-actions-refresh-rotation]`, () => {
+ expect(refreshRotation(45)).toEqual({ type: REFRESH_ROTATE, rotation: 45 });
+ });
+
+ test('returns rotation of 0 [map-actions-refresh-rotation-zero]', () => {
+ expect(refreshRotation(0)).toEqual({ type: REFRESH_ROTATE, rotation: 0 });
+ });
+
+ test('returns negative rotation value [map-actions-refresh-rotation-negative]', () => {
+ expect(refreshRotation(-90)).toEqual({ type: REFRESH_ROTATE, rotation: -90 });
+ });
+
+ test('returns decimal rotation value [map-actions-refresh-rotation-decimal]', () => {
+ expect(refreshRotation(22.5)).toEqual({ type: REFRESH_ROTATE, rotation: 22.5 });
+ });
+
+ test('returns rotation of 360 [map-actions-refresh-rotation-full]', () => {
+ expect(refreshRotation(360)).toEqual({ type: REFRESH_ROTATE, rotation: 360 });
+ });
+});
+
+describe('changeCursor', () => {
+ test(`returns action with type ${CHANGE_CURSOR} and bool true [map-actions-change-cursor-true]`, () => {
+ expect(changeCursor(true)).toEqual({ type: CHANGE_CURSOR, bool: true });
+ });
+
+ test(`returns action with type ${CHANGE_CURSOR} and bool false [map-actions-change-cursor-false]`, () => {
+ expect(changeCursor(false)).toEqual({ type: CHANGE_CURSOR, bool: false });
+ });
+});
+
+describe('updateMapExtent', () => {
+ test(`returns action with type ${UPDATE_MAP_EXTENT} and extent value [map-actions-update-map-extent]`, () => {
+ const extent = [-180, -90, 180, 90];
+ expect(updateMapExtent(extent)).toEqual({ type: UPDATE_MAP_EXTENT, extent });
+ });
+
+ test('returns action with empty array extent [map-actions-update-map-extent-empty]', () => {
+ expect(updateMapExtent([])).toEqual({ type: UPDATE_MAP_EXTENT, extent: [] });
+ });
+
+ test('returns action with undefined extent [map-actions-update-map-extent-undefined]', () => {
+ expect(updateMapExtent(undefined)).toEqual({ type: UPDATE_MAP_EXTENT, extent: undefined });
+ });
+
+ test('returns action with null extent [map-actions-update-map-extent-null]', () => {
+ expect(updateMapExtent(null)).toEqual({ type: UPDATE_MAP_EXTENT, extent: null });
+ });
+});
+
+describe('updateRenderedState', () => {
+ test(`returns action with type ${RENDERED} [map-actions-update-rendered-state]`, () => {
+ expect(updateRenderedState()).toEqual({ type: RENDERED });
+ });
+
+ test('returns no extra properties [map-actions-update-rendered-state-no-extra-props]', () => {
+ const action = updateRenderedState();
+ expect(Object.keys(action)).toEqual(['type']);
+ });
+});
+
+describe('updateMapUI', () => {
+ test(`returns action with type ${UPDATE_MAP_UI}, ui and rotation [map-actions-update-map-ui]`, () => {
+ const ui = { selected: true };
+ const rotation = 90;
+ expect(updateMapUI(ui, rotation)).toEqual({ type: UPDATE_MAP_UI, ui, rotation });
+ });
+
+ test('returns action with rotation of 0 [map-actions-update-map-ui-zero-rotation]', () => {
+ const ui = { selected: false };
+ expect(updateMapUI(ui, 0)).toEqual({ type: UPDATE_MAP_UI, ui, rotation: 0 });
+ });
+
+ test('returns action with null ui [map-actions-update-map-ui-null-ui]', () => {
+ expect(updateMapUI(null, 45)).toEqual({ type: UPDATE_MAP_UI, ui: null, rotation: 45 });
+ });
+
+ test('returns action with undefined rotation [map-actions-update-map-ui-undefined-rotation]', () => {
+ const ui = { selected: true };
+ expect(updateMapUI(ui, undefined)).toEqual({ type: UPDATE_MAP_UI, ui, rotation: undefined });
+ });
+
+ test('returns action with negative rotation [map-actions-update-map-ui-negative-rotation]', () => {
+ const ui = { selected: true };
+ expect(updateMapUI(ui, -45)).toEqual({ type: UPDATE_MAP_UI, ui, rotation: -45 });
+ });
+});
+
+describe('fitToLeadingExtent', () => {
+ test(`returns action with type ${FITTED_TO_LEADING_EXTENT} and extent [map-actions-fit-to-leading-extent]`, () => {
+ const extent = [-100, -50, 100, 50];
+ expect(fitToLeadingExtent(extent)).toEqual({ type: FITTED_TO_LEADING_EXTENT, extent });
+ });
+
+ test('returns action with empty array extent [map-actions-fit-to-leading-extent-empty]', () => {
+ expect(fitToLeadingExtent([])).toEqual({ type: FITTED_TO_LEADING_EXTENT, extent: [] });
+ });
+
+ test('returns action with null extent [map-actions-fit-to-leading-extent-null]', () => {
+ expect(fitToLeadingExtent(null)).toEqual({ type: FITTED_TO_LEADING_EXTENT, extent: null });
+ });
+
+ test('returns action with undefined extent [map-actions-fit-to-leading-extent-undefined]', () => {
+ expect(fitToLeadingExtent(undefined)).toEqual(
+ { type: FITTED_TO_LEADING_EXTENT, extent: undefined },
+ );
+ });
});
diff --git a/web/js/modules/map/reducers.test.js b/web/js/modules/map/reducers.test.js
index 04cce6a78..c59fc8143 100644
--- a/web/js/modules/map/reducers.test.js
+++ b/web/js/modules/map/reducers.test.js
@@ -1,3 +1,265 @@
-test('reducers module test', () => {
+import mapReducer from './reducers';
+import {
+ UPDATE_MAP_EXTENT,
+ UPDATE_MAP_UI,
+ UPDATE_MAP_ROTATION,
+ RENDERED,
+ FITTED_TO_LEADING_EXTENT,
+ CHANGE_CURSOR,
+ REFRESH_ROTATE,
+} from './constants';
+const INITIAL_STATE = {
+ ui: { selected: null },
+ rotation: 0,
+ extent: [],
+ rendered: false,
+ leadingExtent: [],
+ isClickable: false,
+};
+
+describe('mapReducer', () => {
+ describe('initial state', () => {
+ test('returns initial state when called with undefined state and empty action [map-reducer-initial-state]', () => {
+ expect(mapReducer(undefined, {})).toEqual(INITIAL_STATE);
+ });
+
+ test('initial state has rotation of 0 [map-reducer-initial-state-rotation]', () => {
+ expect(mapReducer(undefined, {}).rotation).toBe(0);
+ });
+
+ test('initial state has empty extent [map-reducer-initial-state-extent]', () => {
+ expect(mapReducer(undefined, {}).extent).toEqual([]);
+ });
+
+ test('initial state has rendered false [map-reducer-initial-state-rendered]', () => {
+ expect(mapReducer(undefined, {}).rendered).toBe(false);
+ });
+
+ test('initial state has empty leadingExtent [map-reducer-initial-state-leading-extent]', () => {
+ expect(mapReducer(undefined, {}).leadingExtent).toEqual([]);
+ });
+
+ test('initial state has isClickable false [map-reducer-initial-state-is-clickable]', () => {
+ expect(mapReducer(undefined, {}).isClickable).toBe(false);
+ });
+
+ test('initial state has ui with selected null [map-reducer-initial-state-ui]', () => {
+ expect(mapReducer(undefined, {}).ui).toEqual({ selected: null });
+ });
+ });
+
+ describe(`${UPDATE_MAP_EXTENT}`, () => {
+ test('sets extent to provided value [map-reducer-update-map-extent]', () => {
+ const extent = [-180, -90, 180, 90];
+ expect(mapReducer(INITIAL_STATE, { type: UPDATE_MAP_EXTENT, extent })).toEqual({
+ ...INITIAL_STATE,
+ extent,
+ });
+ });
+
+ test('sets extent to empty array [map-reducer-update-map-extent-empty]', () => {
+ const state = { ...INITIAL_STATE, extent: [-180, -90, 180, 90] };
+ expect(mapReducer(state, { type: UPDATE_MAP_EXTENT, extent: [] })).toEqual({
+ ...INITIAL_STATE,
+ extent: [],
+ });
+ });
+
+ test('does not mutate other state properties [map-reducer-update-map-extent-no-mutation]', () => {
+ const extent = [-100, -50, 100, 50];
+ const result = mapReducer(INITIAL_STATE, { type: UPDATE_MAP_EXTENT, extent });
+ expect(result.rotation).toBe(INITIAL_STATE.rotation);
+ expect(result.rendered).toBe(INITIAL_STATE.rendered);
+ expect(result.isClickable).toBe(INITIAL_STATE.isClickable);
+ });
+ });
+
+ describe(`${UPDATE_MAP_UI}`, () => {
+ test('sets ui and rotation from action [map-reducer-update-map-ui]', () => {
+ const ui = { selected: true };
+ const rotation = 90;
+ expect(mapReducer(INITIAL_STATE, { type: UPDATE_MAP_UI, ui, rotation })).toEqual({
+ ...INITIAL_STATE,
+ ui,
+ rotation,
+ });
+ });
+
+ test('sets rotation to 0 [map-reducer-update-map-ui-zero-rotation]', () => {
+ const ui = { selected: false };
+ const result = mapReducer(INITIAL_STATE, { type: UPDATE_MAP_UI, ui, rotation: 0 });
+ expect(result.rotation).toBe(0);
+ expect(result.ui).toEqual(ui);
+ });
+
+ test('sets rotation to negative value [map-reducer-update-map-ui-negative-rotation]', () => {
+ const ui = { selected: true };
+ const result = mapReducer(INITIAL_STATE, { type: UPDATE_MAP_UI, ui, rotation: -45 });
+ expect(result.rotation).toBe(-45);
+ });
+
+ test('does not mutate other state properties [map-reducer-update-map-ui-no-mutation]', () => {
+ const ui = { selected: true };
+ const result = mapReducer(INITIAL_STATE, { type: UPDATE_MAP_UI, ui, rotation: 90 });
+ expect(result.extent).toEqual(INITIAL_STATE.extent);
+ expect(result.rendered).toBe(INITIAL_STATE.rendered);
+ expect(result.isClickable).toBe(INITIAL_STATE.isClickable);
+ });
+ });
+
+ describe(`${UPDATE_MAP_ROTATION}`, () => {
+ test('sets rotation from action [map-reducer-update-map-rotation]', () => {
+ expect(mapReducer(INITIAL_STATE, { type: UPDATE_MAP_ROTATION, rotation: 45 })).toEqual({
+ ...INITIAL_STATE,
+ rotation: 45,
+ });
+ });
+
+ test('sets rotation to 0 [map-reducer-update-map-rotation-zero]', () => {
+ const state = { ...INITIAL_STATE, rotation: 90 };
+ expect(mapReducer(state, { type: UPDATE_MAP_ROTATION, rotation: 0 })).toEqual({
+ ...INITIAL_STATE,
+ rotation: 0,
+ });
+ });
+
+ test('sets rotation to negative value [map-reducer-update-map-rotation-negative]', () => {
+ expect(mapReducer(
+ INITIAL_STATE, { type: UPDATE_MAP_ROTATION, rotation: -90 },
+ ).rotation).toBe(-90);
+ });
+
+ test('does not mutate other state properties [map-reducer-update-map-rotation-no-mutation]', () => {
+ const result = mapReducer(INITIAL_STATE, { type: UPDATE_MAP_ROTATION, rotation: 45 });
+ expect(result.extent).toEqual(INITIAL_STATE.extent);
+ expect(result.rendered).toBe(INITIAL_STATE.rendered);
+ expect(result.ui).toEqual(INITIAL_STATE.ui);
+ });
+ });
+
+ describe(`${REFRESH_ROTATE}`, () => {
+ test('sets rotation from action identically to UPDATE_MAP_ROTATION [map-reducer-refresh-rotate]', () => {
+ expect(mapReducer(INITIAL_STATE, { type: REFRESH_ROTATE, rotation: 180 })).toEqual({
+ ...INITIAL_STATE,
+ rotation: 180,
+ });
+ });
+
+ test('sets rotation to 0 [map-reducer-refresh-rotate-zero]', () => {
+ const state = { ...INITIAL_STATE, rotation: 270 };
+ expect(mapReducer(state, { type: REFRESH_ROTATE, rotation: 0 }).rotation).toBe(0);
+ });
+
+ test('sets rotation to decimal value [map-reducer-refresh-rotate-decimal]', () => {
+ expect(mapReducer(
+ INITIAL_STATE, { type: REFRESH_ROTATE, rotation: 22.5 },
+ ).rotation).toBe(22.5);
+ });
+
+ test('does not mutate other state properties [map-reducer-refresh-rotate-no-mutation]', () => {
+ const result = mapReducer(INITIAL_STATE, { type: REFRESH_ROTATE, rotation: 180 });
+ expect(result.isClickable).toBe(INITIAL_STATE.isClickable);
+ expect(result.rendered).toBe(INITIAL_STATE.rendered);
+ expect(result.leadingExtent).toEqual(INITIAL_STATE.leadingExtent);
+ });
+ });
+
+ describe(`${RENDERED}`, () => {
+ test('sets rendered to true [map-reducer-rendered]', () => {
+ expect(mapReducer(INITIAL_STATE, { type: RENDERED })).toEqual({
+ ...INITIAL_STATE,
+ rendered: true,
+ });
+ });
+
+ test('rendered stays true when already true [map-reducer-rendered-already-true]', () => {
+ const state = { ...INITIAL_STATE, rendered: true };
+ expect(mapReducer(state, { type: RENDERED }).rendered).toBe(true);
+ });
+
+ test('does not mutate other state properties [map-reducer-rendered-no-mutation]', () => {
+ const result = mapReducer(INITIAL_STATE, { type: RENDERED });
+ expect(result.rotation).toBe(INITIAL_STATE.rotation);
+ expect(result.extent).toEqual(INITIAL_STATE.extent);
+ expect(result.isClickable).toBe(INITIAL_STATE.isClickable);
+ expect(result.ui).toEqual(INITIAL_STATE.ui);
+ });
+ });
+
+ describe(`${FITTED_TO_LEADING_EXTENT}`, () => {
+ test('sets leadingExtent to provided value [map-reducer-fitted-to-leading-extent]', () => {
+ const extent = [-100, -50, 100, 50];
+ expect(mapReducer(INITIAL_STATE, { type: FITTED_TO_LEADING_EXTENT, extent })).toEqual({
+ ...INITIAL_STATE,
+ leadingExtent: extent,
+ });
+ });
+
+ test('sets leadingExtent to empty array [map-reducer-fitted-to-leading-extent-empty]', () => {
+ const state = { ...INITIAL_STATE, leadingExtent: [-100, -50, 100, 50] };
+ expect(mapReducer(state, { type: FITTED_TO_LEADING_EXTENT, extent: [] })).toEqual({
+ ...INITIAL_STATE,
+ leadingExtent: [],
+ });
+ });
+
+ test('does not mutate other state properties [map-reducer-fitted-to-leading-extent-no-mutation]', () => {
+ const extent = [-100, -50, 100, 50];
+ const result = mapReducer(INITIAL_STATE, { type: FITTED_TO_LEADING_EXTENT, extent });
+ expect(result.rotation).toBe(INITIAL_STATE.rotation);
+ expect(result.rendered).toBe(INITIAL_STATE.rendered);
+ expect(result.isClickable).toBe(INITIAL_STATE.isClickable);
+ expect(result.ui).toEqual(INITIAL_STATE.ui);
+ });
+ });
+
+ describe(`${CHANGE_CURSOR}`, () => {
+ test('sets isClickable to true [map-reducer-change-cursor-true]', () => {
+ expect(mapReducer(INITIAL_STATE, { type: CHANGE_CURSOR, bool: true })).toEqual({
+ ...INITIAL_STATE,
+ isClickable: true,
+ });
+ });
+
+ test('sets isClickable to false [map-reducer-change-cursor-false]', () => {
+ const state = { ...INITIAL_STATE, isClickable: true };
+ expect(mapReducer(state, { type: CHANGE_CURSOR, bool: false })).toEqual({
+ ...INITIAL_STATE,
+ isClickable: false,
+ });
+ });
+
+ test('does not mutate other state properties [map-reducer-change-cursor-no-mutation]', () => {
+ const result = mapReducer(INITIAL_STATE, { type: CHANGE_CURSOR, bool: true });
+ expect(result.rotation).toBe(INITIAL_STATE.rotation);
+ expect(result.rendered).toBe(INITIAL_STATE.rendered);
+ expect(result.extent).toEqual(INITIAL_STATE.extent);
+ expect(result.leadingExtent).toEqual(INITIAL_STATE.leadingExtent);
+ expect(result.ui).toEqual(INITIAL_STATE.ui);
+ });
+ });
+
+ describe('default', () => {
+ test('returns current state for unknown action type [map-reducer-default]', () => {
+ expect(mapReducer(INITIAL_STATE, { type: 'UNKNOWN_ACTION' })).toEqual(INITIAL_STATE);
+ });
+
+ test('returns custom state unchanged for unknown action type [map-reducer-default-custom-state]', () => {
+ const customState = {
+ ui: { selected: true },
+ rotation: 45,
+ extent: [-180, -90, 180, 90],
+ rendered: true,
+ leadingExtent: [-100, -50, 100, 50],
+ isClickable: true,
+ };
+ expect(mapReducer(customState, { type: 'UNKNOWN_ACTION' })).toEqual(customState);
+ });
+
+ test('returns same state reference for unknown action type [map-reducer-default-same-reference]', () => {
+ const result = mapReducer(INITIAL_STATE, { type: 'UNKNOWN_ACTION' });
+ expect(result).toBe(INITIAL_STATE);
+ });
+ });
});
diff --git a/web/js/modules/map/util.test.js b/web/js/modules/map/util.test.js
index 4072f4f95..1ba412b68 100644
--- a/web/js/modules/map/util.test.js
+++ b/web/js/modules/map/util.test.js
@@ -1,3 +1,641 @@
-test('util module test', () => {
+import {
+ getLeadingExtent,
+ getRotatedExtent,
+ mapIsExtentValid,
+ getMapParameterSetup,
+ promiseImageryForTime,
+ promiseImageryForTour,
+} from './util';
+jest.mock('ol/extent', () => ({
+ getForViewAndSize: jest.fn(() => [10, 20, 30, 40]),
+}));
+
+jest.mock('ol/layer/Image', () => {
+ const MockImageLayer = jest.fn().mockImplementation(() => ({}));
+ return MockImageLayer;
+});
+
+jest.mock('ol/Map', () => {
+ return jest.fn().mockImplementation(() => {
+ const layersArray = [];
+ const listeners = {};
+ const instance = {
+ getView: jest.fn(),
+ setView: jest.fn(),
+ addLayer: jest.fn((layer) => layersArray.push(layer)),
+ removeLayer: jest.fn((layer) => {
+ const idx = layersArray.indexOf(layer);
+ if (idx !== -1) layersArray.splice(idx, 1);
+ }),
+ getLayers: jest.fn(() => ({ getArray: jest.fn(() => layersArray) })),
+ on: jest.fn((event, cb) => { listeners[event] = cb; }),
+ un: jest.fn((event) => { delete listeners[event]; }),
+ fire: (event) => { if (listeners[event]) listeners[event](); },
+ layersArray,
+ };
+ return instance;
+ });
+});
+
+jest.mock('../link/util', () => ({
+ encode: jest.fn((val) => `encoded:${val}`),
+}));
+
+jest.mock('../layers/selectors', () => ({
+ getActiveVisibleLayersAtDate: jest.fn(),
+}));
+
+jest.mock('../date/util', () => ({
+ tryCatchDate: jest.fn((dateString) => new Date(dateString)),
+}));
+
+import * as olExtent from 'ol/extent';
+import OlMap from 'ol/Map';
+import { encode } from '../link/util';
+import { getActiveVisibleLayersAtDate } from '../layers/selectors';
+import { tryCatchDate } from '../date/util';
+
+function makeMockMap(view) {
+ return {
+ getView: jest.fn(() => view || {}),
+ getSize: jest.fn(() => [800, 600]),
+ };
+}
+
+function makeBaseState(uiOverrides = {}) {
+ const mockChanged = jest.fn();
+ const mockView = { changed: mockChanged };
+ const mockSelected = { getView: jest.fn(() => mockView) };
+ const mockCache = { getItem: jest.fn(() => null) };
+ const mockLayerKey = jest.fn(() => 'key');
+ const mockCreateLayer = jest.fn();
+
+ const state = {
+ map: {
+ ui: {
+ proj: 'geographic',
+ cache: mockCache,
+ selected: mockSelected,
+ createLayer: mockCreateLayer,
+ layerKey: mockLayerKey,
+ ...uiOverrides,
+ },
+ },
+ };
+
+ return { state, mockChanged, mockCache, mockSelected, mockCreateLayer, mockLayerKey };
+}
+
+function makeTileLayer() {
+ return {
+ isVector: false,
+ setVisible: jest.fn(),
+ };
+}
+
+function makeLayerGroup(layers, proj = 'arctic') {
+ return {
+ wv: { proj },
+ getLayersArray: jest.fn(() => layers),
+ };
+}
+
+describe('getLeadingExtent', () => {
+ const minLat = -46.546875;
+ const maxLat = 53.015625;
+
+ function makeUTCDate(hour) {
+ return new Date(Date.UTC(2020, 0, 1, hour, 0, 0));
+ }
+
+ test('hour 0 forces curHour to 23', () => {
+ const result = getLeadingExtent(makeUTCDate(0));
+ const expectedMinLon = 20.6015625 + 23 * (-200.53125 / 23.0);
+ const expectedMaxLon = expectedMinLon + 159.328125;
+ expect(result).toEqual([expectedMinLon, minLat, expectedMaxLon, maxLat]);
+ });
+
+ test('hour 1 forces curHour to 23', () => {
+ const result = getLeadingExtent(makeUTCDate(1));
+ const expectedMinLon = 20.6015625 + 23 * (-200.53125 / 23.0);
+ const expectedMaxLon = expectedMinLon + 159.328125;
+ expect(result).toEqual([expectedMinLon, minLat, expectedMaxLon, maxLat]);
+ });
+
+ test('hour 2 forces curHour to 23', () => {
+ const result = getLeadingExtent(makeUTCDate(2));
+ const expectedMinLon = 20.6015625 + 23 * (-200.53125 / 23.0);
+ const expectedMaxLon = expectedMinLon + 159.328125;
+ expect(result).toEqual([expectedMinLon, minLat, expectedMaxLon, maxLat]);
+ });
+
+ test('hour 3 forces curHour to 0', () => {
+ const result = getLeadingExtent(makeUTCDate(3));
+ const expectedMinLon = 20.6015625 + 0 * (-200.53125 / 23.0);
+ const expectedMaxLon = expectedMinLon + 159.328125;
+ expect(result).toEqual([expectedMinLon, minLat, expectedMaxLon, maxLat]);
+ });
+
+ test('hour 8 forces curHour to 0', () => {
+ const result = getLeadingExtent(makeUTCDate(8));
+ const expectedMinLon = 20.6015625 + 0 * (-200.53125 / 23.0);
+ const expectedMaxLon = expectedMinLon + 159.328125;
+ expect(result).toEqual([expectedMinLon, minLat, expectedMaxLon, maxLat]);
+ });
+
+ test('hour 9 uses actual hour', () => {
+ const result = getLeadingExtent(makeUTCDate(9));
+ const expectedMinLon = 20.6015625 + 9 * (-200.53125 / 23.0);
+ const expectedMaxLon = expectedMinLon + 159.328125;
+ expect(result).toEqual([expectedMinLon, minLat, expectedMaxLon, maxLat]);
+ });
+
+ test('hour 23 uses actual hour', () => {
+ const result = getLeadingExtent(makeUTCDate(23));
+ const expectedMinLon = 20.6015625 + 23 * (-200.53125 / 23.0);
+ const expectedMaxLon = expectedMinLon + 159.328125;
+ expect(result).toEqual([expectedMinLon, minLat, expectedMaxLon, maxLat]);
+ });
+
+ test('always returns a 4-element array with correct lat bounds', () => {
+ const result = getLeadingExtent(makeUTCDate(12));
+ expect(result).toHaveLength(4);
+ expect(result[1]).toBe(minLat);
+ expect(result[3]).toBe(maxLat);
+ });
+});
+
+describe('getRotatedExtent', () => {
+ test('calls getForViewAndSize with correct args and returns result', () => {
+ const mockCenter = [0, 0];
+ const mockResolution = 2000;
+ const mockSize = [800, 600];
+ const mockView = {
+ getCenter: jest.fn(() => mockCenter),
+ getResolution: jest.fn(() => mockResolution),
+ };
+ const mockMap = {
+ getView: jest.fn(() => mockView),
+ getSize: jest.fn(() => mockSize),
+ };
+
+ const result = getRotatedExtent(mockMap);
+
+ expect(mockMap.getView).toHaveBeenCalled();
+ expect(olExtent.getForViewAndSize)
+ .toHaveBeenCalledWith(mockCenter, mockResolution, 0, mockSize);
+ expect(result).toEqual([10, 20, 30, 40]);
+ });
+});
+
+describe('mapIsExtentValid', () => {
+ test('returns false for undefined input', () => {
+ expect(mapIsExtentValid(undefined)).toBe(false);
+ });
+
+ test('returns true for valid array extent', () => {
+ expect(mapIsExtentValid([10, 20, 30, 40])).toBe(true);
+ });
+
+ test('returns false when any value is NaN', () => {
+ expect(mapIsExtentValid([10, NaN, 30, 40])).toBe(false);
+ });
+
+ test('returns false when all values are NaN', () => {
+ expect(mapIsExtentValid([NaN, NaN, NaN, NaN])).toBe(false);
+ });
+
+ test('returns true for object with toArray returning valid values', () => {
+ const extentObj = { toArray: () => [1, 2, 3, 4] };
+ expect(mapIsExtentValid(extentObj)).toBe(true);
+ });
+
+ test('returns false for object with toArray returning NaN values', () => {
+ const extentObj = { toArray: () => [1, NaN, 3, 4] };
+ expect(mapIsExtentValid(extentObj)).toBe(false);
+ });
+
+ test('returns true for valid negative values', () => {
+ expect(mapIsExtentValid([-180, -90, 180, 90])).toBe(true);
+ });
+
+ test('returns true for zero values', () => {
+ expect(mapIsExtentValid([0, 0, 0, 0])).toBe(true);
+ });
+});
+
+describe('getMapParameterSetup', () => {
+ let config;
+ let models;
+ let errors;
+ let parameters;
+ let legacyState;
+
+ beforeEach(() => {
+ config = { pageLoadTime: new Date(Date.UTC(2020, 0, 1, 12, 0, 0)) };
+ models = { map: { load: jest.fn() } };
+ errors = [];
+ parameters = {};
+ legacyState = {};
+ encode.mockReturnValue('encodedExtent');
+ });
+
+ test('calls models.map.load with legacyState and errors', () => {
+ getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(models.map.load).toHaveBeenCalledWith(legacyState, errors);
+ });
+
+ test('returns object with v and r keys', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result).toHaveProperty('v');
+ expect(result).toHaveProperty('r');
+ });
+
+ test('v.stateKey is map.extent', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.v.stateKey).toBe('map.extent');
+ });
+
+ test('v.initialState is the leading extent', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.v.initialState).toEqual(getLeadingExtent(config.pageLoadTime));
+ });
+
+ test('r.stateKey is map.rotation', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.r.stateKey).toBe('map.rotation');
+ });
+
+ test('r.initialState is 0', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.r.initialState).toBe(0);
+ });
+
+ describe('v.options.parse', () => {
+ test('parses valid extent string and returns float array', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.v.options.parse('10,20,30,40')).toEqual([10, 20, 30, 40]);
+ });
+
+ test('returns leadingExtent and pushes error for invalid extent', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const parsed = result.v.options.parse('foo,bar,baz,qux');
+ expect(parsed).toEqual(getLeadingExtent(config.pageLoadTime));
+ expect(errors).toHaveLength(1);
+ expect(errors[0].message).toContain('Invalid extent');
+ });
+ });
+
+ describe('v.options.serialize', () => {
+ test('returns encoded extent when valid and not equal to leading extent', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const currentState = { map: { rotation: 0, leadingExtent: [0, 0, 0, 0] } };
+ const serialized = result.v.options.serialize([1, 2, 3, 4], currentState);
+ expect(encode).toHaveBeenCalledWith([1, 2, 3, 4]);
+ expect(serialized).toBe('encodedExtent');
+ });
+
+ test('returns undefined when extent equals leading extent', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const leadingExtent = getLeadingExtent(config.pageLoadTime);
+ const currentState = { map: { rotation: 0, leadingExtent } };
+ expect(result.v.options.serialize(leadingExtent, currentState)).toBeUndefined();
+ });
+
+ test('uses getRotatedExtent when rotation is truthy', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const mockView = {
+ getCenter: jest.fn(() => [0, 0]),
+ getResolution: jest.fn(() => 100),
+ };
+ const mockMap = {
+ getView: jest.fn(() => mockView),
+ getSize: jest.fn(() => [800, 600]),
+ };
+ const currentState = {
+ map: {
+ rotation: 1.0,
+ leadingExtent: [0, 0, 0, 0],
+ ui: { selected: mockMap },
+ },
+ };
+ result.v.options.serialize([1, 2, 3, 4], currentState);
+ expect(olExtent.getForViewAndSize).toHaveBeenCalled();
+ });
+
+ test('returns undefined when currentItemState is invalid and leadingExtent matches', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const leadingExtent = getLeadingExtent(config.pageLoadTime);
+ const currentState = { map: { rotation: 0, leadingExtent } };
+ expect(result.v.options.serialize([NaN, NaN, NaN, NaN], currentState)).toBeUndefined();
+ });
+ });
+
+ describe('r.options.parse', () => {
+ test('returns 0 for a numeric string', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.r.options.parse('45')).toBe(0);
+ });
+
+ test('returns 0 for another numeric string', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.r.options.parse('180')).toBe(0);
+ });
+
+ test('returns NaN when passed NaN directly', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ expect(result.r.options.parse(NaN)).toBeNaN();
+ });
+ });
+
+ describe('r.options.serialize', () => {
+ test('returns degrees string when rotation is set and proj is not geographic', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const currentState = { proj: { selected: { id: 'arctic' } } };
+ expect(result.r.options.serialize(Math.PI, currentState)).toBe((180.0).toPrecision(6));
+ });
+
+ test('returns undefined when proj is geographic', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const currentState = { proj: { selected: { id: 'geographic' } } };
+ expect(result.r.options.serialize(Math.PI, currentState)).toBeUndefined();
+ });
+
+ test('returns undefined when currentItemState is falsy', () => {
+ const result = getMapParameterSetup(parameters, config, models, legacyState, errors);
+ const currentState = { proj: { selected: { id: 'arctic' } } };
+ expect(result.r.options.serialize(0, currentState)).toBeUndefined();
+ });
+ });
+});
+
+describe('promiseImageryForTime', () => {
+ beforeEach(() => {
+ OlMap.mockClear();
+ document.body.innerHTML = '';
+ });
+
+ test('returns undefined when map.ui.proj is falsy', async () => {
+ const { state } = makeBaseState({ proj: null });
+ const result = await promiseImageryForTime(state, new Date(), 'active');
+ expect(result).toBeUndefined();
+ });
+
+ test('returns date when layers list is empty', async () => {
+ const { state, mockChanged } = makeBaseState();
+ getActiveVisibleLayersAtDate.mockReturnValue([]);
+ const date = new Date('2020-01-01');
+ const result = await promiseImageryForTime(state, date, 'active');
+ expect(result).toBe(date);
+ expect(mockChanged).toHaveBeenCalled();
+ });
+
+ test('skips granule layers', async () => {
+ const { state, mockCreateLayer } = makeBaseState();
+ getActiveVisibleLayersAtDate.mockReturnValue([{ type: 'granule' }]);
+ await promiseImageryForTime(state, new Date(), 'active');
+ expect(mockCreateLayer).not.toHaveBeenCalled();
+ });
+
+ test('skips titiler layers', async () => {
+ const { state, mockCreateLayer } = makeBaseState();
+ getActiveVisibleLayersAtDate.mockReturnValue([{ type: 'titiler' }]);
+ await promiseImageryForTime(state, new Date(), 'active');
+ expect(mockCreateLayer).not.toHaveBeenCalled();
+ });
+
+ test('uses cached item when available and does not call createLayer', async () => {
+ const cachedLayerGroup = { wv: { proj: null } };
+ const { state, mockCreateLayer, mockChanged } = makeBaseState();
+ state.map.ui.cache.getItem.mockReturnValue(cachedLayerGroup);
+ getActiveVisibleLayersAtDate.mockReturnValue([{ type: 'wms' }]);
+ await promiseImageryForTime(state, new Date(), 'active');
+ expect(mockCreateLayer).not.toHaveBeenCalled();
+ expect(mockChanged).toHaveBeenCalled();
+ });
+
+ test('calls createLayer when layer is not cached', async () => {
+ const layerGroup = { wv: { proj: null } };
+ const { state, mockCreateLayer, mockChanged } = makeBaseState();
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ getActiveVisibleLayersAtDate.mockReturnValue([{ type: 'wms' }]);
+ await promiseImageryForTime(state, new Date(), 'active');
+ expect(mockCreateLayer).toHaveBeenCalled();
+ expect(mockChanged).toHaveBeenCalled();
+ });
+});
+
+describe('promiseImageryForTour', () => {
+ beforeEach(() => {
+ OlMap.mockClear();
+ document.body.innerHTML = '';
+ tryCatchDate.mockImplementation((dateString) => new Date(dateString));
+ });
+
+ test('returns early when map.ui.proj is falsy', async () => {
+ const { state, mockChanged } = makeBaseState({ proj: null });
+ await promiseImageryForTour(state, [], '2020-01-01', 'active');
+ expect(mockChanged).not.toHaveBeenCalled();
+ });
+
+ test('processes empty layer list and calls changed', async () => {
+ const { state, mockChanged } = makeBaseState();
+ await promiseImageryForTour(state, [], '2020-01-01', 'active');
+ expect(mockChanged).toHaveBeenCalled();
+ });
+
+ test('skips granule layers', async () => {
+ const { state, mockCreateLayer } = makeBaseState();
+ await promiseImageryForTour(state, [{ type: 'granule' }], '2020-01-01', 'active');
+ expect(mockCreateLayer).not.toHaveBeenCalled();
+ });
+
+ test('skips titiler layers', async () => {
+ const { state, mockCreateLayer } = makeBaseState();
+ await promiseImageryForTour(state, [{ type: 'titiler' }], '2020-01-01', 'active');
+ expect(mockCreateLayer).not.toHaveBeenCalled();
+ });
+
+ test('defaults group to active when activeString is undefined', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ await promiseImageryForTour(state, [{ type: 'wms' }], '2020-01-01', undefined);
+ expect(mockLayerKey).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ group: 'active' }),
+ state,
+ );
+ });
+
+ test('builds style from layer.custom', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ const layer = { type: 'wms', custom: 'myPalette' };
+ await promiseImageryForTour(state, [layer], '2020-01-01', 'active');
+ expect(mockLayerKey).toHaveBeenCalledWith(
+ layer,
+ expect.objectContaining({ style: 'palette=myPalette' }),
+ state,
+ );
+ });
+
+ test('builds style from layer.min', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ const layer = { type: 'wms', min: 0.1 };
+ await promiseImageryForTour(state, [layer], '2020-01-01', 'active');
+ expect(mockLayerKey).toHaveBeenCalledWith(
+ layer,
+ expect.objectContaining({ style: 'min=0.1' }),
+ state,
+ );
+ });
+
+ test('builds style from layer.max', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ const layer = { type: 'wms', max: 0.9 };
+ await promiseImageryForTour(state, [layer], '2020-01-01', 'active');
+ expect(mockLayerKey).toHaveBeenCalledWith(
+ layer,
+ expect.objectContaining({ style: 'max=0.9' }),
+ state,
+ );
+ });
+
+ test('builds style with squash', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ const layer = { type: 'wms', squash: true };
+ await promiseImageryForTour(state, [layer], '2020-01-01', 'active');
+ expect(mockLayerKey).toHaveBeenCalledWith(
+ layer,
+ expect.objectContaining({ style: 'squash' }),
+ state,
+ );
+ });
+
+ test('builds style with noclip', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ const layer = { type: 'wms', noclip: true };
+ await promiseImageryForTour(state, [layer], '2020-01-01', 'active');
+ expect(mockLayerKey).toHaveBeenCalledWith(
+ layer,
+ expect.objectContaining({ style: 'noclip' }),
+ state,
+ );
+ });
+
+ test('builds combined style string from all options', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ const layer = { type: 'wms', custom: 'pal', min: 0.1, max: 0.9, squash: true, noclip: true };
+ await promiseImageryForTour(state, [layer], '2020-01-01', 'active');
+ expect(mockLayerKey).toHaveBeenCalledWith(
+ layer,
+ expect.objectContaining({ style: 'palette=pal,min=0.1,max=0.9,squash,noclip' }),
+ state,
+ );
+ });
+
+ test('does not set style when no style keys are present', async () => {
+ const { state, mockCreateLayer, mockLayerKey } = makeBaseState();
+ const layerGroup = { wv: { proj: null } };
+ mockCreateLayer.mockResolvedValue(layerGroup);
+ const layer = { type: 'wms' };
+ await promiseImageryForTour(state, [layer], '2020-01-01', 'active');
+ const callArgs = mockLayerKey.mock.calls[0][1];
+ expect(callArgs).not.toHaveProperty('style');
+ });
+
+ test('uses cached item and does not call createLayer', async () => {
+ const { state, mockCreateLayer, mockChanged } = makeBaseState();
+ const cachedLayerGroup = { wv: { proj: null } };
+ state.map.ui.cache.getItem.mockReturnValue(cachedLayerGroup);
+ await promiseImageryForTour(state, [{ type: 'wms' }], '2020-01-01', 'active');
+ expect(mockCreateLayer).not.toHaveBeenCalled();
+ expect(mockChanged).toHaveBeenCalled();
+ });
+});
+
+describe('promiseTileLayer (via promiseImageryForTime)', () => {
+ beforeEach(() => {
+ OlMap.mockClear();
+ document.body.innerHTML = '';
+ });
+
+ test('resolves immediately when wv-map container is absent from DOM', async () => {
+ const mockMap = makeMockMap();
+ const tileLayer = makeTileLayer();
+ const layerGroup = makeLayerGroup([tileLayer], 'arctic');
+ const { state, mockChanged } = makeBaseState({
+ createLayer: jest.fn().mockResolvedValue(layerGroup),
+ proj: { arctic: mockMap },
+ });
+
+ getActiveVisibleLayersAtDate.mockReturnValue([{ type: 'wms' }]);
+
+ await promiseImageryForTime(state, new Date(), 'active');
+ expect(mockChanged).toHaveBeenCalled();
+ });
+
+ test('creates preloadMap and resolves after loadend fires', async () => {
+ const mapContainer = document.createElement('div');
+ mapContainer.setAttribute('id', 'wv-map');
+ document.body.appendChild(mapContainer);
+
+ const mockView = {};
+ const mockMap = makeMockMap(mockView);
+ const tileLayer = makeTileLayer();
+ const layerGroup = makeLayerGroup([tileLayer], 'arctic');
+ const { state, mockChanged } = makeBaseState({
+ createLayer: jest.fn().mockResolvedValue(layerGroup),
+ proj: { arctic: mockMap },
+ });
+
+ getActiveVisibleLayersAtDate.mockReturnValue([{ type: 'wms' }]);
+
+ const promise = promiseImageryForTime(state, new Date(), 'active');
+
+ await Promise.resolve();
+ await Promise.resolve();
+
+ const instance = OlMap.mock.results[0]?.value;
+ if (instance?.fire) instance.fire('loadend');
+
+ await promise;
+
+ expect(OlMap).toHaveBeenCalled();
+ expect(mockChanged).toHaveBeenCalled();
+ });
+
+ test('skips promiseTileLayer for vector layers', async () => {
+ const mapContainer = document.createElement('div');
+ mapContainer.setAttribute('id', 'wv-map');
+ document.body.appendChild(mapContainer);
+
+ const mockMap = makeMockMap();
+ const vectorLayer = { isVector: true, setVisible: jest.fn() };
+ const layerGroup = makeLayerGroup([vectorLayer], 'arctic');
+ const { state, mockChanged } = makeBaseState({
+ createLayer: jest.fn().mockResolvedValue(layerGroup),
+ proj: { arctic: mockMap },
+ });
+
+ getActiveVisibleLayersAtDate.mockReturnValue([{ type: 'wms' }]);
+
+ await promiseImageryForTime(state, new Date(), 'active');
+
+ expect(vectorLayer.setVisible).not.toHaveBeenCalled();
+ expect(mockChanged).toHaveBeenCalled();
+ });
});
diff --git a/web/js/modules/measure/actions.test.js b/web/js/modules/measure/actions.test.js
index 22bc698b0..18cb26dd4 100644
--- a/web/js/modules/measure/actions.test.js
+++ b/web/js/modules/measure/actions.test.js
@@ -1,3 +1,27 @@
-test('actions module test', () => {
+import {
+ CHANGE_UNITS,
+ UPDATE_MEASUREMENTS,
+ TOGGLE_MEASURE_ACTIVE,
+} from './constants';
+import {
+ changeUnits,
+ toggleMeasureActive,
+ updateMeasurements,
+} from './actions';
+
+describe('Measure modules actions', () => {
+ test('changeUnits returns action with type CHANGE_UNITS and value [measure-actions-change-units]', () => {
+ expect(changeUnits('miles')).toEqual({ type: CHANGE_UNITS, value: 'miles' });
+ });
+
+ test('toggleMeasureActive returns action with type TOGGLE_MEASURE_ACTIVE and value [measure-actions-toggle-measure-active]', () => {
+ expect(toggleMeasureActive(true)).toEqual({ type: TOGGLE_MEASURE_ACTIVE, value: true });
+ });
+
+ test('updateMeasurements returns action with type UPDATE_MEASUREMENTS and value [measure-actions-update-measurements]', () => {
+ const measurements = { EPSG4326: { distance: 100 } };
+ expect(updateMeasurements(measurements))
+ .toEqual({ type: UPDATE_MEASUREMENTS, value: measurements });
+ });
});
diff --git a/web/js/modules/measure/reducers.test.js b/web/js/modules/measure/reducers.test.js
index 04cce6a78..72967c0f0 100644
--- a/web/js/modules/measure/reducers.test.js
+++ b/web/js/modules/measure/reducers.test.js
@@ -1,3 +1,51 @@
-test('reducers module test', () => {
+import {
+ CHANGE_UNITS,
+ UPDATE_MEASUREMENTS,
+ TOGGLE_MEASURE_ACTIVE,
+} from './constants';
+import { CRS } from '../map/constants';
+import measureReducer from './reducers';
+
+const defaultState = {
+ isActive: false,
+ unitOfMeasure: 'km',
+ allMeasurements: {
+ ...Object.values(CRS)
+ .reduce((prev, key) => ({
+ ...prev,
+ [key]: {},
+ }), {}),
+ },
+};
+
+describe('Measure module reducers', () => {
+ test('returns default state [measure-reducers-default-state]', () => {
+ expect(measureReducer(undefined, {})).toEqual(defaultState);
+ });
+
+ test('returns state with updated unit of measure [measure-reducers-change-units]', () => {
+ const action = { type: CHANGE_UNITS, value: 'miles' };
+ expect(measureReducer(defaultState, action)).toEqual({
+ ...defaultState,
+ unitOfMeasure: 'miles',
+ });
+ });
+
+ test('returns state with updated isActive [measure-reducers-toggle-measure-active]', () => {
+ const action = { type: TOGGLE_MEASURE_ACTIVE, value: true };
+ expect(measureReducer(defaultState, action)).toEqual({
+ ...defaultState,
+ isActive: true,
+ });
+ });
+
+ test('returns state with updated measurements [measure-reducers-update-measurements]', () => {
+ const measurements = { EPSG4326: { distance: 100 } };
+ const action = { type: UPDATE_MEASUREMENTS, value: measurements };
+ expect(measureReducer(defaultState, action)).toEqual({
+ ...defaultState,
+ allMeasurements: measurements,
+ });
+ });
});
diff --git a/web/js/modules/modal/actions.test.js b/web/js/modules/modal/actions.test.js
index fbcae559e..203f53a58 100644
--- a/web/js/modules/modal/actions.test.js
+++ b/web/js/modules/modal/actions.test.js
@@ -7,11 +7,13 @@ import {
renderTemplate,
requestTemplate,
onToggle,
+ onClose,
+ toggleAboutModal,
+ toggleCustomContent,
} from './actions';
import * as constants from './constants';
import util from '../../util/util';
-// jsdom polyfills
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
@@ -71,7 +73,6 @@ describe('Modal open actions', () => {
`renderTemplate action returns ${constants.RENDER_TEMPLATE} type [modal-actions-render-template]`,
() => {
const templateModalKey = 'somePageName';
-
const expectedAction = {
type: constants.RENDER_TEMPLATE,
key: util.encodeId(templateModalKey),
@@ -83,11 +84,73 @@ describe('Modal open actions', () => {
);
},
);
+
+ test(`onClose action returns ${constants.CLOSE} as type [modal-actions-close]`, () => {
+ const expectedAction = {
+ type: constants.CLOSE,
+ };
+ expect(onClose()).toEqual(expectedAction);
+ });
+
+ test(`toggleAboutModal returns ${constants.OPEN_ABOUT} when isOpen is true [modal-actions-open-about]`, () => {
+ const expectedAction = {
+ type: constants.OPEN_ABOUT,
+ };
+ expect(toggleAboutModal(true)).toEqual(expectedAction);
+ });
+
+ test(`toggleAboutModal returns ${constants.CLOSE_ABOUT} when isOpen is false [modal-actions-close-about]`, () => {
+ const expectedAction = {
+ type: constants.CLOSE_ABOUT,
+ };
+ expect(toggleAboutModal(false)).toEqual(expectedAction);
+ });
});
+
+describe('toggleCustomContent actions', () => {
+ test(`dispatches ${constants.CLOSE} when modal is open with same key [modal-actions-toggle-custom-close]`, () => {
+ const key = 'CUSTOM_MODAL_KEY';
+ const params = { headerText: constants.TEST_HEADER };
+ const store = mockStore({ modal: { id: key, isOpen: true } });
+ store.dispatch(toggleCustomContent(key, params));
+ expect(store.getActions()).toEqual([{ type: constants.CLOSE }]);
+ });
+
+ test(`dispatches ${constants.OPEN_CUSTOM} when modal is closed [modal-actions-toggle-custom-open]`, () => {
+ const key = 'CUSTOM_MODAL_KEY';
+ const params = { headerText: constants.TEST_HEADER };
+ const store = mockStore({ modal: { id: key, isOpen: false } });
+ store.dispatch(toggleCustomContent(key, params));
+ expect(store.getActions()).toEqual([
+ {
+ type: constants.OPEN_CUSTOM,
+ key,
+ customProps: params,
+ },
+ ]);
+ });
+
+ test(`dispatches ${constants.OPEN_CUSTOM} when modal key differs [modal-actions-toggle-custom-different-key]`, () => {
+ const key = 'CUSTOM_MODAL_KEY';
+ const differentKey = 'DIFFERENT_MODAL_KEY';
+ const params = { headerText: constants.TEST_HEADER };
+ const store = mockStore({ modal: { id: differentKey, isOpen: true } });
+ store.dispatch(toggleCustomContent(key, params));
+ expect(store.getActions()).toEqual([
+ {
+ type: constants.OPEN_CUSTOM,
+ key,
+ customProps: params,
+ },
+ ]);
+ });
+});
+
describe('Template fetching', () => {
beforeEach(() => {
fetch.resetMocks();
});
+
test('triggers start and success action types [modal-actions-success]', () => {
const loc = 'mock/';
fetch.mockResponseOnce(constants.ABOUT_MOCK_RESPONSE);
@@ -105,6 +168,7 @@ describe('Template fetching', () => {
expect(store.getActions()).toEqual(expectedActions);
});
});
+
test(`creates ${constants.TEMPLATE_REQUEST_FAILURE} Action [modal-actions-failure]`, () => {
const loc = 'mock/';
fetch.mockRejectOnce(ERROR_MESSAGE);
diff --git a/web/js/modules/modal/reducers.test.js b/web/js/modules/modal/reducers.test.js
index 2b4416ef6..4b002b9ba 100644
--- a/web/js/modules/modal/reducers.test.js
+++ b/web/js/modules/modal/reducers.test.js
@@ -1,12 +1,13 @@
import { assign as lodashAssign } from 'lodash';
import * as constants from './constants';
-import { modalReducer, modalState } from './reducers';
+import { modalReducer, modalState, modalAboutReducer } from './reducers';
import util from '../../util/util';
describe('main modalReducer', () => {
test('should return the initial state', () => {
expect(modalReducer(undefined, {})).toEqual(modalState);
});
+
test(`${constants.TOGGLE}action type should toggle open value [modal-reducer-toggle]`, () => {
const modalToggledOpenObj = { isOpen: true };
expect(
@@ -15,6 +16,16 @@ describe('main modalReducer', () => {
}),
).toEqual(modalToggledOpenObj);
});
+
+ test(`${constants.TOGGLE} action type should toggle isOpen from true to false [modal-reducer-toggle-close]`, () => {
+ const openState = lodashAssign({}, modalState, { isOpen: true });
+ expect(
+ modalReducer(openState, {
+ type: constants.TOGGLE,
+ }),
+ ).toEqual(lodashAssign({}, openState, { isOpen: false }));
+ });
+
test(
`${constants.OPEN_BASIC}action type should update various modal props [modal-reducer-open]`,
() => {
@@ -27,7 +38,6 @@ describe('main modalReducer', () => {
customProps: {},
template: null,
};
-
expect(
modalReducer([], {
type: constants.OPEN_BASIC,
@@ -38,6 +48,37 @@ describe('main modalReducer', () => {
).toEqual(basicOpenModalObject);
},
);
+
+ test(
+ `${constants.OPEN_BASIC} action type should default to empty strings when headerText and bodyText are omitted [modal-reducer-open-basic-defaults]`,
+ () => {
+ const key = util.encodeId('__BASIC_MODAL__');
+ const result = modalReducer(modalState, {
+ type: constants.OPEN_BASIC,
+ key,
+ });
+ expect(result.headerText).toBe('');
+ expect(result.bodyText).toBe('');
+ expect(result.isOpen).toBe(true);
+ expect(result.isCustom).toBe(false);
+ },
+ );
+
+ test(
+ `${constants.OPEN_BASIC} action type should toggle isOpen when same key is already open [modal-reducer-open-basic-same-key]`,
+ () => {
+ const key = util.encodeId(`__BASIC_MODAL__${constants.TEST_HEADER}`);
+ const openState = lodashAssign({}, modalState, { key, isOpen: true });
+ const result = modalReducer(openState, {
+ type: constants.OPEN_BASIC,
+ key,
+ headerText: constants.TEST_HEADER,
+ bodyText: constants.TEST_BODY,
+ });
+ expect(result.isOpen).toBe(false);
+ },
+ );
+
test(
`${constants.OPEN_CUSTOM} action type should update various modal props [modal-reducer-open-custom]`,
() => {
@@ -58,9 +99,35 @@ describe('main modalReducer', () => {
).toEqual(modalCustomObject);
},
);
+
+ test(
+ `${constants.OPEN_CUSTOM} action type should default to empty strings when headerText and bodyText are omitted [modal-reducer-open-custom-defaults]`,
+ () => {
+ const result = modalReducer(modalState, {
+ type: constants.OPEN_CUSTOM,
+ key: constants.TEST_KEY,
+ customProps: {},
+ });
+ expect(result.headerText).toBe('');
+ expect(result.bodyText).toBe('');
+ },
+ );
+
+ test(
+ `${constants.OPEN_CUSTOM} action type should toggle isOpen when same key is already open [modal-reducer-open-custom-same-key]`,
+ () => {
+ const openState = lodashAssign({}, modalState, { key: constants.TEST_KEY, isOpen: true });
+ const result = modalReducer(openState, {
+ type: constants.OPEN_CUSTOM,
+ key: constants.TEST_KEY,
+ customProps: {},
+ });
+ expect(result.isOpen).toBe(false);
+ },
+ );
+
test(
- `${constants.RENDER_TEMPLATE
- } action type should update various modal props [modal-reducer-render-template]`,
+ `${constants.RENDER_TEMPLATE} action type should update various modal props [modal-reducer-render-template]`,
() => {
const template = '<html>';
const modalCustomObject = lodashAssign({}, modalState, {
@@ -80,4 +147,78 @@ describe('main modalReducer', () => {
).toEqual(modalCustomObject);
},
);
+
+ test(
+ `${constants.RENDER_TEMPLATE} action type should default headerText to empty string when omitted [modal-reducer-render-template-defaults]`,
+ () => {
+ const template = '<html>';
+ const result = modalReducer(modalState, {
+ type: constants.RENDER_TEMPLATE,
+ key: util.encodeId(constants.TEST_KEY),
+ template,
+ });
+ expect(result.headerText).toBe('');
+ expect(result.bodyText).toBe('');
+ expect(result.isCustom).toBe(false);
+ expect(result.template).toBe(template);
+ },
+ );
+
+ test(
+ `${constants.RENDER_TEMPLATE} action type should toggle isOpen when same key is already open [modal-reducer-render-template-same-key]`,
+ () => {
+ const key = util.encodeId(constants.TEST_KEY);
+ const openState = lodashAssign({}, modalState, { key, isOpen: true });
+ const result = modalReducer(openState, {
+ type: constants.RENDER_TEMPLATE,
+ key,
+ headerText: constants.TEST_HEADER,
+ template: '<html>',
+ });
+ expect(result.isOpen).toBe(false);
+ },
+ );
+
+ test(
+ `${constants.CLOSE} action type should set isOpen to false [modal-reducer-close]`,
+ () => {
+ const openState = lodashAssign({}, modalState, { isOpen: true });
+ expect(
+ modalReducer(openState, {
+ type: constants.CLOSE,
+ }),
+ ).toEqual(lodashAssign({}, openState, { isOpen: false }));
+ },
+ );
+
+ test('unknown action type should return current state [modal-reducer-default]', () => {
+ expect(
+ modalReducer(modalState, { type: 'UNKNOWN_ACTION' }),
+ ).toEqual(modalState);
+ });
+});
+
+describe('modalAboutReducer', () => {
+ test('should return the initial state [modal-about-reducer-initial]', () => {
+ expect(modalAboutReducer(undefined, {})).toEqual({ isOpen: false });
+ });
+
+ test(`${constants.OPEN_ABOUT} action type should set isOpen to true [modal-about-reducer-open]`, () => {
+ expect(
+ modalAboutReducer({ isOpen: false }, { type: constants.OPEN_ABOUT }),
+ ).toEqual({ isOpen: true });
+ });
+
+ test(`${constants.CLOSE_ABOUT} action type should set isOpen to false [modal-about-reducer-close]`, () => {
+ expect(
+ modalAboutReducer({ isOpen: true }, { type: constants.CLOSE_ABOUT }),
+ ).toEqual({ isOpen: false });
+ });
+
+ test('unknown action type should return current state [modal-about-reducer-default]', () => {
+ const currentState = { isOpen: true };
+ expect(
+ modalAboutReducer(currentState, { type: 'UNKNOWN_ACTION' }),
+ ).toEqual(currentState);
+ });
});
diff --git a/web/js/modules/natural-events/actions.test.js b/web/js/modules/natural-events/actions.test.js
index 22bc698b0..f8d7ea543 100644
--- a/web/js/modules/natural-events/actions.test.js
+++ b/web/js/modules/natural-events/actions.test.js
@@ -1,3 +1,284 @@
-test('actions module test', () => {
+import {
+ requestEvents,
+ requestSources,
+ selectEvent,
+ deselectEvent,
+ setEventsFilter,
+ highlightEvent,
+ unHighlightEvent,
+ selected,
+} from './actions';
+jest.mock('./constants', () => ({
+ REQUEST_EVENTS: 'REQUEST_EVENTS',
+ REQUEST_SOURCES: 'REQUEST_SOURCES',
+ SELECT_EVENT: 'SELECT_EVENT',
+ DESELECT_EVENT: 'DESELECT_EVENT',
+ SET_EVENTS_FILTER: 'SET_EVENTS_FILTER',
+ FINISHED_ANIMATING_TO_EVENT: 'FINISHED_ANIMATING_TO_EVENT',
+ HIGHLIGHT_EVENT: 'HIGHLIGHT_EVENT',
+ UNHIGHLIGHT_EVENT: 'UNHIGHLIGHT_EVENT',
+}));
+
+jest.mock('./util', () => ({
+ getEventsRequestURL: jest.fn(() => 'http://mock-url/events'),
+}));
+
+jest.mock('../core/actions', () => ({
+ requestAction: jest.fn(),
+}));
+
+import { getEventsRequestURL } from './util';
+import { requestAction } from '../core/actions';
+
+describe('requestEvents', () => {
+ it('returns a thunk', () => {
+ const thunk = requestEvents();
+ expect(typeof thunk).toBe('function');
+ });
+
+ it('calls getEventsRequestURL with state', () => {
+ const mockState = { events: {} };
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => mockState);
+ requestEvents()(dispatch, getState);
+ expect(getEventsRequestURL).toHaveBeenCalledWith(mockState);
+ });
+
+ it('calls requestAction with correct arguments', () => {
+ const mockState = { events: {} };
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => mockState);
+ requestEvents()(dispatch, getState);
+ expect(requestAction).toHaveBeenCalledWith(
+ dispatch,
+ 'REQUEST_EVENTS',
+ 'http://mock-url/events',
+ 'application/json',
+ );
+ });
+});
+
+describe('requestSources', () => {
+ beforeEach(() => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {});
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('returns a thunk', () => {
+ const thunk = requestSources();
+ expect(typeof thunk).toBe('function');
+ });
+
+ it('calls requestAction with the correct sources URL when no mock', () => {
+ const mockState = {
+ config: {
+ features: { naturalEvents: { host: 'http://mock-host' } },
+ parameters: {},
+ },
+ };
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => mockState);
+ requestSources()(dispatch, getState);
+ expect(requestAction).toHaveBeenCalledWith(
+ dispatch,
+ 'REQUEST_SOURCES',
+ 'http://mock-host/sources',
+ 'application/json',
+ );
+ });
+
+ it('uses mock sources URL and warns when mockSources is set', () => {
+ const mockState = {
+ config: {
+ features: { naturalEvents: { host: 'http://mock-host' } },
+ parameters: { mockSources: 'test-mock' },
+ },
+ };
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => mockState);
+ requestSources()(dispatch, getState);
+ expect(console.warn).toHaveBeenCalledWith('Using mock sources data: test-mock');
+ expect(requestAction).toHaveBeenCalledWith(
+ dispatch,
+ 'REQUEST_SOURCES',
+ 'mock/sources_data.json-test-mock',
+ 'application/json',
+ );
+ });
+
+ it('catches and logs errors thrown by requestAction', () => {
+ requestAction.mockImplementationOnce(() => {
+ throw new Error('network error');
+ });
+ const mockState = {
+ config: {
+ features: { naturalEvents: { host: 'http://mock-host' } },
+ parameters: {},
+ },
+ };
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => mockState);
+ expect(() => requestSources()(dispatch, getState)).not.toThrow();
+ expect(console.error).toHaveBeenCalled();
+ });
+});
+
+describe('selectEvent', () => {
+ it('returns the correct type', () => {
+ const result = selectEvent('event-1', '2023-01-01');
+ expect(result.type).toBe('SELECT_EVENT');
+ });
+
+ it('returns the correct id', () => {
+ const result = selectEvent('event-1', '2023-01-01');
+ expect(result.id).toBe('event-1');
+ });
+
+ it('returns the correct date', () => {
+ const result = selectEvent('event-1', '2023-01-01');
+ expect(result.date).toBe('2023-01-01');
+ });
+
+ it('returns undefined id and date when no args passed', () => {
+ const result = selectEvent();
+ expect(result.id).toBeUndefined();
+ expect(result.date).toBeUndefined();
+ });
+});
+
+describe('deselectEvent', () => {
+ it('returns the correct type', () => {
+ const result = deselectEvent('event-1', '2023-01-01');
+ expect(result.type).toBe('DESELECT_EVENT');
+ });
+
+ it('does not include id or date in the returned object', () => {
+ const result = deselectEvent('event-1', '2023-01-01');
+ expect(result.id).toBeUndefined();
+ expect(result.date).toBeUndefined();
+ });
+});
+
+describe('setEventsFilter', () => {
+ const baseState = {
+ events: {
+ selectedCategories: ['wildfires'],
+ selectedDates: { start: '2023-01-01', end: '2023-01-31' },
+ showAll: false,
+ },
+ };
+
+ it('returns a thunk', () => {
+ const thunk = setEventsFilter([], '2023-01-01', '2023-01-31', false, false);
+ expect(typeof thunk).toBe('function');
+ });
+
+ it('dispatches SET_EVENTS_FILTER with correct payload', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => baseState);
+ setEventsFilter(['wildfires'], '2023-01-01', '2023-01-31', false, true)(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith({
+ type: 'SET_EVENTS_FILTER',
+ categories: ['wildfires'],
+ start: '2023-01-01',
+ end: '2023-01-31',
+ showAll: false,
+ showAllTracks: true,
+ });
+ });
+
+ it('dispatches requestEvents when showAll is false', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => baseState);
+ setEventsFilter(['wildfires'], '2023-01-01', '2023-01-31', false, false)(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it('dispatches requestEvents when categories have changed', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => baseState);
+ setEventsFilter(['floods'], '2023-01-01', '2023-01-31', true, false)(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it('dispatches requestEvents when dates have changed', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => baseState);
+ setEventsFilter(['wildfires'], '2023-02-01', '2023-02-28', true, false)(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it('dispatches requestEvents when showAll changes from false to true', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => baseState);
+ setEventsFilter(['wildfires'], '2023-01-01', '2023-01-31', true, false)(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not dispatch requestEvents when showAll is true and nothing has changed', () => {
+ const unchangedState = {
+ events: {
+ selectedCategories: ['wildfires'],
+ selectedDates: { start: '2023-01-01', end: '2023-01-31' },
+ showAll: true,
+ },
+ };
+ const dispatch = jest.fn();
+ const getState = jest.fn(() => unchangedState);
+ setEventsFilter(['wildfires'], '2023-01-01', '2023-01-31', true, false)(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('highlightEvent', () => {
+ it('returns the correct type', () => {
+ const result = highlightEvent('event-1', '2023-01-01');
+ expect(result.type).toBe('HIGHLIGHT_EVENT');
+ });
+
+ it('returns the correct id', () => {
+ const result = highlightEvent('event-1', '2023-01-01');
+ expect(result.id).toBe('event-1');
+ });
+
+ it('returns the correct date', () => {
+ const result = highlightEvent('event-1', '2023-01-01');
+ expect(result.date).toBe('2023-01-01');
+ });
+
+ it('returns undefined id and date when no args passed', () => {
+ const result = highlightEvent();
+ expect(result.id).toBeUndefined();
+ expect(result.date).toBeUndefined();
+ });
+});
+
+describe('unHighlightEvent', () => {
+ it('returns the correct type', () => {
+ const result = unHighlightEvent('event-1', '2023-01-01');
+ expect(result.type).toBe('UNHIGHLIGHT_EVENT');
+ });
+
+ it('does not include id or date in the returned object', () => {
+ const result = unHighlightEvent('event-1', '2023-01-01');
+ expect(result.id).toBeUndefined();
+ expect(result.date).toBeUndefined();
+ });
+});
+
+describe('selected', () => {
+ it('returns the correct type', () => {
+ const result = selected();
+ expect(result.type).toBe('FINISHED_ANIMATING_TO_EVENT');
+ });
+
+ it('returns only the type property', () => {
+ const result = selected();
+ expect(Object.keys(result)).toEqual(['type']);
+ });
});
diff --git a/web/js/modules/natural-events/reducers.test.js b/web/js/modules/natural-events/reducers.test.js
index 04cce6a78..8490d3812 100644
--- a/web/js/modules/natural-events/reducers.test.js
+++ b/web/js/modules/natural-events/reducers.test.js
@@ -1,3 +1,372 @@
-test('reducers module test', () => {
+import {
+ eventsReducer,
+ eventsRequestReducer,
+ eventRequestResponse,
+ requestedEvents,
+ requestedEventSources,
+ getInitialEventsState,
+ defaultRequestState,
+} from './reducers';
+jest.mock('./constants', () => ({
+ REQUEST_EVENTS: 'REQUEST_EVENTS',
+ REQUEST_SOURCES: 'REQUEST_SOURCES',
+ SELECT_EVENT: 'SELECT_EVENT',
+ DESELECT_EVENT: 'DESELECT_EVENT',
+ SET_EVENTS_FILTER: 'SET_EVENTS_FILTER',
+ FINISHED_ANIMATING_TO_EVENT: 'FINISHED_ANIMATING_TO_EVENT',
+ HIGHLIGHT_EVENT: 'HIGHLIGHT_EVENT',
+ UNHIGHLIGHT_EVENT: 'UNHIGHLIGHT_EVENT',
+}));
+
+jest.mock('../sidebar/constants', () => ({
+ CHANGE_TAB: 'CHANGE_TAB',
+}));
+
+const defaultEventsState = {
+ selected: {
+ id: '',
+ date: null,
+ eventObject: null,
+ geometryForDate: null,
+ },
+ highlighted: {
+ id: '',
+ date: null,
+ },
+ active: false,
+ showAll: true,
+ showAllTracks: false,
+ isAnimatingToEvent: false,
+ selectedCategories: [],
+ selectedDates: {
+ start: null,
+ end: null,
+ },
+};
+
+describe('defaultRequestState', () => {
+ it('has correct default shape', () => {
+ expect(defaultRequestState).toEqual({
+ isLoading: false,
+ error: null,
+ response: null,
+ type: null,
+ ignore: [],
+ });
+ });
+});
+
+describe('eventRequestResponse', () => {
+ it('returns the default request state when called with no args', () => {
+ expect(eventRequestResponse()).toEqual(defaultRequestState);
+ });
+
+ it('merges provided props over defaults', () => {
+ const result = eventRequestResponse({ isLoading: true, error: 'oops' });
+ expect(result.isLoading).toBe(true);
+ expect(result.error).toBe('oops');
+ expect(result.response).toBeNull();
+ });
+});
+
+describe('eventsReducer', () => {
+ it('returns the default state when no state is provided', () => {
+ const state = eventsReducer(undefined, { type: '@@INIT' });
+ expect(state).toEqual(defaultEventsState);
+ });
+
+ it('returns the same state for an unknown action', () => {
+ const state = eventsReducer(defaultEventsState, { type: 'UNKNOWN' });
+ expect(state).toBe(defaultEventsState);
+ });
+
+ describe('SELECT_EVENT', () => {
+ it('sets selected id and date', () => {
+ const action = { type: 'SELECT_EVENT', id: 'event-1', date: '2023-01-01' };
+ const state = eventsReducer(defaultEventsState, action);
+ expect(state.selected.id).toBe('event-1');
+ expect(state.selected.date).toBe('2023-01-01');
+ });
+
+ it('sets isAnimatingToEvent to true', () => {
+ const action = { type: 'SELECT_EVENT', id: 'event-1', date: '2023-01-01' };
+ const state = eventsReducer(defaultEventsState, action);
+ expect(state.isAnimatingToEvent).toBe(true);
+ });
+ });
+
+ describe('DESELECT_EVENT', () => {
+ it('resets selected to default', () => {
+ const preState = {
+ ...defaultEventsState,
+ selected: { id: 'event-1', date: '2023-01-01' },
+ };
+ const state = eventsReducer(preState, { type: 'DESELECT_EVENT' });
+ expect(state.selected).toEqual({
+ id: '',
+ date: null,
+ eventObject: null,
+ geometryForDate: null,
+ });
+ });
+ });
+
+ describe('SET_EVENTS_FILTER', () => {
+ it('sets showAll, showAllTracks, selectedCategories, and selectedDates', () => {
+ const action = {
+ type: 'SET_EVENTS_FILTER',
+ showAll: false,
+ showAllTracks: true,
+ categories: ['wildfires'],
+ start: '2023-01-01',
+ end: '2023-01-31',
+ };
+ const state = eventsReducer(defaultEventsState, action);
+ expect(state.showAll).toBe(false);
+ expect(state.showAllTracks).toBe(true);
+ expect(state.selectedCategories).toEqual(['wildfires']);
+ expect(state.selectedDates).toEqual({ start: '2023-01-01', end: '2023-01-31' });
+ });
+ });
+
+ describe('CHANGE_TAB', () => {
+ it('sets active to true when activeTab is events', () => {
+ const action = { type: 'CHANGE_TAB', activeTab: 'events' };
+ const state = eventsReducer(defaultEventsState, action);
+ expect(state.active).toBe(true);
+ });
+
+ it('sets active to false when activeTab is not events', () => {
+ const preState = { ...defaultEventsState, active: true };
+ const action = { type: 'CHANGE_TAB', activeTab: 'layers' };
+ const state = eventsReducer(preState, action);
+ expect(state.active).toBe(false);
+ });
+
+ it('returns the same state reference when active does not change', () => {
+ const preState = { ...defaultEventsState, active: false };
+ const action = { type: 'CHANGE_TAB', activeTab: 'layers' };
+ const state = eventsReducer(preState, action);
+ expect(state).toBe(preState);
+ });
+ });
+
+ describe('FINISHED_ANIMATING_TO_EVENT', () => {
+ it('sets isAnimatingToEvent to false', () => {
+ const preState = { ...defaultEventsState, isAnimatingToEvent: true };
+ const state = eventsReducer(preState, { type: 'FINISHED_ANIMATING_TO_EVENT' });
+ expect(state.isAnimatingToEvent).toBe(false);
+ });
+ });
+
+ describe('HIGHLIGHT_EVENT', () => {
+ it('sets highlighted id and date', () => {
+ const action = { type: 'HIGHLIGHT_EVENT', id: 'event-2', date: '2023-06-15' };
+ const state = eventsReducer(defaultEventsState, action);
+ expect(state.highlighted.id).toBe('event-2');
+ expect(state.highlighted.date).toBe('2023-06-15');
+ });
+ });
+
+ describe('UNHIGHLIGHT_EVENT', () => {
+ it('resets highlighted to default', () => {
+ const preState = {
+ ...defaultEventsState,
+ highlighted: { id: 'event-2', date: '2023-06-15' },
+ };
+ const state = eventsReducer(preState, { type: 'UNHIGHLIGHT_EVENT' });
+ expect(state.highlighted).toEqual({ id: '', date: null });
+ });
+ });
+});
+
+describe('eventsRequestReducer', () => {
+ describe('REQUEST_EVENTS_START', () => {
+ it('sets isLoading to true and clears response', () => {
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, { type: 'REQUEST_EVENTS_START' });
+ expect(state.isLoading).toBe(true);
+ expect(state.response).toBeNull();
+ });
+ });
+
+ describe('REQUEST_EVENTS_SUCCESS', () => {
+ it('returns sorted events on success', () => {
+ const events = [
+ { id: 'e1', geometry: [{ date: '2023-01-01T00:00:00Z' }] },
+ { id: 'e2', geometry: [{ date: '2023-06-01T00:00:00Z' }] },
+ ];
+ const action = { type: 'REQUEST_EVENTS_SUCCESS', response: { events } };
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, action);
+ expect(state.isLoading).toBe(false);
+ expect(Array.isArray(state.response)).toBe(true);
+ expect(state.response[0].id).toBe('e2');
+ expect(state.response[1].id).toBe('e1');
+ });
+
+ it('returns empty array when events payload is empty', () => {
+ const action = { type: 'REQUEST_EVENTS_SUCCESS', response: { events: [] } };
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, action);
+ expect(state.response).toEqual([]);
+ });
+
+ it('returns empty array when events payload is undefined', () => {
+ const action = { type: 'REQUEST_EVENTS_SUCCESS', response: {} };
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, action);
+ expect(state.response).toEqual([]);
+ });
+
+ it('deduplicates geometry entries with the same date', () => {
+ const events = [
+ {
+ id: 'e1',
+ geometry: [
+ { date: '2023-01-01T00:00:00Z' },
+ { date: '2023-01-01T12:00:00Z' },
+ ],
+ },
+ ];
+ const action = { type: 'REQUEST_EVENTS_SUCCESS', response: { events } };
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, action);
+ expect(state.response[0].geometry).toHaveLength(1);
+ });
+
+ it('handles events with non-array geometry', () => {
+ const events = [{ id: 'e1', geometry: null }];
+ const action = { type: 'REQUEST_EVENTS_SUCCESS', response: { events } };
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, action);
+ expect(state.response[0].geometry).toEqual([]);
+ });
+ });
+
+ describe('REQUEST_EVENTS_FAILURE', () => {
+ it('sets error and clears response', () => {
+ const action = { type: 'REQUEST_EVENTS_FAILURE', error: 'fetch failed' };
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, action);
+ expect(state.error).toBe('fetch failed');
+ expect(state.response).toBeNull();
+ expect(state.isLoading).toBe(false);
+ });
+ });
+
+ describe('REQUEST_SOURCES_START', () => {
+ it('sets isLoading to true and clears response', () => {
+ const state = eventsRequestReducer('REQUEST_SOURCES', {}, { type: 'REQUEST_SOURCES_START' });
+ expect(state.isLoading).toBe(true);
+ expect(state.response).toBeNull();
+ });
+ });
+
+ describe('REQUEST_SOURCES_SUCCESS', () => {
+ it('returns sources payload on success', () => {
+ const sources = [{ id: 's1' }, { id: 's2' }];
+ const action = { type: 'REQUEST_SOURCES_SUCCESS', response: { sources } };
+ const state = eventsRequestReducer('REQUEST_SOURCES', {}, action);
+ expect(state.isLoading).toBe(false);
+ expect(state.response).toEqual(sources);
+ });
+
+ it('returns null when sources payload is missing', () => {
+ const action = { type: 'REQUEST_SOURCES_SUCCESS', response: {} };
+ const state = eventsRequestReducer('REQUEST_SOURCES', {}, action);
+ expect(state.response).toBeNull();
+ });
+ });
+
+ describe('REQUEST_SOURCES_FAILURE', () => {
+ it('sets error and clears response', () => {
+ const action = { type: 'REQUEST_SOURCES_FAILURE', error: 'sources failed' };
+ const state = eventsRequestReducer('REQUEST_SOURCES', {}, action);
+ expect(state.error).toBe('sources failed');
+ expect(state.response).toBeNull();
+ expect(state.isLoading).toBe(false);
+ });
+ });
+
+ describe('default case', () => {
+ it('returns default request state for unknown action', () => {
+ const state = eventsRequestReducer('REQUEST_EVENTS', {}, { type: 'UNKNOWN' });
+ expect(state).toEqual(defaultRequestState);
+ });
+ });
+});
+
+describe('requestedEvents', () => {
+ it('returns default state for unknown action', () => {
+ const state = requestedEvents(undefined, { type: 'UNKNOWN' });
+ expect(state).toEqual(defaultRequestState);
+ });
+
+ it('handles REQUEST_EVENTS_START', () => {
+ const state = requestedEvents({}, { type: 'REQUEST_EVENTS_START' });
+ expect(state.isLoading).toBe(true);
+ });
+
+ it('handles REQUEST_EVENTS_SUCCESS', () => {
+ const events = [{ id: 'e1', geometry: [{ date: '2023-01-01T00:00:00Z' }] }];
+ const state = requestedEvents({}, { type: 'REQUEST_EVENTS_SUCCESS', response: { events } });
+ expect(state.isLoading).toBe(false);
+ expect(Array.isArray(state.response)).toBe(true);
+ });
+
+ it('handles REQUEST_EVENTS_FAILURE', () => {
+ const state = requestedEvents({}, { type: 'REQUEST_EVENTS_FAILURE', error: 'err' });
+ expect(state.error).toBe('err');
+ });
+});
+
+describe('requestedEventSources', () => {
+ it('returns default state for unknown action', () => {
+ const state = requestedEventSources(undefined, { type: 'UNKNOWN' });
+ expect(state).toEqual(defaultRequestState);
+ });
+
+ it('handles REQUEST_SOURCES_START', () => {
+ const state = requestedEventSources({}, { type: 'REQUEST_SOURCES_START' });
+ expect(state.isLoading).toBe(true);
+ });
+
+ it('handles REQUEST_SOURCES_SUCCESS', () => {
+ const sources = [{ id: 's1' }];
+ const state = requestedEventSources({}, { type: 'REQUEST_SOURCES_SUCCESS', response: { sources } });
+ expect(state.isLoading).toBe(false);
+ expect(state.response).toEqual(sources);
+ });
+
+ it('handles REQUEST_SOURCES_FAILURE', () => {
+ const state = requestedEventSources({}, { type: 'REQUEST_SOURCES_FAILURE', error: 'src err' });
+ expect(state.error).toBe('src err');
+ });
+});
+
+describe('getInitialEventsState', () => {
+ const config = {
+ initialDate: '2023-06-01',
+ naturalEvents: {
+ categories: ['wildfires', 'floods'],
+ },
+ };
+
+ it('returns selectedCategories from config', () => {
+ const state = getInitialEventsState(config);
+ expect(state.selectedCategories).toEqual(['wildfires', 'floods']);
+ });
+
+ it('returns correct endDate based on initialDate', () => {
+ const state = getInitialEventsState(config);
+ expect(state.selectedDates.end).toBe('2023-06-01');
+ });
+
+ it('returns correct startDate 120 days before initialDate', () => {
+ const state = getInitialEventsState(config);
+ expect(state.selectedDates.start).toBe('2023-02-01');
+ });
+
+ it('spreads the default eventsReducerState properties', () => {
+ const state = getInitialEventsState(config);
+ expect(state.active).toBe(false);
+ expect(state.showAll).toBe(true);
+ expect(state.isAnimatingToEvent).toBe(false);
+ expect(state.highlighted).toEqual({ id: '', date: null });
+ });
});
diff --git a/web/js/modules/natural-events/selectors.test.js b/web/js/modules/natural-events/selectors.test.js
index c4e1cdccf..b4cac457a 100644
--- a/web/js/modules/natural-events/selectors.test.js
+++ b/web/js/modules/natural-events/selectors.test.js
@@ -1,3 +1,230 @@
-test('selectors module test', () => {
+import { getFilteredEvents } from './selectors';
+jest.mock('./util', () => ({
+ validateGeometryCoords: jest.fn(),
+}));
+
+import { validateGeometryCoords } from './util';
+
+const buildState = ({ selectedCategories, response, proj } = {}) => ({
+ events: {
+ selectedCategories: selectedCategories || [],
+ },
+ requestedEvents: {
+ response: response !== undefined ? response : [],
+ },
+ proj: {
+ selected: proj || 'geographic',
+ },
+});
+
+describe('getFilteredEvents', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('returns an empty array when response is null', () => {
+ const state = buildState({ response: null });
+ const result = getFilteredEvents(state);
+ expect(result).toEqual([]);
+ });
+
+ it('returns an empty array when response is undefined', () => {
+ const state = buildState({ response: undefined });
+ const result = getFilteredEvents(state);
+ expect(result).toEqual([]);
+ });
+
+ it('returns an empty array when response is an empty array', () => {
+ validateGeometryCoords.mockReturnValue(true);
+ const state = buildState({ response: [] });
+ const result = getFilteredEvents(state);
+ expect(result).toEqual([]);
+ });
+
+ it('filters out events where all geometries fail validation', () => {
+ validateGeometryCoords.mockReturnValue(false);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [0, 0] }],
+ },
+ ],
+ });
+ const result = getFilteredEvents(state);
+ expect(result).toEqual([]);
+ });
+
+ it('includes events where at least one geometry passes validation', () => {
+ validateGeometryCoords
+ .mockReturnValueOnce(false)
+ .mockReturnValueOnce(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [0, 0] }, { coordinates: [10, 10] }],
+ },
+ ],
+ });
+ const result = getFilteredEvents(state);
+ expect(result).toHaveLength(1);
+ expect(result[0].geometry).toHaveLength(1);
+ });
+
+ it('only keeps geometries that pass validation', () => {
+ validateGeometryCoords
+ .mockReturnValueOnce(true)
+ .mockReturnValueOnce(false)
+ .mockReturnValueOnce(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }],
+ geometry: [
+ { coordinates: [0, 0] },
+ { coordinates: [10, 10] },
+ { coordinates: [20, 20] },
+ ],
+ },
+ ],
+ });
+ const result = getFilteredEvents(state);
+ expect(result[0].geometry).toHaveLength(2);
+ });
+
+ it('filters out categories not present in activeCategories', () => {
+ validateGeometryCoords.mockReturnValue(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }, { id: 'floods' }],
+ geometry: [{ coordinates: [0, 0] }],
+ },
+ ],
+ });
+ const result = getFilteredEvents(state);
+ expect(result[0].categories).toEqual([{ id: 'wildfires' }]);
+ });
+
+ it('keeps all categories that match activeCategories', () => {
+ validateGeometryCoords.mockReturnValue(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }, { id: 'floods' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }, { id: 'floods' }],
+ geometry: [{ coordinates: [0, 0] }],
+ },
+ ],
+ });
+ const result = getFilteredEvents(state);
+ expect(result[0].categories).toHaveLength(2);
+ });
+
+ it('returns an empty categories array when no categories match', () => {
+ validateGeometryCoords.mockReturnValue(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'volcanoes' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }, { id: 'floods' }],
+ geometry: [{ coordinates: [0, 0] }],
+ },
+ ],
+ });
+ const result = getFilteredEvents(state);
+ expect(result[0].categories).toEqual([]);
+ });
+
+ it('processes multiple events correctly', () => {
+ validateGeometryCoords
+ .mockReturnValueOnce(true)
+ .mockReturnValueOnce(false)
+ .mockReturnValueOnce(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [0, 0] }],
+ },
+ {
+ id: 'e2',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [10, 10] }],
+ },
+ {
+ id: 'e3',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [20, 20] }],
+ },
+ ],
+ });
+ const result = getFilteredEvents(state);
+ expect(result).toHaveLength(2);
+ expect(result.map((e) => e.id)).toEqual(['e1', 'e3']);
+ });
+
+ it('does not mutate the original event objects', () => {
+ validateGeometryCoords.mockReturnValue(true);
+ const originalEvent = {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [0, 0] }],
+ };
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [originalEvent],
+ });
+ getFilteredEvents(state);
+ expect(originalEvent.categories).toHaveLength(1);
+ expect(originalEvent.geometry).toHaveLength(1);
+ });
+
+ it('passes the correct projection to validateGeometryCoords', () => {
+ validateGeometryCoords.mockReturnValue(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [0, 0] }],
+ },
+ ],
+ proj: 'arctic',
+ });
+ getFilteredEvents(state);
+ expect(validateGeometryCoords).toHaveBeenCalledWith({ coordinates: [0, 0] }, 'arctic');
+ });
+
+ it('returns a memoized result when called with the same state', () => {
+ validateGeometryCoords.mockReturnValue(true);
+ const state = buildState({
+ selectedCategories: [{ id: 'wildfires' }],
+ response: [
+ {
+ id: 'e1',
+ categories: [{ id: 'wildfires' }],
+ geometry: [{ coordinates: [0, 0] }],
+ },
+ ],
+ });
+ const result1 = getFilteredEvents(state);
+ const result2 = getFilteredEvents(state);
+ expect(result1).toBe(result2);
+ });
});
diff --git a/web/js/modules/natural-events/util.test.js b/web/js/modules/natural-events/util.test.js
index fefaf6395..7a485cd74 100644
--- a/web/js/modules/natural-events/util.test.js
+++ b/web/js/modules/natural-events/util.test.js
@@ -1,83 +1,520 @@
-import { config } from '@fortawesome/fontawesome-svg-core';
-import { getEventsRequestURL } from './util';
-import fixtures from '../../fixtures';
+import {
+ getEventsRequestURL,
+ parseEvent,
+ serializeEvent,
+ parseEventFilterDates,
+ serializeEventFilterDates,
+ serializeCategories,
+ mapLocationToEventFilterState,
+ toEventDateString,
+ getDefaultEventDate,
+ validateGeometryCoords,
+} from './util';
-let initialState = fixtures.getState();
+jest.mock('ol/extent', () => ({
+ containsCoordinate: jest.fn(),
+}));
-initialState = {
- ...initialState,
- events: {
- ...initialState.events,
- selectedDates: {
- start: '2020-01-01',
- end: '2021-01-01',
+jest.mock('ol/proj', () => ({
+ transform: jest.fn(),
+}));
+
+jest.mock('immutability-helper', () => (state, spec) => {
+ const result = JSON.parse(JSON.stringify(state));
+ if (spec.events) {
+ if (spec.events.selectedCategories?.$set !== undefined) {
+ result.events.selectedCategories = spec.events.selectedCategories.$set;
+ }
+ if (spec.events.selectedDates) {
+ if (spec.events.selectedDates.start?.$set !== undefined) {
+ result.events.selectedDates.start = spec.events.selectedDates.start.$set;
+ }
+ if (spec.events.selectedDates.end?.$set !== undefined) {
+ result.events.selectedDates.end = spec.events.selectedDates.end.$set;
+ }
+ }
+ if (spec.events.showAll?.$set !== undefined) {
+ result.events.showAll = spec.events.showAll.$set;
+ }
+ }
+ return result;
+});
+
+jest.mock('../map/constants', () => ({
+ CRS: {
+ GEOGRAPHIC: 'EPSG:4326',
+ ARCTIC: 'EPSG:3413',
+ ANTARCTIC: 'EPSG:3031',
+ },
+}));
+
+jest.mock('./constants', () => ({
+ LIMIT_EVENT_REQUEST_COUNT: 50,
+}));
+
+jest.mock('../../util/util', () => ({
+ __esModule: true,
+ default: {
+ toQueryString: (params) => {
+ const str = Object.entries(params)
+ .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
+ .join('&');
+ return str ? `?${str}` : '';
},
- selectedCategories: [
- { id: 'snow' },
- { id: 'wildfires' },
- { id: 'manmade' },
- ],
+ now: jest.fn(() => new Date('2023-06-15T00:00:00Z')),
},
-};
+}));
-const mockProj = {
- geographic: { selected: { crs: 'EPSG:4326' } },
- arctic: { selected: { crs: 'EPSG:3413' } },
- antarctic: { selected: { crs: 'EPSG:3031' } },
-};
+import { containsCoordinate } from 'ol/extent';
+import { transform } from 'ol/proj';
-const updateEventState = (newState, state) => ({
- ...state,
+const GEOGRAPHIC_CRS = 'EPSG:4326';
+const ARCTIC_CRS = 'EPSG:3413';
+const ANTARCTIC_CRS = 'EPSG:3031';
+
+const buildState = (overrides = {}) => ({
+ config: {
+ features: {
+ naturalEvents: { host: 'fake.eonet.url/api' },
+ },
+ parameters: {},
+ naturalEvents: {
+ categories: [{ id: 'wildfires' }, { id: 'floods' }, { id: 'snow' }],
+ },
+ },
+ proj: {
+ selected: { crs: GEOGRAPHIC_CRS },
+ },
+ map: {
+ ui: {
+ selected: {
+ getView: () => ({
+ calculateExtent: () => [-15.06, 27.16, 13.32, 56.06],
+ }),
+ },
+ },
+ },
events: {
- ...state.events,
- ...newState,
+ selectedCategories: [{ id: 'snow' }, { id: 'wildfires' }, { id: 'manmade' }],
+ selectedDates: { start: '2020-01-01', end: '2021-01-01' },
+ showAll: true,
},
+ ...overrides,
+});
+
+const updateEventState = (newState, state) => ({
+ ...state,
+ events: { ...state.events, ...newState },
});
const updateProjState = (newState, state) => ({
...state,
- proj: {
- ...newState,
- },
+ proj: { ...newState },
});
-test('Request URL with grographic proj and no bbox [naturalevents-geo-proj-no-bbox]', () => {
- const requestURL = getEventsRequestURL(initialState);
- expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-180%2C90%2C180%2C-90&start=2020-01-01&end=2021-01-01&category=snow%2Cwildfires%2Cmanmade');
+describe('getEventsRequestURL', () => {
+ beforeEach(() => {
+ jest.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ test('Request URL with geographic proj and no bbox [naturalevents-geo-proj-no-bbox]', () => {
+ const state = buildState();
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-180%2C90%2C180%2C-90&start=2020-01-01&end=2021-01-01&category=snow%2Cwildfires%2Cmanmade');
+ });
+
+ test('Request URL with geographic proj and bbox set [naturalevents-geo-proj-bbox]', () => {
+ const state = updateEventState({ showAll: false }, buildState());
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-15.06%2C27.16%2C13.32%2C56.06&start=2020-01-01&end=2021-01-01&category=snow%2Cwildfires%2Cmanmade');
+ });
+
+ test("Request URL doesn't include categories param if none set [naturalevents-categories-param]", () => {
+ const state = updateEventState({ selectedCategories: [] }, buildState());
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-180%2C90%2C180%2C-90&start=2020-01-01&end=2021-01-01');
+ });
+
+ test('Uses mock events if mockEvents is "true" [naturalevents-mock-events]', () => {
+ const state = buildState({
+ config: { ...buildState().config, parameters: { mockEvents: 'true' } },
+ });
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toBe('mock/events_data.json');
+ });
+
+ test('Uses named mock events file when mockEvents is not "true"', () => {
+ const state = buildState({
+ config: { ...buildState().config, parameters: { mockEvents: 'custom-mock' } },
+ });
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toBe('mock/events_data.json-custom-mock');
+ });
+
+ test('Request URL with arctic proj uses default bbox [naturalevents-polar-proj]', () => {
+ let state = updateProjState({ selected: { crs: ARCTIC_CRS } }, buildState());
+ state = updateEventState({ showAll: false, selectedCategories: [{ id: 'snow' }] }, state);
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-180%2C40%2C180%2C90&start=2020-01-01&end=2021-01-01&category=snow');
+ });
+
+ test('Request URL with antarctic proj uses correct default bbox', () => {
+ let state = updateProjState({ selected: { crs: ANTARCTIC_CRS } }, buildState());
+ state = updateEventState({ showAll: false, selectedCategories: [{ id: 'snow' }] }, state);
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-180%2C-90%2C180%2C-40&start=2020-01-01&end=2021-01-01&category=snow');
+ });
+
+ test('Request URL does not include date params when selectedDates are null', () => {
+ const state = updateEventState({ selectedDates: { start: null, end: null } }, buildState());
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).not.toContain('start=');
+ expect(requestURL).not.toContain('end=');
+ });
+
+ test('Uses geographic default bbox when showAll is false but map is not available', () => {
+ const state = {
+ ...buildState(),
+ map: null,
+ events: { ...buildState().events, showAll: false },
+ };
+ const requestURL = getEventsRequestURL(state);
+ expect(requestURL).toContain('bbox=-180%2C90%2C180%2C-90');
+ });
+
+ test('warns when mockEvents is set', () => {
+ const state = buildState({
+ config: { ...buildState().config, parameters: { mockEvents: 'true' } },
+ });
+ getEventsRequestURL(state);
+ expect(console.warn).toHaveBeenCalledWith('Using mock events data: true');
+ });
});
-test('Request URL with grographic proj and bbox set [naturalevents-geo-proj-bbox]', () => {
- const state = updateEventState({ showAll: false }, initialState);
- const requestURL = getEventsRequestURL(state);
- expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-15.06%2C27.16%2C13.32%2C56.06&start=2020-01-01&end=2021-01-01&category=snow%2Cwildfires%2Cmanmade');
+describe('parseEvent', () => {
+ it('parses a valid event string with id and date', () => {
+ const result = parseEvent('EONET_1234,2023-06-15');
+ expect(result.selected.id).toBe('EONET_1234');
+ expect(result.selected.date).toBe('2023-06-15');
+ expect(result.active).toBe(true);
+ expect(result.showAll).toBe(true);
+ });
+
+ it('returns empty id when id does not match EONET pattern', () => {
+ const result = parseEvent('INVALID_ID,2023-06-15');
+ expect(result.selected.id).toBe('');
+ });
+
+ it('returns null date when date does not match date pattern', () => {
+ const result = parseEvent('EONET_1234,not-a-date');
+ expect(result.selected.date).toBeNull();
+ });
+
+ it('returns empty id and null date for bare comma', () => {
+ const result = parseEvent(',');
+ expect(result.selected.id).toBe('');
+ expect(result.selected.date).toBeNull();
+ });
+
+ it('handles only an id with no date', () => {
+ const result = parseEvent('EONET_1234');
+ expect(result.selected.id).toBe('EONET_1234');
+ expect(result.selected.date).toBeNull();
+ });
});
-test('Request URL doesn\'t include categories param if none set [naturalevents-categories-param]', () => {
- const state = updateEventState({ selectedCategories: [] }, initialState);
- const requestURL = getEventsRequestURL(state);
- expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-180%2C90%2C180%2C-90&start=2020-01-01&end=2021-01-01');
+describe('serializeEvent', () => {
+ it('returns id,date when active, id, and date are all set', () => {
+ const state = { active: true, selected: { id: 'EONET_1234', date: '2023-06-15' } };
+ expect(serializeEvent(state)).toBe('EONET_1234,2023-06-15');
+ });
+
+ it('returns just the event id when active and id set but date is missing', () => {
+ const state = { active: true, selected: { id: 'EONET_1234', date: null } };
+ expect(serializeEvent(state)).toBe('EONET_1234');
+ });
+
+ it('returns "true" string when active but no id or date', () => {
+ const state = { active: true, selected: { id: '', date: null } };
+ expect(serializeEvent(state)).toBe('true');
+ });
+
+ it('returns undefined when not active', () => {
+ const state = { active: false, selected: { id: 'EONET_1234', date: '2023-06-15' } };
+ expect(serializeEvent(state)).toBeUndefined();
+ });
+
+ it('returns undefined when active is false and no id or date', () => {
+ const state = { active: false, selected: { id: '', date: null } };
+ expect(serializeEvent(state)).toBeUndefined();
+ });
});
-test('Uses mock events if mockEvents param is present [naturalevents-mock-events]', () => {
- const state = {
- ...initialState,
- config: {
- ...config,
- parameters: {
- mockEvents: 'true',
- },
+describe('parseEventFilterDates', () => {
+ it('parses a valid date range string', () => {
+ const result = parseEventFilterDates('2023-01-01,2023-12-31');
+ expect(result.start).toBe('2023-01-01');
+ expect(result.end).toBe('2023-12-31');
+ });
+
+ it('returns undefined end when only start is provided', () => {
+ const result = parseEventFilterDates('2023-01-01');
+ expect(result.start).toBe('2023-01-01');
+ expect(result.end).toBeUndefined();
+ });
+
+ it('returns both as empty strings when given a bare comma', () => {
+ const result = parseEventFilterDates(',');
+ expect(result.start).toBe('');
+ expect(result.end).toBe('');
+ });
+});
+
+describe('serializeEventFilterDates', () => {
+ it('returns formatted date string when events tab is active and both dates set', () => {
+ const currentItemState = { start: '2023-01-01', end: '2023-12-31' };
+ const state = { events: { active: true } };
+ expect(serializeEventFilterDates(currentItemState, state)).toBe('2023-01-01,2023-12-31');
+ });
+
+ it('returns undefined when events tab is not active', () => {
+ const currentItemState = { start: '2023-01-01', end: '2023-12-31' };
+ const state = { events: { active: false } };
+ expect(serializeEventFilterDates(currentItemState, state)).toBeUndefined();
+ });
+
+ it('returns undefined when start date is missing', () => {
+ const currentItemState = { end: '2023-12-31' };
+ const state = { events: { active: true } };
+ expect(serializeEventFilterDates(currentItemState, state)).toBeUndefined();
+ });
+
+ it('returns undefined when end date is missing', () => {
+ const currentItemState = { start: '2023-01-01' };
+ const state = { events: { active: true } };
+ expect(serializeEventFilterDates(currentItemState, state)).toBeUndefined();
+ });
+});
+
+describe('serializeCategories', () => {
+ const defaultCategories = [{ id: 'wildfires' }, { id: 'floods' }];
+ const baseState = {
+ events: { active: true },
+ config: { naturalEvents: { categories: defaultCategories } },
+ };
+
+ it('returns undefined when using default categories reference', () => {
+ expect(serializeCategories(defaultCategories, baseState)).toBeUndefined();
+ });
+
+ it('returns comma-separated ids when using non-default categories and tab is active', () => {
+ const customCategories = [{ id: 'volcanoes' }, { id: 'snow' }];
+ expect(serializeCategories(customCategories, baseState)).toBe('volcanoes,snow');
+ });
+
+ it('returns undefined when events tab is not active', () => {
+ const customCategories = [{ id: 'volcanoes' }];
+ const state = { ...baseState, events: { active: false } };
+ expect(serializeCategories(customCategories, state)).toBeUndefined();
+ });
+});
+
+describe('mapLocationToEventFilterState', () => {
+ const allCategories = [{ id: 'wildfires' }, { id: 'floods' }, { id: 'snow' }];
+ const baseState = {
+ config: { naturalEvents: { categories: allCategories } },
+ };
+ const stateFromLocation = {
+ events: {
+ selected: { id: '', date: null },
+ selectedDates: { start: '2023-01-01', end: '2023-06-01' },
+ selectedCategories: [],
+ showAll: true,
},
};
- const requestURL = getEventsRequestURL(state);
- expect(requestURL).toBe('mock/events_data.json');
+
+ it('uses all categories when efc param is not set', () => {
+ const result = mapLocationToEventFilterState({}, stateFromLocation, baseState);
+ expect(result.events.selectedCategories).toEqual(allCategories);
+ });
+
+ it('filters categories by efc param', () => {
+ const result = mapLocationToEventFilterState({ efc: 'wildfires,snow' }, stateFromLocation, baseState);
+ expect(result.events.selectedCategories).toEqual([{ id: 'wildfires' }, { id: 'snow' }]);
+ });
+
+ it('returns empty selectedCategories when allCategories is empty', () => {
+ const emptyState = { config: { naturalEvents: { categories: [] } } };
+ const result = mapLocationToEventFilterState({ efc: 'wildfires' }, stateFromLocation, emptyState);
+ expect(result.events.selectedCategories).toEqual([]);
+ });
+
+ it('sets showAll to true when efs is "true"', () => {
+ const result = mapLocationToEventFilterState({ efs: 'true' }, stateFromLocation, baseState);
+ expect(result.events.showAll).toBe(true);
+ });
+
+ it('sets showAll to true when efs param is absent', () => {
+ const result = mapLocationToEventFilterState({}, stateFromLocation, baseState);
+ expect(result.events.showAll).toBe(true);
+ });
+
+ it('sets showAll to false when efs is "false"', () => {
+ const result = mapLocationToEventFilterState({ efs: 'false' }, stateFromLocation, baseState);
+ expect(result.events.showAll).toBe(false);
+ });
+
+ it('uses selected event date for start and end when event is selected and no efd param', () => {
+ const stateWithSelected = {
+ events: {
+ ...stateFromLocation.events,
+ selected: { id: 'EONET_1', date: '2023-03-15' },
+ },
+ };
+ const result = mapLocationToEventFilterState({}, stateWithSelected, baseState);
+ expect(result.events.selectedDates.start).toBe('2023-03-15');
+ expect(result.events.selectedDates.end).toBe('2023-03-15');
+ });
+
+ it('uses stateFromLocation dates when no efd param and no event selected', () => {
+ const result = mapLocationToEventFilterState({}, stateFromLocation, baseState);
+ expect(result.events.selectedDates.start).toBe('2023-01-01');
+ expect(result.events.selectedDates.end).toBe('2023-06-01');
+ });
+});
+
+describe('toEventDateString', () => {
+ it('returns the date portion of an ISO string', () => {
+ const d = new Date('2023-06-15T12:00:00Z');
+ expect(toEventDateString(d)).toBe('2023-06-15');
+ });
+
+ it('handles midnight UTC correctly', () => {
+ const d = new Date('2023-01-01T00:00:00Z');
+ expect(toEventDateString(d)).toBe('2023-01-01');
+ });
});
-test('Request URL with polar proj uses default bbox [naturalevents-polar-proj]', () => {
- let state = updateProjState(mockProj.arctic, initialState);
- state = updateEventState({
- showAll: false,
- selectedCategories: [{ id: 'snow' }],
- }, state);
- const requestURL = getEventsRequestURL(state);
- expect(requestURL).toBe('fake.eonet.url/api/events?status=all&limit=50&bbox=-180%2C40%2C180%2C90&start=2020-01-01&end=2021-01-01&category=snow');
+describe('getDefaultEventDate', () => {
+ it('returns the date of the first geometry when only one geometry exists', () => {
+ const event = {
+ geometry: [{ date: '2023-01-01T00:00:00Z' }],
+ categories: [{ id: 'wildfires' }],
+ };
+ expect(getDefaultEventDate(event)).toBe('2023-01-01');
+ });
+
+ it('returns the first geometry date for non-severeStorms with multiple geometries', () => {
+ const event = {
+ geometry: [
+ { date: '2023-01-01T00:00:00Z' },
+ { date: '2023-01-02T00:00:00Z' },
+ ],
+ categories: [{ id: 'wildfires' }],
+ };
+ expect(getDefaultEventDate(event)).toBe('2023-01-01');
+ });
+
+ it('uses categories.id directly when categories is an object with id', () => {
+ const event = {
+ geometry: [
+ { date: '2023-01-01T00:00:00Z' },
+ { date: '2023-01-02T00:00:00Z' },
+ ],
+ categories: { id: 'wildfires' },
+ };
+ expect(getDefaultEventDate(event)).toBe('2023-01-01');
+ });
+
+ it('returns previous geometry date for severeStorms event occurring today', () => {
+ const event = {
+ geometry: [
+ { date: '2023-06-15T00:00:00Z' },
+ { date: '2023-06-14T00:00:00Z' },
+ ],
+ categories: [{ id: 'severeStorms' }],
+ };
+ expect(getDefaultEventDate(event)).toBe('2023-06-14');
+ });
+
+ it('returns first geometry date for severeStorms when date is not today', () => {
+ const event = {
+ geometry: [
+ { date: '2020-01-01T00:00:00Z' },
+ { date: '2019-12-31T00:00:00Z' },
+ ],
+ categories: [{ id: 'severeStorms' }],
+ };
+ expect(getDefaultEventDate(event)).toBe('2020-01-01');
+ });
+});
+
+describe('validateGeometryCoords', () => {
+ const proj = {
+ crs: GEOGRAPHIC_CRS,
+ maxExtent: [-180, -90, 180, 90],
+ };
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('returns true for a Point geometry within extent', () => {
+ transform.mockReturnValue([10, 20]);
+ containsCoordinate.mockReturnValue(true);
+ const geometry = { type: 'Point', coordinates: [10, 20] };
+ expect(validateGeometryCoords(geometry, proj)).toBe(true);
+ });
+
+ it('returns false for a Point geometry outside extent', () => {
+ transform.mockReturnValue([200, 200]);
+ containsCoordinate.mockReturnValue(false);
+ const geometry = { type: 'Point', coordinates: [200, 200] };
+ expect(validateGeometryCoords(geometry, proj)).toBe(false);
+ });
+
+ it('returns true for a Polygon where all coordinates are within extent', () => {
+ transform.mockReturnValue([10, 20]);
+ containsCoordinate.mockReturnValue(true);
+ const geometry = {
+ type: 'Polygon',
+ coordinates: [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]],
+ };
+ expect(validateGeometryCoords(geometry, proj)).toBe(true);
+ });
+
+ it('returns false for a Polygon where some coordinates are outside extent', () => {
+ transform.mockReturnValueOnce([10, 20]).mockReturnValueOnce([200, 200]);
+ containsCoordinate.mockReturnValueOnce(true).mockReturnValueOnce(false);
+ const geometry = {
+ type: 'Polygon',
+ coordinates: [[[0, 0], [200, 200]]],
+ };
+ expect(validateGeometryCoords(geometry, proj)).toBe(false);
+ });
+
+ it('returns undefined for an unrecognized geometry type', () => {
+ const geometry = { type: 'LineString', coordinates: [[0, 0], [1, 1]] };
+ expect(validateGeometryCoords(geometry, proj)).toBeUndefined();
+ });
+
+ it('calls transform with the correct source and target CRS', () => {
+ transform.mockReturnValue([10, 20]);
+ containsCoordinate.mockReturnValue(true);
+ const geometry = { type: 'Point', coordinates: [10, 20] };
+ validateGeometryCoords(geometry, proj);
+ expect(transform).toHaveBeenCalledWith([10, 20], GEOGRAPHIC_CRS, GEOGRAPHIC_CRS);
+ });
+
+ it('calls containsCoordinate with the transformed coordinates', () => {
+ transform.mockReturnValue([50, 60]);
+ containsCoordinate.mockReturnValue(true);
+ const geometry = { type: 'Point', coordinates: [10, 20] };
+ validateGeometryCoords(geometry, proj);
+ expect(containsCoordinate).toHaveBeenCalledWith(proj.maxExtent, [50, 60]);
+ });
});
diff --git a/web/js/modules/notifications/reducers.test.js b/web/js/modules/notifications/reducers.test.js
index 4df4aaf78..e82fc97d9 100644
--- a/web/js/modules/notifications/reducers.test.js
+++ b/web/js/modules/notifications/reducers.test.js
@@ -6,10 +6,31 @@ import {
import * as constants from './constants';
import { defaultRequestState } from '../core/reducers';
+jest.mock('../../util/local-storage', () => ({
+ __esModule: true,
+ default: {
+ keys: {
+ NOTIFICATION_OUTAGE: 'outage',
+ NOTIFICATION_ALERT: 'alert',
+ NOTIFICATION_MSG: 'message',
+ },
+ getItem: jest.fn(),
+ setItem: jest.fn(),
+ },
+}));
+
+import safeLocalStorage from '../../util/local-storage';
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ safeLocalStorage.getItem.mockReturnValue(null);
+});
+
describe('notificationsRequest reducer', () => {
test('should return the initial state', () => {
expect(notificationsRequest([], {})).toEqual(defaultRequestState);
});
+
test('Should set isLoading to true on Request Start [notifications-reducer-loading]', () => {
expect(
notificationsRequest([], {
@@ -22,6 +43,7 @@ describe('notificationsRequest reducer', () => {
type: null,
});
});
+
test('Should return response upon request success [notifications-reducer-success]', () => {
expect(
notificationsRequest([], {
@@ -35,16 +57,29 @@ describe('notificationsRequest reducer', () => {
type: null,
});
});
+
+ test('Should set error on request failure [notifications-reducer-failure]', () => {
+ expect(
+ notificationsRequest([], {
+ type: constants.REQUEST_NOTIFICATIONS_FAILURE,
+ error: 'fetch error',
+ }),
+ ).toEqual({
+ isLoading: false,
+ error: 'fetch error',
+ response: null,
+ type: null,
+ });
+ });
});
+
describe('notificationsReducer', () => {
test('should return the initial state [notifications-reducer-initial-state]', () => {
- expect(notificationsReducer(undefined, {})).toEqual(
- notificationReducerState,
- );
+ expect(notificationsReducer(undefined, {})).toEqual(notificationReducerState);
});
+
test(
- `${constants.SET_NOTIFICATIONS
- } action type should return object containing sorted mock object [notification-reducer-mock-object]`,
+ `${constants.SET_NOTIFICATIONS} action type should return object containing sorted mock object [notification-reducer-mock-object]`,
() => {
expect(
notificationsReducer([], {
@@ -62,9 +97,9 @@ describe('notificationsReducer', () => {
});
},
);
+
test(
- `${constants.SET_NOTIFICATIONS
- } action type should return object containing sorted mock object [notification-reducer-mock-object-seen]`,
+ `${constants.SET_NOTIFICATIONS} action type should return object containing sorted mock object [notification-reducer-mock-object-seen]`,
() => {
expect(
notificationsReducer(notificationReducerState, {
@@ -79,4 +114,145 @@ describe('notificationsReducer', () => {
});
},
);
+
+ test('SET_NOTIFICATIONS with empty array should return current state unchanged', () => {
+ const currentState = { ...notificationReducerState, number: 5 };
+ const result = notificationsReducer(currentState, {
+ type: constants.SET_NOTIFICATIONS,
+ array: [],
+ });
+ expect(result).toEqual(currentState);
+ });
+
+ test('NOTIFICATIONS_SEEN preserves existing number value', () => {
+ const stateWithNotifications = {
+ ...notificationReducerState,
+ number: 3,
+ numberUnseen: 3,
+ type: 'alert',
+ isActive: true,
+ object: { alerts: [], messages: [], outages: [], layerNotices: [] },
+ };
+ const result = notificationsReducer(stateWithNotifications, {
+ type: constants.NOTIFICATIONS_SEEN,
+ });
+ expect(result.number).toBe(3);
+ expect(result.numberUnseen).toBeNull();
+ expect(result.type).toBe('');
+ expect(result.isActive).toBe(true);
+ });
+
+ test('OUTAGE_NOTIFICATIONS_SEEN reduces number and numberUnseen by numberOutagesUnseen', () => {
+ const stateWithOutages = {
+ number: 3,
+ numberUnseen: 3,
+ numberOutagesUnseen: 2,
+ type: 'outage',
+ isActive: true,
+ object: {
+ alerts: [],
+ messages: [],
+ layerNotices: [],
+ outages: [
+ { notification_type: 'outage', created_at: '2023-03-01' },
+ { notification_type: 'outage', created_at: '2023-02-01' },
+ ],
+ },
+ };
+ const result = notificationsReducer(stateWithOutages, {
+ type: constants.OUTAGE_NOTIFICATIONS_SEEN,
+ });
+ expect(result.number).toBe(1);
+ expect(result.numberUnseen).toBe(1);
+ expect(result.numberOutagesUnseen).toBe(0);
+ });
+
+ test('OUTAGE_NOTIFICATIONS_SEEN sets number and numberUnseen to 0 when result would be negative', () => {
+ const stateWithOutages = {
+ number: 1,
+ numberUnseen: 1,
+ numberOutagesUnseen: 3,
+ type: 'outage',
+ isActive: true,
+ object: {
+ alerts: [],
+ messages: [],
+ layerNotices: [],
+ outages: [
+ { notification_type: 'outage', created_at: '2023-03-01' },
+ { notification_type: 'outage', created_at: '2023-02-01' },
+ { notification_type: 'outage', created_at: '2023-01-01' },
+ ],
+ },
+ };
+ const result = notificationsReducer(stateWithOutages, {
+ type: constants.OUTAGE_NOTIFICATIONS_SEEN,
+ });
+ expect(result.number).toBe(0);
+ expect(result.numberUnseen).toBe(0);
+ expect(result.numberOutagesUnseen).toBe(0);
+ });
+
+ test('OUTAGE_NOTIFICATIONS_SEEN preserves existing object in state', () => {
+ const originalObject = {
+ alerts: [],
+ messages: [{ notification_type: 'message', created_at: '2023-04-01' }],
+ layerNotices: [{ id: 20 }],
+ outages: [
+ { notification_type: 'outage', created_at: '2023-03-01' },
+ { notification_type: 'outage', created_at: '2023-02-01' },
+ ],
+ };
+ const stateWithOutages = {
+ number: 2,
+ numberUnseen: 2,
+ numberOutagesUnseen: 2,
+ type: 'outage',
+ isActive: true,
+ object: originalObject,
+ };
+ const result = notificationsReducer(stateWithOutages, {
+ type: constants.OUTAGE_NOTIFICATIONS_SEEN,
+ });
+ expect(result.object).toBe(originalObject);
+ });
+
+ test('OUTAGE_NOTIFICATIONS_SEEN updates type via getPriority on remaining notifications', () => {
+ const stateWithOutages = {
+ number: 2,
+ numberUnseen: 2,
+ numberOutagesUnseen: 2,
+ type: 'outage',
+ isActive: true,
+ object: {
+ alerts: [],
+ messages: [],
+ layerNotices: [],
+ outages: [
+ { notification_type: 'outage', created_at: '2023-03-01' },
+ { notification_type: 'outage', created_at: '2023-02-01' },
+ ],
+ },
+ };
+ const result = notificationsReducer(stateWithOutages, {
+ type: constants.OUTAGE_NOTIFICATIONS_SEEN,
+ });
+ expect(typeof result.type).toBe('string');
+ });
+
+ test('unknown action type returns current state unchanged', () => {
+ const currentState = { ...notificationReducerState, number: 5 };
+ const result = notificationsReducer(currentState, { type: 'UNKNOWN_ACTION' });
+ expect(result).toEqual(currentState);
+ });
+
+ test('notificationReducerState has correct initial shape', () => {
+ expect(notificationReducerState).toEqual({
+ number: null,
+ numberUnseen: null,
+ type: '',
+ isActive: false,
+ object: {},
+ });
+ });
});
diff --git a/web/js/modules/notifications/util.test.js b/web/js/modules/notifications/util.test.js
index 4072f4f95..f5c61c2bc 100644
--- a/web/js/modules/notifications/util.test.js
+++ b/web/js/modules/notifications/util.test.js
@@ -1,3 +1,414 @@
-test('util module test', () => {
+/* eslint-disable camelcase */
+import {
+ transformLayerNotices,
+ separateByType,
+ getPriority,
+ getNumberOfTypeNotSeen,
+ getCount,
+ addToLocalStorage,
+ getLayerNoticesForLayer,
+} from './util';
+jest.mock('../../util/local-storage', () => ({
+ __esModule: true,
+ default: {
+ keys: {
+ NOTIFICATION_OUTAGE: 'outage',
+ NOTIFICATION_ALERT: 'alert',
+ NOTIFICATION_MSG: 'message',
+ },
+ getItem: jest.fn(),
+ setItem: jest.fn(),
+ },
+}));
+
+import safeLocalStorage from '../../util/local-storage';
+
+const OUTAGE = 'outage';
+const ALERT = 'alert';
+const MSG = 'message';
+
+const makeNotification = (type, created_at, path = '/notifications/status') => ({
+ notification_type: type,
+ created_at,
+ path,
+});
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ safeLocalStorage.getItem.mockReturnValue(null);
+});
+
+describe('transformLayerNotices', () => {
+ it('extracts layers from path segments after index 2', () => {
+ const notices = [{ path: '/layer-notice/MODIS/layer1/layer2', message: 'hello' }];
+ const result = transformLayerNotices(notices);
+ expect(result[0].layers).toEqual(['MODIS', 'layer1', 'layer2']);
+ });
+
+ it('returns an empty layers array when path has no segments after index 2', () => {
+ const notices = [{ path: '/layer-notice', message: 'hi' }];
+ const result = transformLayerNotices(notices);
+ expect(result[0].layers).toEqual([]);
+ });
+
+ it('preserves all other properties on the notice', () => {
+ const notices = [{ path: '/layer-notice/MODIS/layer1', message: 'test', id: 42 }];
+ const result = transformLayerNotices(notices);
+ expect(result[0].message).toBe('test');
+ expect(result[0].id).toBe(42);
+ });
+
+ it('returns an empty array when given an empty array', () => {
+ expect(transformLayerNotices([])).toEqual([]);
+ });
+
+ it('handles multiple notices', () => {
+ const notices = [
+ { path: '/layer-notice/MODIS/layerA', message: 'a' },
+ { path: '/layer-notice/VIIRS/layerB/layerC', message: 'b' },
+ ];
+ const result = transformLayerNotices(notices);
+ expect(result[0].layers).toEqual(['MODIS', 'layerA']);
+ expect(result[1].layers).toEqual(['VIIRS', 'layerB', 'layerC']);
+ });
+});
+
+describe('separateByType', () => {
+ it('separates messages into the messages array', () => {
+ const notifications = [makeNotification(MSG, '2023-01-01')];
+ const result = separateByType(notifications);
+ expect(result.messages).toHaveLength(1);
+ expect(result.alerts).toHaveLength(0);
+ expect(result.outages).toHaveLength(0);
+ });
+
+ it('separates alerts into the alerts array', () => {
+ const notifications = [makeNotification(ALERT, '2023-01-01')];
+ const result = separateByType(notifications);
+ expect(result.alerts).toHaveLength(1);
+ expect(result.messages).toHaveLength(0);
+ expect(result.outages).toHaveLength(0);
+ });
+
+ it('separates outages into the outages array', () => {
+ const notifications = [makeNotification(OUTAGE, '2023-01-01')];
+ const result = separateByType(notifications);
+ expect(result.outages).toHaveLength(1);
+ expect(result.messages).toHaveLength(0);
+ expect(result.alerts).toHaveLength(0);
+ });
+
+ it('separates layer notices from regular notifications', () => {
+ const notifications = [
+ makeNotification(MSG, '2023-01-01', '/layer-notice/MODIS/layer1'),
+ ];
+ const result = separateByType(notifications);
+ expect(result.layerNotices).toHaveLength(1);
+ expect(result.messages).toHaveLength(0);
+ });
+
+ it('adds layers property to layer notices', () => {
+ const notifications = [
+ makeNotification(MSG, '2023-01-01', '/layer-notice/MODIS/layer1'),
+ ];
+ const result = separateByType(notifications);
+ expect(result.layerNotices[0].layers).toEqual(['MODIS', 'layer1']);
+ });
+
+ it('sorts each category by date descending', () => {
+ const notifications = [
+ makeNotification(MSG, '2023-01-01'),
+ makeNotification(MSG, '2023-06-01'),
+ ];
+ const result = separateByType(notifications);
+ expect(result.messages[0].created_at).toBe('2023-06-01');
+ expect(result.messages[1].created_at).toBe('2023-01-01');
+ });
+
+ it('handles mixed types in one array', () => {
+ const notifications = [
+ makeNotification(MSG, '2023-01-01'),
+ makeNotification(ALERT, '2023-02-01'),
+ makeNotification(OUTAGE, '2023-03-01'),
+ makeNotification(MSG, '2023-01-01', '/layer-notice/MODIS/layer1'),
+ ];
+ const result = separateByType(notifications);
+ expect(result.messages).toHaveLength(1);
+ expect(result.alerts).toHaveLength(1);
+ expect(result.outages).toHaveLength(1);
+ expect(result.layerNotices).toHaveLength(1);
+ });
+
+ it('returns empty arrays when given an empty array', () => {
+ const result = separateByType([]);
+ expect(result.messages).toEqual([]);
+ expect(result.alerts).toEqual([]);
+ expect(result.outages).toEqual([]);
+ expect(result.layerNotices).toEqual([]);
+ });
+
+ it('ignores notifications with unrecognized types', () => {
+ const notifications = [makeNotification('unknown_type', '2023-01-01')];
+ const result = separateByType(notifications);
+ expect(result.messages).toHaveLength(0);
+ expect(result.alerts).toHaveLength(0);
+ expect(result.outages).toHaveLength(0);
+ });
+});
+
+describe('getPriority', () => {
+ it('returns empty string when no notifications are present', () => {
+ const result = getPriority({ messages: [], alerts: [], outages: [] });
+ expect(result).toBe('');
+ });
+
+ it('returns message type when only an unseen message is present', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const sorted = {
+ messages: [makeNotification(MSG, '2023-01-01')],
+ alerts: [],
+ outages: [],
+ };
+ expect(getPriority(sorted)).toBe(MSG);
+ });
+
+ it('returns alert type when an unseen alert is present (overrides message)', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const sorted = {
+ messages: [makeNotification(MSG, '2023-01-01')],
+ alerts: [makeNotification(ALERT, '2023-01-01')],
+ outages: [],
+ };
+ expect(getPriority(sorted)).toBe(ALERT);
+ });
+
+ it('returns outage type when an unseen outage is present (highest priority)', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const sorted = {
+ messages: [makeNotification(MSG, '2023-01-01')],
+ alerts: [makeNotification(ALERT, '2023-01-01')],
+ outages: [makeNotification(OUTAGE, '2023-01-01')],
+ };
+ expect(getPriority(sorted)).toBe(OUTAGE);
+ });
+
+ it('returns empty string when the most recent notification has already been seen', () => {
+ safeLocalStorage.getItem.mockReturnValue('2023-12-31');
+ const sorted = {
+ messages: [],
+ alerts: [],
+ outages: [makeNotification(OUTAGE, '2023-01-01')],
+ };
+ expect(getPriority(sorted)).toBe('');
+ });
+
+ it('returns outage when outage is newer than what is stored', () => {
+ safeLocalStorage.getItem.mockReturnValue('2022-01-01');
+ const sorted = {
+ messages: [],
+ alerts: [],
+ outages: [makeNotification(OUTAGE, '2023-06-01')],
+ };
+ expect(getPriority(sorted)).toBe(OUTAGE);
+ });
+
+ it('returns alert when alert is unseen and outage is already seen', () => {
+ safeLocalStorage.getItem.mockImplementation((key) => {
+ if (key === OUTAGE) return '2023-12-31';
+ return null;
+ });
+ const sorted = {
+ messages: [],
+ alerts: [makeNotification(ALERT, '2023-01-01')],
+ outages: [makeNotification(OUTAGE, '2023-01-01')],
+ };
+ expect(getPriority(sorted)).toBe(ALERT);
+ });
+});
+
+describe('getNumberOfTypeNotSeen', () => {
+ it('returns the full array length when no storage item exists', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const items = [
+ { created_at: '2023-06-01' },
+ { created_at: '2023-05-01' },
+ { created_at: '2023-04-01' },
+ ];
+ expect(getNumberOfTypeNotSeen(OUTAGE, items)).toBe(3);
+ });
+
+ it('returns 0 when all notifications have been seen', () => {
+ safeLocalStorage.getItem.mockReturnValue('2023-12-31');
+ const items = [
+ { created_at: '2023-06-01' },
+ { created_at: '2023-05-01' },
+ ];
+ expect(getNumberOfTypeNotSeen(OUTAGE, items)).toBe(0);
+ });
+
+ it('returns correct count when some are newer than the stored date', () => {
+ safeLocalStorage.getItem.mockReturnValue('2023-04-15');
+ const items = [
+ { created_at: '2023-06-01' },
+ { created_at: '2023-05-01' },
+ { created_at: '2023-03-01' },
+ ];
+ expect(getNumberOfTypeNotSeen(OUTAGE, items)).toBe(2);
+ });
+
+ it('returns 0 when array is empty and no storage item', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ expect(getNumberOfTypeNotSeen(OUTAGE, [])).toBe(0);
+ });
+
+ it('returns 0 when array is empty and storage item exists', () => {
+ safeLocalStorage.getItem.mockReturnValue('2023-01-01');
+ expect(getNumberOfTypeNotSeen(OUTAGE, [])).toBe(0);
+ });
+
+ it('stops counting at the first seen item', () => {
+ safeLocalStorage.getItem.mockReturnValue('2023-04-15');
+ const items = [
+ { created_at: '2023-06-01' },
+ { created_at: '2023-03-01' },
+ { created_at: '2023-02-01' },
+ ];
+ expect(getNumberOfTypeNotSeen(OUTAGE, items)).toBe(1);
+ });
+});
+
+describe('getCount', () => {
+ it('returns the sum of messages, alerts, and outages', () => {
+ const notifications = {
+ messages: [{ id: 1 }, { id: 2 }],
+ alerts: [{ id: 3 }],
+ outages: [{ id: 4 }, { id: 5 }, { id: 6 }],
+ };
+ expect(getCount(notifications)).toBe(6);
+ });
+
+ it('returns 0 when all arrays are empty', () => {
+ expect(getCount({ messages: [], alerts: [], outages: [] })).toBe(0);
+ });
+
+ it('does not count layerNotices', () => {
+ const notifications = {
+ messages: [{ id: 1 }],
+ alerts: [],
+ outages: [],
+ layerNotices: [{ id: 2 }, { id: 3 }],
+ };
+ expect(getCount(notifications)).toBe(1);
+ });
+
+ it('returns correct count with only messages', () => {
+ expect(getCount({ messages: [{ id: 1 }, { id: 2 }], alerts: [], outages: [] })).toBe(2);
+ });
+
+ it('returns correct count with only alerts', () => {
+ expect(getCount({ messages: [], alerts: [{ id: 1 }], outages: [] })).toBe(1);
+ });
+
+ it('returns correct count with only outages', () => {
+ expect(getCount({ messages: [], alerts: [], outages: [{ id: 1 }, { id: 2 }] })).toBe(2);
+ });
+});
+
+describe('addToLocalStorage', () => {
+ it('stores message, outage, and alert created_at values', () => {
+ addToLocalStorage({
+ messages: [{ created_at: '2023-01-01' }],
+ outages: [{ created_at: '2023-02-01' }],
+ alerts: [{ created_at: '2023-03-01' }],
+ });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(OUTAGE, '2023-02-01');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(ALERT, '2023-03-01');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(MSG, '2023-01-01');
+ });
+
+ it('does not call setItem for outage when outages array is empty', () => {
+ addToLocalStorage({
+ messages: [{ created_at: '2023-01-01' }],
+ outages: [],
+ alerts: [],
+ });
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalledWith(OUTAGE, expect.anything());
+ });
+
+ it('does not call setItem when all arrays are empty', () => {
+ addToLocalStorage({
+ messages: [],
+ outages: [],
+ alerts: [],
+ });
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ it('does not call setItem for message when messages array is empty', () => {
+ addToLocalStorage({
+ messages: [],
+ outages: [{ created_at: '2023-01-01' }],
+ alerts: [],
+ });
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalledWith(MSG, expect.anything());
+ });
+
+ it('only stores the first item from each array', () => {
+ addToLocalStorage({
+ messages: [{ created_at: '2023-06-01' }, { created_at: '2023-01-01' }],
+ outages: [{ created_at: '2023-05-01' }, { created_at: '2023-02-01' }],
+ alerts: [{ created_at: '2023-04-01' }, { created_at: '2023-03-01' }],
+ });
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(MSG, '2023-06-01');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(OUTAGE, '2023-05-01');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(ALERT, '2023-04-01');
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalledWith(MSG, '2023-01-01');
+ });
+});
+
+describe('getLayerNoticesForLayer', () => {
+ const buildNotifications = (layerNotices) => ({ object: { layerNotices } });
+
+ it('returns an empty string when no layer notices match the layer', () => {
+ const notifications = buildNotifications([
+ { layers: ['layer2'], message: 'Notice for layer2' },
+ ]);
+ expect(getLayerNoticesForLayer('layer1', notifications)).toBe('');
+ });
+
+ it('returns formatted HTML for a matching layer notice', () => {
+ const notifications = buildNotifications([
+ { layers: ['layer1'], message: 'Notice A' },
+ ]);
+ expect(getLayerNoticesForLayer('layer1', notifications)).toBe(' <div>Notice A</div>');
+ });
+
+ it('concatenates multiple matching notices', () => {
+ const notifications = buildNotifications([
+ { layers: ['layer1'], message: 'Notice A' },
+ { layers: ['layer1'], message: 'Notice B' },
+ ]);
+ const result = getLayerNoticesForLayer('layer1', notifications);
+ expect(result).toBe(' <div>Notice A</div> <div>Notice B</div>');
+ });
+
+ it('filters out non-matching layer notices', () => {
+ const notifications = buildNotifications([
+ { layers: ['layer1'], message: 'Notice A' },
+ { layers: ['layer2'], message: 'Notice B' },
+ ]);
+ const result = getLayerNoticesForLayer('layer1', notifications);
+ expect(result).toBe(' <div>Notice A</div>');
+ });
+
+ it('returns empty string when layerNotices is an empty array', () => {
+ const notifications = buildNotifications([]);
+ expect(getLayerNoticesForLayer('layer1', notifications)).toBe('');
+ });
+
+ it('returns empty string when layerNotices is null or undefined', () => {
+ const notifications = buildNotifications(null);
+ expect(getLayerNoticesForLayer('layer1', notifications)).toBe('');
+ });
});
diff --git a/web/js/modules/palettes/actions.test.js b/web/js/modules/palettes/actions.test.js
index 112442923..985e08dcd 100644
--- a/web/js/modules/palettes/actions.test.js
+++ b/web/js/modules/palettes/actions.test.js
@@ -8,6 +8,12 @@ import {
setThresholdRangeSquashAndNoClip,
setCustomPalette,
clearCustomPalette,
+ loadedCustomPalettes,
+ clearCustoms,
+ clearCustomsSnapshot,
+ refreshPalettes,
+ refreshDisabledClassification,
+ setToggledClassification,
} from './actions';
import { addLayer } from '../layers/selectors';
import {
@@ -17,6 +23,8 @@ import {
SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP,
SET_CUSTOM,
CLEAR_CUSTOM,
+ SET_DISABLED_CLASSIFICATION,
+ LOADED_CUSTOM_PALETTES,
} from './constants';
import fixtures from '../../fixtures';
@@ -30,57 +38,55 @@ const state = fixtures.getState();
const config = fixtures.config();
const ERROR_MESSAGE = 'There was an error';
-describe('Palette terra-aod fetching with requestPalette action [palettes-actions-request-palette]', () => {
+describe('requestPalette action [palettes-actions-request]', () => {
const mockStore = configureMockStore(middlewares);
+ let layers = addLayer('terra-aod', [], config.layers, {}, 0);
+ layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
+ const stateWithLayers = update(state, {
+ layers: { active: { $set: layers } },
+ });
+
beforeEach(() => {
fetch.resetMocks();
});
- test(`test ${REQUEST_PALETTE_SUCCESS}`, () => {
- fetch.mockResponseOnce(JSON.stringify(config.palettes.rendered['terra-aod']));
- const expectedActions = [
- { type: REQUEST_PALETTE_START, id: 'terra-aod' },
- {
- type: REQUEST_PALETTE_SUCCESS,
- id: 'terra-aod',
- response: config.palettes.rendered['terra-aod'],
- },
- ];
- const store = mockStore(state);
- return store.dispatch(requestPalette('terra-aod')).then(() => {
- expect(store.getActions()).toEqual(expectedActions);
- });
+
+ test(`test ${requestPalette} action success [palettes-actions-request-success]`, async () => {
+ fetch.mockResponse(JSON.stringify({}));
+ const store = mockStore(stateWithLayers);
+ await store.dispatch(requestPalette('terra-aod'));
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(REQUEST_PALETTE_START);
+ expect(types).toContain(REQUEST_PALETTE_SUCCESS);
});
- test(`Test ${REQUEST_PALETTE_FAILURE} [palettes-actions-failure]`, () => {
- fetch.mockReject(ERROR_MESSAGE);
- const expectedActions = [
- { type: REQUEST_PALETTE_START, id: 'terra-aod' },
- {
- type: REQUEST_PALETTE_FAILURE,
- id: 'terra-aod',
- error: ERROR_MESSAGE,
- },
- ];
- const store = mockStore(state);
- return store.dispatch(requestPalette('terra-aod')).catch(() => {
- expect(store.getActions()).toEqual(expectedActions);
- });
+
+ test(`test ${requestPalette} action failure [palettes-actions-request-failure]`, async () => {
+ fetch.mockReject(new Error(ERROR_MESSAGE));
+ const store = mockStore(stateWithLayers);
+ await store.dispatch(requestPalette('terra-aod'));
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(REQUEST_PALETTE_START);
+ expect(types).toContain(REQUEST_PALETTE_FAILURE);
});
});
-describe('Test lookup actions [palettes-actions-lookup]', () => {
+
+describe('palette threshold/custom/clear actions [palettes-actions-main]', () => {
const mockStore = configureMockStore(middlewares);
let layers = addLayer('terra-aod', [], config.layers, {}, 0);
layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
const stateWithLayers = update(state, {
layers: { active: { $set: layers } },
});
+
beforeEach(() => {
fetch.resetMocks();
});
+
test(`test ${setThresholdRangeSquashAndNoClip} action with min equal to 1`, () => {
const store = mockStore(stateWithLayers);
store.dispatch(setThresholdRangeSquashAndNoClip('terra-aod', { min: 1 }, 0, 'active'));
const response = store.getActions()[0];
-
expect(response.type).toEqual(SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP);
expect(response.props).toEqual({ min: 1 });
expect(response.groupName).toEqual('active');
@@ -99,13 +105,13 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
config.palettes.lookups['terra-aod']['min-1'],
);
});
+
test(`test ${setThresholdRangeSquashAndNoClip} action with squash and max [palettes-actions-threshold-1]`, () => {
const store = mockStore(stateWithLayers);
store.dispatch(
setThresholdRangeSquashAndNoClip('terra-aod', { max: 1, squash: true }, 0, 'active'),
);
const response = store.getActions()[0];
-
expect(response.type).toEqual(SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP);
expect(response.props).toEqual({ max: 1, squash: true });
expect(response.groupName).toEqual('active');
@@ -122,13 +128,13 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
config.palettes.lookups['terra-aod']['max-1-squashed'],
);
});
+
test(`test ${setThresholdRangeSquashAndNoClip} action with noclip and max [palettes-actions-threshold-2]`, () => {
const store = mockStore(stateWithLayers);
store.dispatch(
setThresholdRangeSquashAndNoClip('terra-aod', { max: 1, noclip: true }, 0, 'active'),
);
const response = store.getActions()[0];
-
expect(response.type).toEqual(SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP);
expect(response.props).toEqual({ max: 1, noclip: true });
expect(response.groupName).toEqual('active');
@@ -145,12 +151,12 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
config.palettes.lookups['terra-aod']['max-1-noclipped'],
);
});
+
test(`test ${setCustomPalette} action with red-1 fixture palette [palettes-actions-set-custom]`, () => {
const expectedLegendColors = config.palettes.custom['red-1'].colors;
const store = mockStore(stateWithLayers);
store.dispatch(setCustomPalette('terra-aod', 'red-1', 0, 'active'));
const response = store.getActions()[0];
-
expect(response.type).toEqual(SET_CUSTOM);
expect(response.paletteId).toEqual('red-1');
expect(response.groupName).toEqual('active');
@@ -164,6 +170,7 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
config.palettes.lookups['terra-aod']['red-1'],
);
});
+
test(`test ${clearCustomPalette} action when no threshold applied [palettes-actions-clear-custom]`, () => {
let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
terraAOD = update(terraAOD, {
@@ -192,7 +199,6 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
const customPalatteState = update(stateWithLayers, {
palettes: { active: { $set: { 'terra-aod': terraAOD } } },
});
-
const store = mockStore(customPalatteState);
store.dispatch(clearCustomPalette('terra-aod', 0, 'active'));
const response = store.getActions()[0];
@@ -203,6 +209,7 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
expect(response.layerId).toEqual('terra-aod');
expect(response.activeString).toEqual('active');
});
+
test(
`test ${clearCustomPalette} action with threshold and squash applied [palettes-actions-clear-custom-threshold-1]`,
() => {
@@ -269,6 +276,7 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
);
},
);
+
test(
`test ${clearCustomPalette} action with threshold and noclip applied [palettes-actions-clear-custom-threshold-2]`,
() => {
@@ -336,3 +344,249 @@ describe('Test lookup actions [palettes-actions-lookup]', () => {
},
);
});
+
+describe('loadedCustomPalettes action [palettes-actions-loaded-custom]', () => {
+ test('returns correct type and custom payload', () => {
+ const customs = { 'red-1': { colors: ['ff0000ff'] } };
+ const result = loadedCustomPalettes(customs);
+ expect(result.type).toEqual(LOADED_CUSTOM_PALETTES);
+ expect(result.custom).toEqual(customs);
+ });
+
+ test('returns correct type with empty object', () => {
+ const result = loadedCustomPalettes({});
+ expect(result.type).toEqual(LOADED_CUSTOM_PALETTES);
+ expect(result.custom).toEqual({});
+ });
+});
+
+describe('setToggledClassification action [palettes-actions-set-toggled-classification]', () => {
+ const mockStore = configureMockStore(middlewares);
+ let layers = addLayer('terra-aod', [], config.layers, {}, 0);
+ layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
+ const stateWithLayers = update(state, {
+ layers: { active: { $set: layers } },
+ });
+
+ test('does not dispatch when layer is not found in active layers', () => {
+ const terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': terraAOD } } },
+ layers: { active: { layers: { $set: [] } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(setToggledClassification('terra-aod', 0, 0, 'active'));
+ const actions = store.getActions();
+ expect(actions.length).toEqual(0);
+ });
+
+ test('dispatches SET_DISABLED_CLASSIFICATION when layer is present in active layers', () => {
+ const terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ const layerObj = { id: 'terra-aod', palette: { id: 'terra-aod' } };
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': terraAOD } } },
+ layers: { active: { layers: { $set: [layerObj] } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(setToggledClassification('terra-aod', 0, 0, 'active'));
+ const actions = store.getActions();
+ expect(actions[0].type).toEqual(SET_DISABLED_CLASSIFICATION);
+ expect(actions[0].layerId).toEqual('terra-aod');
+ expect(actions[0].groupName).toEqual('active');
+ expect(actions[0].activeString).toEqual('active');
+ expect(actions[0].props).toBeDefined();
+ });
+});
+
+describe('refreshDisabledClassification action [palettes-actions-refresh-disabled]', () => {
+ const mockStore = configureMockStore(middlewares);
+ let layers = addLayer('terra-aod', [], config.layers, {}, 0);
+ layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
+ const stateWithLayers = update(state, {
+ layers: { active: { $set: layers } },
+ });
+
+ test('does not dispatch when disabledArray is empty and layerId is not in selector result', () => {
+ const store = mockStore(stateWithLayers);
+ store.dispatch(refreshDisabledClassification('terra-aod', [], 0, 'active'));
+ const actions = store.getActions();
+ expect(actions.length).toEqual(0);
+ });
+});
+
+describe('clearCustoms action [palettes-actions-clear-customs]', () => {
+ const mockStore = configureMockStore(middlewares);
+ let layers = addLayer('terra-aod', [], config.layers, {}, 0);
+ layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
+ const stateWithLayers = update(state, {
+ layers: { active: { $set: layers } },
+ });
+
+ test('dispatches CLEAR_CUSTOM for a layer with a custom palette', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ lookup: { $set: config.palettes.lookups['terra-aod']['red-1'] },
+ });
+ terraAOD = update(terraAOD, {
+ maps: { 0: { custom: { $set: 'red-1' } } },
+ });
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': terraAOD } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(clearCustoms());
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(CLEAR_CUSTOM);
+ });
+
+ test('dispatches SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP for a layer with max threshold', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ maps: { 0: { max: { $set: 1 } } },
+ });
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': terraAOD } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(clearCustoms());
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP);
+ });
+
+ test('dispatches SET_DISABLED_CLASSIFICATION for a layer with disabled colormaps when layer is in active layers', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ maps: { 0: { disabled: { $set: [0] } } },
+ });
+ const layerObj = { id: 'terra-aod', palette: { id: 'terra-aod' } };
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': cloneDeep(terraAOD) } } },
+ layers: { active: { layers: { $set: [layerObj] } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(clearCustoms());
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(SET_DISABLED_CLASSIFICATION);
+ });
+
+ test('does not dispatch SET_DISABLED_CLASSIFICATION when keepDisabledClassification is true', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ maps: { 0: { disabled: { $set: [0] } } },
+ });
+ const layerObj = { id: 'terra-aod', palette: { id: 'terra-aod' } };
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': cloneDeep(terraAOD) } } },
+ layers: { active: { layers: { $set: [layerObj] } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(clearCustoms(true));
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).not.toContain(SET_DISABLED_CLASSIFICATION);
+ });
+});
+
+describe('clearCustomsSnapshot action [palettes-actions-clear-customs-snapshot]', () => {
+ const mockStore = configureMockStore(middlewares);
+ let layers = addLayer('terra-aod', [], config.layers, {}, 0);
+ layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
+ const stateWithLayers = update(state, {
+ layers: { active: { $set: layers } },
+ });
+
+ test('does not dispatch SET_DISABLED_CLASSIFICATION for disabled colormaps', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ maps: { 0: { disabled: { $set: [0] } } },
+ });
+ const layerObj = { id: 'terra-aod', palette: { id: 'terra-aod' } };
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': cloneDeep(terraAOD) } } },
+ layers: { active: { layers: { $set: [layerObj] } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(clearCustomsSnapshot());
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).not.toContain(SET_DISABLED_CLASSIFICATION);
+ });
+
+ test('dispatches CLEAR_CUSTOM for a layer with a custom palette', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ lookup: { $set: config.palettes.lookups['terra-aod']['red-1'] },
+ });
+ terraAOD = update(terraAOD, {
+ maps: { 0: { custom: { $set: 'red-1' } } },
+ });
+ const customState = update(stateWithLayers, {
+ palettes: { active: { $set: { 'terra-aod': terraAOD } } },
+ });
+ const store = mockStore(customState);
+ store.dispatch(clearCustomsSnapshot());
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(CLEAR_CUSTOM);
+ });
+});
+
+describe('refreshPalettes action [palettes-actions-refresh-palettes]', () => {
+ const mockStore = configureMockStore(middlewares);
+ let layers = addLayer('terra-aod', [], config.layers, {}, 0);
+ layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
+ const stateWithLayers = update(state, {
+ layers: { active: { $set: layers } },
+ });
+
+ test('dispatches SET_CUSTOM for a palette with a custom colormap', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ maps: { 0: { custom: { $set: 'red-1' } } },
+ });
+ const activePalettes = { 'terra-aod': cloneDeep(terraAOD) };
+ const store = mockStore(stateWithLayers);
+ store.dispatch(refreshPalettes(activePalettes));
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(SET_CUSTOM);
+ });
+
+ test('dispatches SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP for palette with max', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ maps: { 0: { max: { $set: 1 } } },
+ });
+ const activePalettes = { 'terra-aod': cloneDeep(terraAOD) };
+ const store = mockStore(stateWithLayers);
+ store.dispatch(refreshPalettes(activePalettes));
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP);
+ });
+
+ test('dispatches SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP for palette with squash', () => {
+ let terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ terraAOD = update(terraAOD, {
+ maps: { 0: { squash: { $set: true } } },
+ });
+ const activePalettes = { 'terra-aod': cloneDeep(terraAOD) };
+ const store = mockStore(stateWithLayers);
+ store.dispatch(refreshPalettes(activePalettes));
+ const actions = store.getActions();
+ const types = actions.map((a) => a.type);
+ expect(types).toContain(SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP);
+ });
+
+ test('dispatches no actions for a palette with no custom, threshold, or disabled colormaps', () => {
+ const terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ const activePalettes = { 'terra-aod': cloneDeep(terraAOD) };
+ const store = mockStore(stateWithLayers);
+ store.dispatch(refreshPalettes(activePalettes));
+ const actions = store.getActions();
+ expect(actions.length).toEqual(0);
+ });
+});
diff --git a/web/js/modules/palettes/reducers.test.js b/web/js/modules/palettes/reducers.test.js
index 3eace5be2..560eeb863 100644
--- a/web/js/modules/palettes/reducers.test.js
+++ b/web/js/modules/palettes/reducers.test.js
@@ -1,5 +1,5 @@
import update from 'immutability-helper';
-import { getInitialPaletteState, paletteReducer } from './reducers';
+import { getInitialPaletteState, paletteReducer, defaultPaletteState } from './reducers';
import fixtures from '../../fixtures';
import {
SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP,
@@ -7,9 +7,12 @@ import {
SET_CUSTOM,
REQUEST_PALETTE_START,
BULK_PALETTE_RENDERING_SUCCESS,
+ BULK_PALETTE_PRELOADING_SUCCESS,
REQUEST_PALETTE_SUCCESS,
+ LOADED_CUSTOM_PALETTES,
+ SET_DISABLED_CLASSIFICATION,
} from './constants';
-import { INIT_SECOND_LAYER_GROUP } from '../layers/constants';
+import { INIT_SECOND_LAYER_GROUP, SYNC_SECOND_LAYER_GROUP } from '../layers/constants';
const config = fixtures.config();
@@ -25,6 +28,22 @@ test('SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP action updates active palette Object
expect(response.active['terra-aod']).toBeDefined();
});
+test('BULK_PALETTE_RENDERING_SUCCESS action merges rendered palettes with new palettes from action [palettes-reducer-bulk-render]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const updatedState = update(initialPaletteState, {
+ rendered: { $set: { 'test-1': 'test-1' } },
+ });
+ const response = paletteReducer(updatedState, {
+ type: BULK_PALETTE_RENDERING_SUCCESS,
+ id: 'test-2',
+ rendered: { 'test-2': 'test-2' },
+ });
+ expect(updatedState.rendered['test-2']).toBeUndefined();
+ expect(updatedState.rendered['test-1']).toEqual('test-1');
+ expect(response.rendered['test-2']).toEqual('test-2');
+ expect(response.rendered['test-1']).toEqual('test-1');
+});
+
test('CLEAR_CUSTOM action updates active palette Object [palettes-reducer-clear-custom]', () => {
const initialPaletteState = getInitialPaletteState(config);
const response = paletteReducer(initialPaletteState, {
@@ -36,6 +55,7 @@ test('CLEAR_CUSTOM action updates active palette Object [palettes-reducer-clear-
expect(initialPaletteState.active['terra-aod']).toEqual(undefined);
expect(response.active['terra-aod']).toBeDefined();
});
+
test('SET_CUSTOM action updates active palette Object [palettes-reducer-set-custom]', () => {
const initialPaletteState = getInitialPaletteState(config);
const response = paletteReducer(initialPaletteState, {
@@ -47,6 +67,7 @@ test('SET_CUSTOM action updates active palette Object [palettes-reducer-set-cust
expect(initialPaletteState.active['terra-aod']).toEqual(undefined);
expect(response.active['terra-aod']).toBeDefined();
});
+
test('INIT_SECOND_LAYER_GROUP action updates active palette Object [palettes-reducer-second-layer-group]', () => {
const initialPaletteState = getInitialPaletteState(config);
const previousState = update(initialPaletteState, {
@@ -61,6 +82,7 @@ test('INIT_SECOND_LAYER_GROUP action updates active palette Object [palettes-red
expect(previousState.activeB.test).toBeUndefined();
expect(response.activeB.test).toEqual('tests');
});
+
test('REQUEST_PALETTE_START action updates active palette Object [palettes-reducer-request-palette]', () => {
const initialPaletteState = getInitialPaletteState(config);
const response = paletteReducer(initialPaletteState, {
@@ -70,6 +92,7 @@ test('REQUEST_PALETTE_START action updates active palette Object [palettes-reduc
expect(initialPaletteState.isLoading.test).toBeUndefined();
expect(response.isLoading.test).toBeTruthy();
});
+
test('REQUEST_PALETTE_SUCCESS action updates active palette Object [palettes-reducer-success]', () => {
const initialPaletteState = getInitialPaletteState(config);
const response = paletteReducer(initialPaletteState, {
@@ -81,18 +104,213 @@ test('REQUEST_PALETTE_SUCCESS action updates active palette Object [palettes-red
expect(response.rendered.test).toEqual('test-response');
});
-test('BULK_PALETTE_RENDERING_SUCCESS action merges rendered palettes with new palettes from action [palettes-reducer-bulk-render]', () => {
+test('BULK_PALETTE_PRELOADING_SUCCESS action merges tourStoryPalettes [palettes-reducer-bulk-preload]', () => {
const initialPaletteState = getInitialPaletteState(config);
- const updatedState = update(initialPaletteState, {
- rendered: { $set: { 'test-1': 'test-1' } },
+ const response = paletteReducer(initialPaletteState, {
+ type: BULK_PALETTE_PRELOADING_SUCCESS,
+ tourStoryPalettes: { 'story-1': 'story-1' },
});
- const response = paletteReducer(updatedState, {
+ expect(initialPaletteState.tourStoryPalettes['story-1']).toBeUndefined();
+ expect(response.tourStoryPalettes['story-1']).toEqual('story-1');
+});
+
+test('BULK_PALETTE_PRELOADING_SUCCESS action merges with existing tourStoryPalettes [palettes-reducer-bulk-preload-merge]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const stateWithExisting = update(initialPaletteState, {
+ tourStoryPalettes: { $set: { 'story-1': 'story-1' } },
+ });
+ const response = paletteReducer(stateWithExisting, {
+ type: BULK_PALETTE_PRELOADING_SUCCESS,
+ tourStoryPalettes: { 'story-2': 'story-2' },
+ });
+ expect(response.tourStoryPalettes['story-1']).toEqual('story-1');
+ expect(response.tourStoryPalettes['story-2']).toEqual('story-2');
+});
+
+test('BULK_PALETTE_PRELOADING_SUCCESS action with empty tourStoryPalettes [palettes-reducer-bulk-preload-empty]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: BULK_PALETTE_PRELOADING_SUCCESS,
+ });
+ expect(response.tourStoryPalettes).toEqual({});
+});
+
+test('BULK_PALETTE_RENDERING_SUCCESS action with empty rendered [palettes-reducer-bulk-render-empty]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
type: BULK_PALETTE_RENDERING_SUCCESS,
- id: 'test-2',
- rendered: { 'test-2': 'test-2' },
});
- expect(updatedState.rendered['test-2']).toBeUndefined();
- expect(updatedState.rendered['test-1']).toEqual('test-1');
- expect(response.rendered['test-2']).toEqual('test-2');
- expect(response.rendered['test-1']).toEqual('test-1');
+ expect(response.rendered).toBeDefined();
+});
+
+test('REQUEST_PALETTE_SUCCESS action removes id from isLoading [palettes-reducer-success-loading]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const stateWithLoading = update(initialPaletteState, {
+ isLoading: { $set: { test: true } },
+ });
+ const response = paletteReducer(stateWithLoading, {
+ type: REQUEST_PALETTE_SUCCESS,
+ id: 'test',
+ response: 'test-response',
+ });
+ expect(stateWithLoading.isLoading.test).toBeTruthy();
+ expect(response.isLoading.test).toBeUndefined();
+});
+
+test('INIT_SECOND_LAYER_GROUP action does not overwrite existing activeB [palettes-reducer-second-layer-group-no-overwrite]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const previousState = update(initialPaletteState, {
+ active: { $set: { 'terra-aod': 'active-value' } },
+ activeB: { $set: { 'aqua-cr': 'existing-b-value' } },
+ });
+ const response = paletteReducer(previousState, {
+ type: INIT_SECOND_LAYER_GROUP,
+ });
+ expect(response.activeB['aqua-cr']).toEqual('existing-b-value');
+ expect(response.activeB['terra-aod']).toBeUndefined();
+});
+
+test('SYNC_SECOND_LAYER_GROUP action merges active into activeB with B taking precedence [palettes-reducer-sync]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const previousState = update(initialPaletteState, {
+ active: { $set: { 'terra-aod': 'from-a', 'shared-layer': 'a-value' } },
+ activeB: { $set: { 'aqua-cr': 'from-b', 'shared-layer': 'b-value' } },
+ });
+ const response = paletteReducer(previousState, {
+ type: SYNC_SECOND_LAYER_GROUP,
+ });
+ expect(response.activeB['terra-aod']).toEqual('from-a');
+ expect(response.activeB['aqua-cr']).toEqual('from-b');
+ expect(response.activeB['shared-layer']).toEqual('b-value');
+});
+
+test('SYNC_SECOND_LAYER_GROUP action deep clones active and activeB [palettes-reducer-sync-clone]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const previousState = update(initialPaletteState, {
+ active: { $set: { 'terra-aod': { nested: 'value' } } },
+ activeB: { $set: {} },
+ });
+ const response = paletteReducer(previousState, {
+ type: SYNC_SECOND_LAYER_GROUP,
+ });
+ expect(response.activeB['terra-aod']).toEqual({ nested: 'value' });
+ expect(response.activeB['terra-aod']).not.toBe(previousState.active['terra-aod']);
+});
+
+test('SET_DISABLED_CLASSIFICATION action updates active palette Object [palettes-reducer-disabled-classification]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: SET_DISABLED_CLASSIFICATION,
+ layerId: 'terra-aod',
+ groupName: 'active',
+ palettes: { 'terra-aod': config.palettes.rendered['terra-aod'] },
+ });
+ expect(initialPaletteState.active['terra-aod']).toEqual(undefined);
+ expect(response.active['terra-aod']).toBeDefined();
+});
+
+test('SET_DISABLED_CLASSIFICATION action updates activeB when groupName is activeB [palettes-reducer-disabled-classification-b]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: SET_DISABLED_CLASSIFICATION,
+ layerId: 'terra-aod',
+ groupName: 'activeB',
+ palettes: { 'terra-aod': config.palettes.rendered['terra-aod'] },
+ });
+ expect(initialPaletteState.activeB['terra-aod']).toEqual(undefined);
+ expect(response.activeB['terra-aod']).toBeDefined();
+});
+
+test('CLEAR_CUSTOM action with no palettes sets empty object [palettes-reducer-clear-custom-empty]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: CLEAR_CUSTOM,
+ groupName: 'active',
+ });
+ expect(response.active).toEqual({});
+});
+
+test('SET_CUSTOM action updates activeB when groupName is activeB [palettes-reducer-set-custom-b]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: SET_CUSTOM,
+ layerId: 'terra-aod',
+ groupName: 'activeB',
+ palettes: { 'terra-aod': config.palettes.rendered['terra-aod'] },
+ });
+ expect(initialPaletteState.activeB['terra-aod']).toEqual(undefined);
+ expect(response.activeB['terra-aod']).toBeDefined();
+});
+
+test('LOADED_CUSTOM_PALETTES action updates custom palettes [palettes-reducer-loaded-custom]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const newCustom = { 'my-custom': { colors: ['ff0000ff'] } };
+ const response = paletteReducer(initialPaletteState, {
+ type: LOADED_CUSTOM_PALETTES,
+ custom: newCustom,
+ });
+ expect(response.custom['my-custom']).toEqual({ colors: ['ff0000ff'] });
+});
+
+test('LOADED_CUSTOM_PALETTES action with no custom sets empty object [palettes-reducer-loaded-custom-empty]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const stateWithCustom = update(initialPaletteState, {
+ custom: { $set: { 'red-1': config.palettes.custom['red-1'] } },
+ });
+ const response = paletteReducer(stateWithCustom, {
+ type: LOADED_CUSTOM_PALETTES,
+ });
+ expect(response.custom).toEqual({});
+});
+
+test('default case returns existing state unchanged [palettes-reducer-default]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: 'UNKNOWN_ACTION_TYPE',
+ });
+ expect(response).toBe(initialPaletteState);
+});
+
+test('paletteReducer uses defaultPaletteState when no state is provided [palettes-reducer-default-state]', () => {
+ const response = paletteReducer(undefined, { type: 'UNKNOWN_ACTION_TYPE' });
+ expect(response).toEqual(defaultPaletteState);
+});
+
+test('getInitialPaletteState returns defaultPaletteState shape when config is empty [palettes-reducer-initial-empty]', () => {
+ const response = getInitialPaletteState({});
+ expect(response.rendered).toEqual({});
+ expect(response.custom).toEqual({});
+ expect(response.active).toEqual({});
+ expect(response.activeB).toEqual({});
+ expect(response.isLoading).toEqual({});
+ expect(response.tourStoryPalettes).toEqual({});
+});
+
+test('getInitialPaletteState populates rendered and custom from config [palettes-reducer-initial-config]', () => {
+ const response = getInitialPaletteState(config);
+ expect(response.rendered).toEqual(config.palettes.rendered);
+ expect(response.custom).toEqual(config.palettes.custom);
+});
+
+test('groupName defaults to active when not provided in action [palettes-reducer-groupname-default]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: SET_CUSTOM,
+ layerId: 'terra-aod',
+ palettes: { 'terra-aod': config.palettes.rendered['terra-aod'] },
+ });
+ expect(response.active['terra-aod']).toBeDefined();
+ expect(response.activeB['terra-aod']).toBeUndefined();
+});
+
+test('SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP action updates activeB when groupName is activeB [palettes-reducer-threshold-b]', () => {
+ const initialPaletteState = getInitialPaletteState(config);
+ const response = paletteReducer(initialPaletteState, {
+ type: SET_THRESHOLD_RANGE_SQUASH_AND_NOCLIP,
+ layerId: 'terra-aod',
+ groupName: 'activeB',
+ palettes: { 'terra-aod': config.palettes.rendered['terra-aod'] },
+ });
+ expect(initialPaletteState.activeB['terra-aod']).toEqual(undefined);
+ expect(response.activeB['terra-aod']).toBeDefined();
});
diff --git a/web/js/modules/palettes/selectors.test.js b/web/js/modules/palettes/selectors.test.js
index c4e1cdccf..2f460f491 100644
--- a/web/js/modules/palettes/selectors.test.js
+++ b/web/js/modules/palettes/selectors.test.js
@@ -1,3 +1,380 @@
-test('selectors module test', () => {
+import { assign, cloneDeep } from 'lodash';
+import update from 'immutability-helper';
+import fixtures from '../../fixtures';
+import { addLayer } from '../layers/selectors';
+import {
+ getRenderedPalette,
+ getPalette,
+ getPaletteLegend,
+ getPaletteLegends,
+ getDefaultLegend,
+ getCustomPalette,
+ getCount,
+ getLookup,
+ getKey,
+ getActivePalettes,
+ isPaletteAllowed,
+ isActive,
+ findIndex,
+ setCustomSelector,
+ setRange,
+ clearCustomSelector,
+ initDisabledSelector,
+ setDisabledSelector,
+ refreshDisabledSelector,
+} from './selectors';
+const config = fixtures.config();
+const baseState = fixtures.getState();
+
+let layers = addLayer('terra-aod', [], config.layers, {}, 0);
+layers = addLayer('aqua-cr', layers, config.layers, {}, 1);
+const stateWithLayers = update(baseState, {
+ layers: { active: { $set: layers } },
+});
+
+const buildState = (activePalettes = {}) => update(stateWithLayers, {
+ palettes: { active: { $set: activePalettes } },
+});
+
+describe('getRenderedPalette', () => {
+ test('returns the full rendered palette object when index is undefined', () => {
+ const palette = getRenderedPalette('terra-aod', undefined, buildState());
+ expect(palette).toBeDefined();
+ expect(palette.maps).toBeDefined();
+ });
+
+ test('returns the palette map at the given index', () => {
+ const palette = getRenderedPalette('terra-aod', 0, buildState());
+ expect(palette).toBeDefined();
+ expect(palette.entries).toBeDefined();
+ });
+
+ test('throws an error when the palette does not exist', () => {
+ expect(() => getRenderedPalette('non-existent-layer', 0, buildState())).toThrow();
+ });
+});
+
+describe('getPalette', () => {
+ test('returns rendered palette map when no active palette exists', () => {
+ const palette = getPalette('terra-aod', 0, 'active', buildState());
+ expect(palette).toBeDefined();
+ expect(palette.entries).toBeDefined();
+ });
+
+ test('returns custom active palette when it exists', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const testState = buildState(result);
+ const palette = getPalette('terra-aod', 0, 'active', testState);
+ expect(palette).toBeDefined();
+ });
+
+ test('defaults index to 0 when index is undefined', () => {
+ const palette = getPalette('terra-aod', undefined, 'active', buildState());
+ expect(palette).toBeDefined();
+ });
+
+ test('uses compare.activeString when group is not provided', () => {
+ const palette = getPalette('terra-aod', 0, undefined, buildState());
+ expect(palette).toBeDefined();
+ });
+});
+
+describe('getPaletteLegend', () => {
+ test('returns the legend of a palette', () => {
+ const legend = getPaletteLegend('terra-aod', 0, 'active', buildState());
+ expect(legend).toBeDefined();
+ });
+});
+
+describe('getPaletteLegends', () => {
+ test('returns an array of legends for all colormaps', () => {
+ const legends = getPaletteLegends('terra-aod', 'active', buildState());
+ expect(Array.isArray(legends)).toBe(true);
+ expect(legends.length).toBeGreaterThan(0);
+ });
+});
+
+describe('getDefaultLegend', () => {
+ test('returns the legend from the rendered palette at the given index', () => {
+ const legend = getDefaultLegend('terra-aod', 0, buildState());
+ expect(legend).toBeDefined();
+ });
+});
+
+describe('getCustomPalette', () => {
+ test('returns the custom palette by id', () => {
+ const palette = getCustomPalette('red-1', config.palettes.custom);
+ expect(palette).toBeDefined();
+ expect(palette.colors).toBeDefined();
+ });
+
+ test('throws an error when the custom palette does not exist', () => {
+ expect(() => getCustomPalette('non-existent', config.palettes.custom)).toThrow('Invalid palette: non-existent');
+ });
+});
+
+describe('getCount', () => {
+ test('returns the number of colormaps for a layer', () => {
+ const count = getCount('terra-aod', buildState());
+ expect(count).toBeGreaterThan(0);
+ });
+});
+
+describe('getLookup', () => {
+ test('returns lookup from active palette using provided group', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const testState = buildState(result);
+ const lookup = getLookup('terra-aod', 'active', testState);
+ expect(lookup).toBeDefined();
+ });
+
+ test('returns lookup using compare.activeString when group is not provided', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const testState = buildState(result);
+ const lookup = getLookup('terra-aod', undefined, testState);
+ expect(lookup).toBeDefined();
+ });
+});
+
+describe('isActive', () => {
+ test('returns the active palette entry when it exists', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const testState = buildState(result);
+ const active = isActive('terra-aod', 'active', testState);
+ expect(active).toBeDefined();
+ });
+
+ test('returns undefined when no active palette entry exists', () => {
+ const result = isActive('terra-aod', 'active', buildState());
+ expect(result).toBeUndefined();
+ });
+
+ test('uses compare.activeString when group is not provided', () => {
+ const result = isActive('terra-aod', undefined, buildState());
+ expect(result).toBeUndefined();
+ });
+});
+
+describe('getKey', () => {
+ test('returns empty string when palette is not active', () => {
+ const key = getKey('terra-aod', 'active', buildState());
+ expect(key).toEqual('');
+ });
+
+ test('returns palette key when custom palette is active', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const testState = buildState(result);
+ const key = getKey('terra-aod', 'active', testState);
+ expect(key).toContain('palette=red-1');
+ });
+
+ test('returns key with min when min is set', () => {
+ const result = setRange('terra-aod', { min: 1 }, 0, {}, buildState());
+ const testState = buildState(result);
+ const key = getKey('terra-aod', 'active', testState);
+ expect(key).toContain('min=');
+ });
+
+ test('returns key with max when max is set', () => {
+ const result = setRange('terra-aod', { max: 1 }, 0, {}, buildState());
+ const testState = buildState(result);
+ const key = getKey('terra-aod', 'active', testState);
+ expect(key).toContain('max=');
+ });
+
+ test('returns key with squash when squash is set', () => {
+ const result = setRange('terra-aod', { max: 1, squash: true }, 0, {}, buildState());
+ const testState = buildState(result);
+ const key = getKey('terra-aod', 'active', testState);
+ expect(key).toContain('squash');
+ });
+
+ test('returns key with noclip when noclip is set', () => {
+ const result = setRange('terra-aod', { max: 1, noclip: true }, 0, {}, buildState());
+ const testState = buildState(result);
+ const key = getKey('terra-aod', 'active', testState);
+ expect(key).toContain('noclip');
+ });
+
+ test('uses compare.activeString when groupStr is not provided', () => {
+ const key = getKey('terra-aod', undefined, buildState());
+ expect(key).toEqual('');
+ });
+});
+
+describe('getActivePalettes', () => {
+ test('returns the active palettes for the given activeString', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const testState = buildState(result);
+ const active = getActivePalettes(testState, 'active');
+ expect(active['terra-aod']).toBeDefined();
+ });
+});
+
+describe('isPaletteAllowed', () => {
+ test('returns true for a layer with a non-immutable palette', () => {
+ const result = isPaletteAllowed('terra-aod', config);
+ expect(result).toBe(true);
+ });
+});
+
+describe('findIndex', () => {
+ test('returns the index of a matching value in the palette entries', () => {
+ const { values } = config.palettes.rendered['terra-aod'].maps[0].entries;
+ const firstValue = values[0];
+ const result = findIndex('terra-aod', firstValue, 0, 'active', buildState());
+ expect(result).toEqual(0);
+ });
+
+ test('returns undefined when value is not found', () => {
+ const result = findIndex('terra-aod', 'non-existent-value', 0, 'active', buildState());
+ expect(result).toBeUndefined();
+ });
+});
+
+describe('setCustomSelector', () => {
+ test('sets a custom palette and returns a lookup', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ expect(result['terra-aod']).toBeDefined();
+ expect(result['terra-aod'].lookup).toBeDefined();
+ expect(result['terra-aod'].maps[0].custom).toEqual('red-1');
+ });
+
+ test('throws an error for an invalid layer', () => {
+ expect(() => setCustomSelector('non-existent', 'red-1', 0, 'active', buildState())).toThrow('Invalid layer: non-existent');
+ });
+
+ test('returns early when palette and lookup are already set to the same custom id', () => {
+ const firstResult = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const secondState = buildState(firstResult);
+ const secondResult = setCustomSelector('terra-aod', 'red-1', 0, 'active', secondState);
+ expect(secondResult['terra-aod'].maps[0].custom).toEqual('red-1');
+ });
+
+ test('defaults index to 0 when index is undefined', () => {
+ const result = setCustomSelector('terra-aod', 'red-1', undefined, 'active', buildState());
+ expect(result['terra-aod'].maps[0].custom).toEqual('red-1');
+ });
+});
+
+describe('setRange', () => {
+ test('sets min value and produces a lookup', () => {
+ const result = setRange('terra-aod', { min: 1 }, 0, {}, buildState());
+ expect(result['terra-aod']).toBeDefined();
+ expect(result['terra-aod'].maps[0].min).toEqual(1);
+ expect(result['terra-aod'].lookup).toBeDefined();
+ });
+
+ test('sets max value and produces a lookup', () => {
+ const result = setRange('terra-aod', { max: 1 }, 0, {}, buildState());
+ expect(result['terra-aod'].maps[0].max).toEqual(1);
+ expect(result['terra-aod'].lookup).toBeDefined();
+ });
+
+ test('sets squash and max and produces a lookup', () => {
+ const result = setRange('terra-aod', { max: 1, squash: true }, 0, {}, buildState());
+ expect(result['terra-aod'].maps[0].squash).toEqual(true);
+ expect(result['terra-aod'].lookup).toBeDefined();
+ });
+
+ test('sets noclip and max and produces a lookup', () => {
+ const result = setRange('terra-aod', { max: 1, noclip: true }, 0, {}, buildState());
+ expect(result['terra-aod'].maps[0].noclip).toEqual(true);
+ expect(result['terra-aod'].lookup).toBeDefined();
+ });
+
+ test('converts min of 0 to undefined and does not produce a lookup', () => {
+ const result = setRange('terra-aod', { min: 0 }, 0, {}, buildState());
+ expect(result['terra-aod']).toBeUndefined();
+ });
+
+ test('converts max at last value index to undefined and does not produce a lookup', () => {
+ const lastIndex = config.palettes.rendered['terra-aod'].maps[0].entries.values.length - 1;
+ const result = setRange('terra-aod', { max: lastIndex }, 0, {}, buildState());
+ expect(result['terra-aod']).toBeUndefined();
+ });
+
+ test('defaults index to 0 when index is undefined', () => {
+ const result = setRange('terra-aod', { min: 1 }, undefined, {}, buildState());
+ expect(result['terra-aod'].maps[0].min).toEqual(1);
+ });
+});
+
+describe('clearCustomSelector', () => {
+ test('clears custom palette and returns palettes without layerId when no threshold', () => {
+ const withCustom = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const result = clearCustomSelector('terra-aod', 0, withCustom, buildState());
+ expect(result['terra-aod']).toBeUndefined();
+ });
+
+ test('returns original palettes when layer has no active entry', () => {
+ const palettes = {};
+ const result = clearCustomSelector('terra-aod', 0, palettes, buildState());
+ expect(result).toEqual(palettes);
+ });
+
+ test('returns original palettes when no custom is set', () => {
+ const terraAOD = assign({}, config.palettes.rendered['terra-aod']);
+ const palettes = { 'terra-aod': terraAOD };
+ const result = clearCustomSelector('terra-aod', 0, palettes, buildState());
+ expect(result).toEqual(palettes);
+ });
+
+ test('defaults index to 0 when index is undefined', () => {
+ const withCustom = setCustomSelector('terra-aod', 'red-1', 0, 'active', buildState());
+ const result = clearCustomSelector('terra-aod', undefined, withCustom, buildState());
+ expect(result['terra-aod']).toBeUndefined();
+ });
+});
+
+describe('initDisabledSelector', () => {
+ test('sets disabled array from hyphen-separated string', () => {
+ const result = initDisabledSelector('terra-aod', '0-1', 0, {}, buildState());
+ expect(result).toBeDefined();
+ });
+
+ test('sets empty disabled array when disabledStr is empty string', () => {
+ const result = initDisabledSelector('terra-aod', '', 0, {}, buildState());
+ expect(result).toBeDefined();
+ });
+
+ test('sets empty disabled array when disabledStr is null', () => {
+ const result = initDisabledSelector('terra-aod', null, 0, {}, buildState());
+ expect(result).toBeDefined();
+ });
+});
+
+describe('setDisabledSelector', () => {
+ test('adds a classIndex to the disabled array when not already present', () => {
+ const result = setDisabledSelector('terra-aod', 0, 0, {}, buildState());
+ expect(result).toBeDefined();
+ });
+
+ test('removes a classIndex from the disabled array when already present', () => {
+ const firstResult = setDisabledSelector('terra-aod', 0, 0, {}, buildState());
+ const firstState = buildState(firstResult);
+ const secondResult = setDisabledSelector('terra-aod', 0, 0, firstResult, firstState);
+ expect(secondResult).toBeDefined();
+ });
+
+ test('sets disabled to empty array when classIndex is NaN', () => {
+ const result = setDisabledSelector('terra-aod', NaN, 0, {}, buildState());
+ expect(result).toBeDefined();
+ });
+});
+
+describe('refreshDisabledSelector', () => {
+ test('returns palettes with layerId when min is set and disabled array is non-empty', () => {
+ const withMin = setRange('terra-aod', { min: 1 }, 0, {}, buildState());
+ const testState = buildState(withMin);
+ const result = refreshDisabledSelector('terra-aod', [0], 0, cloneDeep(withMin), testState);
+ expect(result['terra-aod']).toBeDefined();
+ expect(result['terra-aod'].lookup).toBeDefined();
+ });
+
+ test('returns palettes without layerId when no lookup condition is met', () => {
+ const result = refreshDisabledSelector('terra-aod', [], 0, {}, buildState());
+ expect(result['terra-aod']).toBeUndefined();
+ });
});
diff --git a/web/js/modules/palettes/util.test.js b/web/js/modules/palettes/util.test.js
index 09baff26b..19268d10f 100644
--- a/web/js/modules/palettes/util.test.js
+++ b/web/js/modules/palettes/util.test.js
@@ -4,6 +4,17 @@ import {
hasCustomTypePalette,
loadPalettes,
mapLocationToPaletteState,
+ palettesTranslate,
+ getMinValue,
+ getMaxValue,
+ hasCustomPaletteInActiveProjection,
+ getPaletteAttributeArray,
+ parseLegacyPalettes,
+ lookup,
+ drawPaletteOnCanvas,
+ drawSidebarPaletteOnCanvas,
+ drawTravelModePaletteOnCanvas,
+ drawTicksOnCanvas,
} from './util';
import fixtures from '../../fixtures';
@@ -27,6 +38,11 @@ test('hasCustomTypePalette func determines if custom palette is in string [palet
expect(bool).toBeTruthy();
});
+test('hasCustomTypePalette returns false for string with no palette attributes', () => {
+ const bool = hasCustomTypePalette('terra-aod(hidden,opacity=0.54)');
+ expect(bool).toBeFalsy();
+});
+
test('loadPalettes func updates state with correct palette attributes [palettes-load-palettes]', () => {
const updatedState = update(state, {
layers: {
@@ -45,6 +61,31 @@ test('loadPalettes func updates state with correct palette attributes [palettes-
expect(colorMap.noclip).toEqual(true);
});
+test('loadPalettes with l1 param loads activeB palettes', () => {
+ const layerStringB = 'terra-aod(palette=red-1)';
+ const layerArrayB = layersParse12(layerStringB, config);
+ const updatedState = update(state, {
+ layers: {
+ active: { layers: { $set: layerArrayB } },
+ activeB: { layers: { $set: layerArrayB } },
+ },
+ });
+ const loadedState = loadPalettes({ l1: layerStringB }, updatedState);
+ expect(loadedState).toBeDefined();
+});
+
+test('loadPalettes with no palette attributes returns state unchanged', () => {
+ const layerStringPlain = 'terra-aod,mask';
+ const layerArrayPlain = layersParse12(layerStringPlain, config);
+ const updatedState = update(state, {
+ layers: {
+ active: { layers: { $set: layerArrayPlain } },
+ },
+ });
+ const loadedState = loadPalettes({ l: layerStringPlain }, updatedState);
+ expect(loadedState.palettes.active['terra-aod']).toBeUndefined();
+});
+
describe('permalink 1.1', () => {
test('parses palette for valid layer [palettes-parse-permalink]', () => {
const parameters = {
@@ -123,3 +164,281 @@ describe('permalink 1.1', () => {
expect(stateFromLocation.layers.active.layers.length).toBe(1);
});
});
+
+test('mapLocationToPaletteState returns state unchanged when no l or l1 or palettes param', () => {
+ const result = mapLocationToPaletteState({}, state, state, config);
+ expect(result).toEqual(state);
+});
+
+test('mapLocationToPaletteState with only palettes param and no active layers does not crash', () => {
+ const parameters = { palettes: 'terra-aod,red-1' };
+ const result = mapLocationToPaletteState(parameters, state, state, config);
+ expect(result).toBeDefined();
+});
+
+test('parseLegacyPalettes sets custom palette on matching active layer', () => {
+ const parameters = { palettes: 'terra-aod,blue-1' };
+ const layersState = update(state, {
+ layers: {
+ active: {
+ layers: { $set: layersParse12('terra-aod', config) },
+ },
+ },
+ });
+ const result = parseLegacyPalettes(parameters, layersState, state, config);
+ const layer = result.layers.active.layers[0];
+ expect(layer.custom).toBe('blue-1');
+});
+
+test('parseLegacyPalettes does not overwrite an existing custom on a layer', () => {
+ const parameters = { palettes: 'terra-aod,blue-1' };
+ const layerArray = layersParse12('terra-aod', config);
+ const layerWithCustom = update(layerArray[0], { custom: { $set: 'red-1' } });
+ const layersState = update(state, {
+ layers: {
+ active: {
+ layers: { $set: [layerWithCustom] },
+ },
+ },
+ });
+ const result = parseLegacyPalettes(parameters, layersState, state, config);
+ expect(result.layers.active.layers[0].custom).toBe('red-1');
+});
+
+test('parseLegacyPalettes ignores a palette for a layer not in active layers', () => {
+ const parameters = { palettes: 'non-existent-layer,blue-1' };
+ const layersState = update(state, {
+ layers: {
+ active: {
+ layers: { $set: layersParse12('terra-aod', config) },
+ },
+ },
+ });
+ const result = parseLegacyPalettes(parameters, layersState, state, config);
+ expect(result.layers.active.layers[0].custom).toBeUndefined();
+});
+
+test('parseLegacyPalettes handles multiple tilde-separated pairs', () => {
+ const parameters = { palettes: 'terra-aod,blue-1~aqua-aod,red-1' };
+ const layersState = update(state, {
+ layers: {
+ active: {
+ layers: { $set: layersParse12('terra-aod,aqua-aod', config) },
+ },
+ },
+ });
+ const result = parseLegacyPalettes(parameters, layersState, state, config);
+ expect(result.layers.active.layers[0].custom).toBe('blue-1');
+ expect(result.layers.active.layers[1].custom).toBe('red-1');
+});
+
+test('palettesTranslate maps source colors to target palette', () => {
+ const source = ['ff0000ff', '00ff00ff', '0000ffff'];
+ const target = ['aaaaaaff', 'bbbbbbff', 'ccccccff'];
+ const result = palettesTranslate(source, target);
+ expect(result.length).toBe(3);
+ expect(result[0]).toBe('aaaaaaff');
+});
+
+test('getMinValue returns first element of array', () => {
+ expect(getMinValue(['1', '2', '3'])).toBe('1');
+});
+
+test('getMinValue returns value when input has no length', () => {
+ expect(getMinValue(5)).toBe(5);
+});
+
+test('getMaxValue returns last element of array', () => {
+ expect(getMaxValue(['1', '2', '3'])).toBe('3');
+});
+
+test('getMaxValue returns value when input has no length', () => {
+ expect(getMaxValue(5)).toBe(5);
+});
+
+test('hasCustomPaletteInActiveProjection returns true when active layer has a custom palette', () => {
+ const activeLayers = [{ id: 'terra-aod' }];
+ const activePalettes = { 'terra-aod': { maps: [] } };
+ expect(hasCustomPaletteInActiveProjection(activeLayers, activePalettes)).toBe(true);
+});
+
+test('hasCustomPaletteInActiveProjection returns false when no active layer has a custom palette', () => {
+ const activeLayers = [{ id: 'terra-aod' }];
+ const activePalettes = {};
+ expect(hasCustomPaletteInActiveProjection(activeLayers, activePalettes)).toBe(false);
+});
+
+test('hasCustomPaletteInActiveProjection returns false for empty layers array', () => {
+ expect(hasCustomPaletteInActiveProjection([], {})).toBe(false);
+});
+
+test('lookup builds a lookup table from source and target palettes', () => {
+ const source = { colors: ['ff0000ff', '00ff00ff'] };
+ const target = { colors: ['aaaaaaff', 'bbbbbbff'] };
+ const result = lookup(source, target);
+ expect(Object.keys(result).length).toBe(2);
+ const firstKey = '255,0,0,255';
+ expect(result[firstKey]).toBeDefined();
+ expect(result[firstKey].r).toBe(170);
+});
+
+test('getPaletteAttributeArray returns empty array when palette has no custom attributes', () => {
+ const layerStringPlain = 'terra-aod';
+ const layerArrayPlain = layersParse12(layerStringPlain, config);
+ const updatedState = update(state, {
+ layers: { active: { layers: { $set: layerArrayPlain } } },
+ });
+ const loadedState = loadPalettes({ l: layerStringPlain }, updatedState);
+ const palettes = loadedState.palettes.active;
+ if (!palettes['terra-aod']) {
+ expect(palettes['terra-aod']).toBeUndefined();
+ } else {
+ const result = getPaletteAttributeArray('terra-aod', palettes, loadedState);
+ expect(Array.isArray(result)).toBe(true);
+ }
+});
+
+test('getPaletteAttributeArray returns array of palette attributes for layer with custom palette', () => {
+ const layerString = 'terra-aod(palette=red-1,min=1,max=2,squash=true,noclip=true)';
+ const layerArray = layersParse12(layerString, config);
+ const updatedState = update(state, {
+ layers: { active: { layers: { $set: layerArray } } },
+ });
+ const loadedState = loadPalettes({ l: layerString }, updatedState);
+ const palettes = loadedState.palettes.active;
+ const result = getPaletteAttributeArray('terra-aod', palettes, loadedState);
+ expect(result).toEqual([
+ { id: 'palette', value: 'red-1' },
+ { id: 'min', value: '1' },
+ { id: 'squash', value: 'true' },
+ { id: 'noclip', value: 'true' },
+ ]);
+});
+
+describe('drawPaletteOnCanvas', () => {
+ const makeMockCtx = () => ({
+ fillStyle: '',
+ fillRect: jest.fn(),
+ rect: jest.fn(),
+ stroke: jest.fn(),
+ strokeStyle: '',
+ beginPath: jest.fn(),
+ moveTo: jest.fn(),
+ lineTo: jest.fn(),
+ closePath: jest.fn(),
+ lineWidth: 0,
+ });
+
+ test('fills background and draws color bins when colors provided', () => {
+ const ctx = makeMockCtx();
+ drawPaletteOnCanvas(ctx, ['ff0000ff', '00ff00ff', '0000ffff'], 300, 20);
+ expect(ctx.fillRect).toHaveBeenCalled();
+ });
+
+ test('only fills background when no colors provided', () => {
+ const ctx = makeMockCtx();
+ drawPaletteOnCanvas(ctx, null, 300, 20);
+ expect(ctx.fillRect).toHaveBeenCalledTimes(1);
+ });
+
+ test('draws with empty colors array', () => {
+ const ctx = makeMockCtx();
+ drawPaletteOnCanvas(ctx, [], 300, 20);
+ expect(ctx.fillRect).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('drawSidebarPaletteOnCanvas', () => {
+ const makeMockCtx = () => ({
+ fillStyle: '',
+ fillRect: jest.fn(),
+ rect: jest.fn(),
+ stroke: jest.fn(),
+ strokeStyle: '',
+ });
+
+ test('fills background and draws color bins when colors provided', () => {
+ const ctx = makeMockCtx();
+ drawSidebarPaletteOnCanvas(ctx, ['ff0000ff', '00ff00ff'], 300);
+ expect(ctx.fillRect).toHaveBeenCalled();
+ expect(ctx.rect).toHaveBeenCalled();
+ expect(ctx.stroke).toHaveBeenCalled();
+ });
+
+ test('only fills background when no colors provided', () => {
+ const ctx = makeMockCtx();
+ drawSidebarPaletteOnCanvas(ctx, null, 300);
+ expect(ctx.fillRect).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('drawTravelModePaletteOnCanvas', () => {
+ const makeMockCtx = () => ({
+ fillStyle: '',
+ fillRect: jest.fn(),
+ rect: jest.fn(),
+ stroke: jest.fn(),
+ strokeStyle: '',
+ });
+
+ test('fills background and draws color bins when colors provided', () => {
+ const ctx = makeMockCtx();
+ drawTravelModePaletteOnCanvas(ctx, ['ff0000ff', '00ff00ff'], 300, 20);
+ expect(ctx.fillRect).toHaveBeenCalled();
+ expect(ctx.rect).toHaveBeenCalled();
+ expect(ctx.stroke).toHaveBeenCalled();
+ });
+
+ test('only fills background when no colors provided', () => {
+ const ctx = makeMockCtx();
+ drawTravelModePaletteOnCanvas(ctx, null, 300, 20);
+ expect(ctx.fillRect).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('drawTicksOnCanvas', () => {
+ const makeMockCtx = () => ({
+ fillStyle: '',
+ fillRect: jest.fn(),
+ beginPath: jest.fn(),
+ moveTo: jest.fn(),
+ lineTo: jest.fn(),
+ stroke: jest.fn(),
+ closePath: jest.fn(),
+ strokeStyle: '',
+ lineWidth: 0,
+ });
+
+ test('draws ticks when legend has ticks and more than 100 bins', () => {
+ const colors = new Array(101).fill('ff0000ff');
+ const legend = { colors, ticks: [10, 50, 90] };
+ const ctx = makeMockCtx();
+ drawTicksOnCanvas(ctx, legend, 500);
+ expect(ctx.beginPath).toHaveBeenCalled();
+ expect(ctx.stroke).toHaveBeenCalled();
+ });
+
+ test('does not draw ticks when bins are 100 or fewer', () => {
+ const colors = new Array(100).fill('ff0000ff');
+ const legend = { colors, ticks: [10, 50] };
+ const ctx = makeMockCtx();
+ drawTicksOnCanvas(ctx, legend, 500);
+ expect(ctx.beginPath).not.toHaveBeenCalled();
+ });
+
+ test('does not draw ticks when ticks array is empty', () => {
+ const colors = new Array(101).fill('ff0000ff');
+ const legend = { colors, ticks: [] };
+ const ctx = makeMockCtx();
+ drawTicksOnCanvas(ctx, legend, 500);
+ expect(ctx.beginPath).not.toHaveBeenCalled();
+ });
+
+ test('does not draw ticks when ticks is undefined', () => {
+ const colors = new Array(101).fill('ff0000ff');
+ const legend = { colors };
+ const ctx = makeMockCtx();
+ drawTicksOnCanvas(ctx, legend, 500);
+ expect(ctx.beginPath).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/js/modules/product-picker/actions.test.js b/web/js/modules/product-picker/actions.test.js
index 22bc698b0..378f971bc 100644
--- a/web/js/modules/product-picker/actions.test.js
+++ b/web/js/modules/product-picker/actions.test.js
@@ -1,3 +1,279 @@
-test('actions module test', () => {
+import {
+ initState,
+ saveSearchState,
+ collapseFacet,
+ selectCategoryType,
+ selectMeasurement,
+ selectSource,
+ selectLayer,
+ showMeasurements,
+ toggleFeatureTab,
+ toggleMeasurementsTab,
+ toggleRecentLayersTab,
+ toggleSearchMode,
+ toggleCategoryMode,
+ toggleMobileFacets,
+ clearRecentLayers,
+ clearSingleRecentLayer,
+ onProjectionSwitch,
+ resetProductPickerState,
+} from './actions';
+import initSearch from './search-config';
+import {
+ getRecentLayers,
+ clearRecentLayers as clearRecentFromLocalStorage,
+ clearSingleRecentLayer as clearSingleRecentLayerFromLocalStorage,
+} from './util';
+
+import {
+ SAVE_SEARCH_STATE,
+ INIT_STATE,
+ COLLAPSE_FACET,
+ SELECT_CATEGORY_TYPE,
+ SELECT_MEASUREMENT,
+ SELECT_SOURCE,
+ SELECT_LAYER,
+ SHOW_MEASUREMENTS,
+ TOGGLE_FEATURED_TAB,
+ TOGGLE_MEASUREMENTS_TAB,
+ TOGGLE_RECENT_LAYERS_TAB,
+ TOGGLE_SEARCH_MODE,
+ TOGGLE_CATEGORY_MODE,
+ TOGGLE_MOBILE_FACETS,
+ CLEAR_RECENT_LAYERS,
+ CLEAR_SINGLE_RECENT_LAYER,
+ PROJ_SWITCH,
+ RESET_STATE,
+} from './constants';
+
+jest.mock('./search-config');
+jest.mock('./util', () => ({
+ getRecentLayers: jest.fn(),
+ clearRecentLayers: jest.fn(),
+ clearSingleRecentLayer: jest.fn(),
+}));
+
+describe('actions', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('initState', () => {
+ it('dispatches INIT_STATE with searchConfig and projection', () => {
+ const mockState = { proj: { id: 'geographic' } };
+ const mockSearchConfig = { index: {} };
+ initSearch.mockReturnValue(mockSearchConfig);
+
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue(mockState);
+
+ initState()(dispatch, getState);
+
+ expect(getState).toHaveBeenCalled();
+ expect(initSearch).toHaveBeenCalledWith(mockState);
+ expect(dispatch).toHaveBeenCalledWith({
+ type: INIT_STATE,
+ searchConfig: mockSearchConfig,
+ projection: 'geographic',
+ });
+ });
+ });
+
+ describe('saveSearchState', () => {
+ it('returns SAVE_SEARCH_STATE action with filters, searchTerm, and searchConfig', () => {
+ const filters = { category: 'Atmosphere' };
+ const searchTerm = 'aerosol';
+ const searchConfig = { index: {} };
+
+ expect(saveSearchState(filters, searchTerm, searchConfig)).toEqual({
+ type: SAVE_SEARCH_STATE,
+ filters,
+ searchTerm,
+ searchConfig,
+ });
+ });
+ });
+
+ describe('collapseFacet', () => {
+ it('returns COLLAPSE_FACET action with field', () => {
+ expect(collapseFacet('category')).toEqual({
+ type: COLLAPSE_FACET,
+ field: 'category',
+ });
+ });
+ });
+
+ describe('selectCategoryType', () => {
+ it('returns SELECT_CATEGORY_TYPE action with value', () => {
+ expect(selectCategoryType('science')).toEqual({
+ type: SELECT_CATEGORY_TYPE,
+ value: 'science',
+ });
+ });
+ });
+
+ describe('selectMeasurement', () => {
+ it('returns SELECT_MEASUREMENT action with value', () => {
+ expect(selectMeasurement('aerosol')).toEqual({
+ type: SELECT_MEASUREMENT,
+ value: 'aerosol',
+ });
+ });
+ });
+
+ describe('selectSource', () => {
+ it('returns SELECT_SOURCE action with value', () => {
+ expect(selectSource('MODIS')).toEqual({
+ type: SELECT_SOURCE,
+ value: 'MODIS',
+ });
+ });
+ });
+
+ describe('selectLayer', () => {
+ it('returns SELECT_LAYER action with value', () => {
+ expect(selectLayer('MODIS_Terra_CorrectedReflectance_TrueColor')).toEqual({
+ type: SELECT_LAYER,
+ value: 'MODIS_Terra_CorrectedReflectance_TrueColor',
+ });
+ });
+ });
+
+ describe('showMeasurements', () => {
+ it('returns SHOW_MEASUREMENTS action with value', () => {
+ expect(showMeasurements(true)).toEqual({
+ type: SHOW_MEASUREMENTS,
+ value: true,
+ });
+ });
+ });
+
+ describe('toggleFeatureTab', () => {
+ it('dispatches TOGGLE_FEATURED_TAB with config from state', () => {
+ const mockConfig = { projections: { geographic: {} } };
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ config: mockConfig });
+
+ toggleFeatureTab()(dispatch, getState);
+
+ expect(getState).toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({
+ type: TOGGLE_FEATURED_TAB,
+ config: mockConfig,
+ });
+ });
+ });
+
+ describe('toggleMeasurementsTab', () => {
+ it('returns TOGGLE_MEASUREMENTS_TAB action', () => {
+ expect(toggleMeasurementsTab()).toEqual({
+ type: TOGGLE_MEASUREMENTS_TAB,
+ });
+ });
+ });
+
+ describe('toggleRecentLayersTab', () => {
+ it('dispatches TOGGLE_RECENT_LAYERS_TAB with recentLayers', () => {
+ const layerConfig = { MODIS_Terra: {} };
+ const mockRecentLayers = [{ id: 'MODIS_Terra' }];
+ getRecentLayers.mockReturnValue(mockRecentLayers);
+
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({
+ layers: { layerConfig },
+ proj: { id: 'geographic' },
+ });
+
+ toggleRecentLayersTab()(dispatch, getState);
+
+ expect(getRecentLayers).toHaveBeenCalledWith(layerConfig, 'geographic');
+ expect(dispatch).toHaveBeenCalledWith({
+ type: TOGGLE_RECENT_LAYERS_TAB,
+ recentLayers: mockRecentLayers,
+ });
+ });
+ });
+
+ describe('toggleSearchMode', () => {
+ it('returns TOGGLE_SEARCH_MODE action', () => {
+ expect(toggleSearchMode()).toEqual({
+ type: TOGGLE_SEARCH_MODE,
+ });
+ });
+ });
+
+ describe('toggleCategoryMode', () => {
+ it('returns TOGGLE_CATEGORY_MODE action', () => {
+ expect(toggleCategoryMode()).toEqual({
+ type: TOGGLE_CATEGORY_MODE,
+ });
+ });
+ });
+
+ describe('toggleMobileFacets', () => {
+ it('returns TOGGLE_MOBILE_FACETS action', () => {
+ expect(toggleMobileFacets()).toEqual({
+ type: TOGGLE_MOBILE_FACETS,
+ });
+ });
+ });
+
+ describe('clearRecentLayers', () => {
+ it('calls clearRecentFromLocalStorage and returns CLEAR_RECENT_LAYERS action', () => {
+ const result = clearRecentLayers();
+
+ expect(clearRecentFromLocalStorage).toHaveBeenCalled();
+ expect(result).toEqual({
+ type: CLEAR_RECENT_LAYERS,
+ });
+ });
+ });
+
+ describe('clearSingleRecentLayer', () => {
+ it('calls clearSingleRecentLayerFromLocalStorage and dispatches CLEAR_SINGLE_RECENT_LAYER', () => {
+ const layer = { id: 'MODIS_Terra' };
+ const layerConfig = { MODIS_Terra: {} };
+ const mockRecentLayers = [{ id: 'MODIS_Terra_2' }];
+ const projections = { geographic: {}, arctic: {} };
+
+ getRecentLayers.mockReturnValue(mockRecentLayers);
+
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({
+ layers: { layerConfig },
+ proj: { id: 'geographic' },
+ config: { projections },
+ });
+
+ clearSingleRecentLayer(layer)(dispatch, getState);
+
+ expect(clearSingleRecentLayerFromLocalStorage).toHaveBeenCalledWith(
+ layer,
+ Object.keys(projections),
+ );
+ expect(getRecentLayers).toHaveBeenCalledWith(layerConfig, 'geographic');
+ expect(dispatch).toHaveBeenCalledWith({
+ type: CLEAR_SINGLE_RECENT_LAYER,
+ recentLayers: mockRecentLayers,
+ });
+ });
+ });
+
+ describe('onProjectionSwitch', () => {
+ it('returns PROJ_SWITCH action with projection', () => {
+ expect(onProjectionSwitch('arctic')).toEqual({
+ type: PROJ_SWITCH,
+ projection: 'arctic',
+ });
+ });
+ });
+
+ describe('resetProductPickerState', () => {
+ it('returns RESET_STATE action', () => {
+ expect(resetProductPickerState()).toEqual({
+ type: RESET_STATE,
+ });
+ });
+ });
});
diff --git a/web/js/modules/product-picker/format-config.test.js b/web/js/modules/product-picker/format-config.test.js
index 40b9a58b1..9e805fc75 100644
--- a/web/js/modules/product-picker/format-config.test.js
+++ b/web/js/modules/product-picker/format-config.test.js
@@ -1,3 +1,387 @@
-test('format-config module test', () => {
+import buildLayerFacetProps from './format-config';
+import { available } from '../layers/selectors';
+import { formatDisplayDate } from '../date/util';
+jest.mock('../layers/selectors', () => ({
+ available: jest.fn(),
+}));
+
+jest.mock('../../util/util', () => ({
+ __esModule: true,
+ default: {
+ decodeHTML: jest.fn((val) => val.replace('&amp;', '&')),
+ },
+}));
+
+jest.mock('../date/util', () => ({
+ formatDisplayDate: jest.fn(() => '2024-01-01'),
+}));
+
+const selectedDate = new Date('2024-01-01');
+
+function buildConfig(layerOverrides = {}, extra = {}) {
+ const layers = {
+ layer1: {
+ id: 'layer1',
+ type: 'wmts',
+ subtitle: 'Source A',
+ ...layerOverrides,
+ },
+ };
+ return {
+ layers,
+ measurements: {
+ 'Aerosol Optical Depth': {
+ sources: {
+ MODIS: { settings: ['layer1'] },
+ },
+ },
+ },
+ categories: {
+ atmosphere: {
+ Aerosols: {
+ measurements: ['Aerosol Optical Depth'],
+ },
+ },
+ },
+ ...extra,
+ };
+}
+
+describe('buildLayerFacetProps', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ available.mockReturnValue(false);
+ });
+
+ describe('setTypeProp - raster types', () => {
+ it.each(['wms', 'wmts', 'xyz', 'composite:wmts', 'esriMapServer'])(
+ 'sets type to "Raster (Mosaicked)" for type "%s"',
+ (type) => {
+ const config = buildConfig({ type });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].type).toBe('Raster (Mosaicked)');
+ },
+ );
+
+ it('sets type to "Raster (Granule)" for granule type', () => {
+ const config = buildConfig({ type: 'granule' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].type).toBe('Raster (Granule)');
+ });
+
+ it('sets type to "Dynamically-rendered" for titiler type', () => {
+ const config = buildConfig({ type: 'titiler' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].type).toBe('Dynamically-rendered');
+ });
+
+ it('sets type to "Vector" for vector type', () => {
+ const config = buildConfig({ type: 'vector' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].type).toBe('Vector');
+ });
+
+ it('sets type to "Vector" for indexedVector type', () => {
+ const config = buildConfig({ type: 'indexedVector' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].type).toBe('Vector');
+ });
+
+ it('capitalizes an unknown type', () => {
+ const config = buildConfig({ type: 'custom' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].type).toBe('Custom');
+ });
+ });
+
+ describe('setChartableProp', () => {
+ it('sets analysis to Chartable when all conditions are met', () => {
+ const config = buildConfig({
+ type: 'wmts',
+ palette: { id: 'palette1' },
+ colormapType: 'continuous',
+ layerPeriod: 'Daily',
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].analysis).toEqual(['Chartable (Raster-based)']);
+ });
+
+ it('does not set analysis when palette is missing', () => {
+ const config = buildConfig({
+ type: 'wmts',
+ colormapType: 'continuous',
+ layerPeriod: 'Daily',
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].analysis).toBeUndefined();
+ });
+
+ it('does not set analysis when colormapType is not continuous', () => {
+ const config = buildConfig({
+ type: 'wmts',
+ palette: { id: 'palette1' },
+ colormapType: 'classification',
+ layerPeriod: 'Daily',
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].analysis).toBeUndefined();
+ });
+
+ it('does not set analysis when layerPeriod is not Daily', () => {
+ const config = buildConfig({
+ type: 'wmts',
+ palette: { id: 'palette1' },
+ colormapType: 'continuous',
+ layerPeriod: 'Monthly',
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].analysis).toBeUndefined();
+ });
+
+ it('does not set analysis when disableCharting is true', () => {
+ const config = buildConfig({
+ type: 'wmts',
+ palette: { id: 'palette1' },
+ colormapType: 'continuous',
+ layerPeriod: 'Daily',
+ disableCharting: true,
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].analysis).toBeUndefined();
+ });
+ });
+
+ describe('setCoverageFacetProp', () => {
+ it('sets coverage to "Always Available" when no date info is present', () => {
+ const config = buildConfig({ type: 'wmts' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].coverage).toEqual(['Always Available']);
+ });
+
+ it('sets coverage to available date string when layer is available on selectedDate', () => {
+ available.mockReturnValue(true);
+ formatDisplayDate.mockReturnValue('Jan 01, 2024');
+ const config = buildConfig({
+ type: 'wmts',
+ startDate: '2020-01-01',
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].coverage).toEqual(['Available Jan 01, 2024']);
+ });
+
+ it('does not set coverage when layer has date info but is not available', () => {
+ available.mockReturnValue(false);
+ const config = buildConfig({
+ type: 'wmts',
+ startDate: '2020-01-01',
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].coverage).toBeUndefined();
+ });
+
+ it('deletes existing coverage prop and sets Always Available when no date info present', () => {
+ const config = buildConfig({
+ type: 'wmts',
+ coverage: ['stale coverage'],
+ });
+ available.mockReturnValue(false);
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].coverage).toEqual(['Always Available']);
+ });
+
+ it('deletes existing coverage and leaves undefined when has dates but not available', () => {
+ available.mockReturnValue(false);
+ const config = buildConfig({
+ type: 'wmts',
+ startDate: '2020-01-01',
+ coverage: ['stale coverage'],
+ });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].coverage).toBeUndefined();
+ });
+ });
+
+ describe('setLayerProp - sources via subtitle', () => {
+ it('sets sources from subtitle', () => {
+ const config = buildConfig({ type: 'wmts', subtitle: 'NASA / GSFC' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].sources).toEqual(['NASA / GSFC']);
+ });
+
+ it('decodes HTML entities in subtitle', () => {
+ const config = buildConfig({ type: 'wmts', subtitle: 'NASA &amp; GSFC' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].sources).toEqual(['NASA & GSFC']);
+ });
+
+ it('does not set sources when subtitle is absent', () => {
+ const config = buildConfig({ type: 'wmts', subtitle: undefined });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].sources).toBeUndefined();
+ });
+
+ it('does not duplicate existing source value', () => {
+ const config = {
+ layers: {
+ layer1: {
+ id: 'layer1',
+ type: 'wmts',
+ subtitle: 'Source A',
+ sources: ['Source A'],
+ },
+ },
+ measurements: {},
+ categories: {},
+ };
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].sources).toEqual(['Source A']);
+ });
+ });
+
+ describe('setMeasurementSourceFacetProps', () => {
+ it('sets measurements from measurement config', () => {
+ const config = buildConfig({ type: 'wmts' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].measurements).toContain('Aerosol Optical Depth');
+ });
+
+ it('does not set measurement if key includes "Featured"', () => {
+ const config = {
+ layers: { layer1: { id: 'layer1', type: 'wmts' } },
+ measurements: {
+ 'Featured Aerosol': {
+ sources: {
+ MODIS: { settings: ['layer1'] },
+ },
+ },
+ },
+ categories: {},
+ };
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].measurements).toBeUndefined();
+ });
+
+ it('handles measurement sources with empty settings gracefully', () => {
+ const config = {
+ layers: { layer1: { id: 'layer1', type: 'wmts' } },
+ measurements: {
+ 'Sea Surface Temp': {
+ sources: {
+ MODIS: { settings: [] },
+ },
+ },
+ },
+ categories: {},
+ };
+ expect(() => buildLayerFacetProps(config, selectedDate)).not.toThrow();
+ });
+ });
+
+ describe('setCategoryFacetProps', () => {
+ it('sets categories on layer from category config', () => {
+ const config = buildConfig({ type: 'wmts' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].categories).toContain('Aerosols');
+ });
+
+ it('skips the "featured" category key', () => {
+ const config = {
+ layers: { layer1: { id: 'layer1', type: 'wmts' } },
+ measurements: {
+ 'Aerosol Optical Depth': {
+ sources: { MODIS: { settings: ['layer1'] } },
+ },
+ },
+ categories: {
+ featured: {
+ Aerosols: { measurements: ['Aerosol Optical Depth'] },
+ },
+ },
+ };
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].categories).toBeUndefined();
+ });
+
+ it('skips sub-categories keyed "All"', () => {
+ const config = {
+ layers: { layer1: { id: 'layer1', type: 'wmts' } },
+ measurements: {
+ 'Aerosol Optical Depth': {
+ sources: { MODIS: { settings: ['layer1'] } },
+ },
+ },
+ categories: {
+ atmosphere: {
+ All: { measurements: ['Aerosol Optical Depth'] },
+ },
+ },
+ };
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].categories).toBeUndefined();
+ });
+
+ it('throws when a measurement key has no config entry', () => {
+ const config = {
+ layers: { layer1: { id: 'layer1', type: 'wmts' } },
+ measurements: {},
+ categories: {
+ atmosphere: {
+ Aerosols: { measurements: ['NonExistentMeasurement'] },
+ },
+ },
+ };
+ expect(() => buildLayerFacetProps(config, selectedDate)).toThrow(
+ 'No measurement config entry for "NonExistentMeasurement".',
+ );
+ });
+ });
+
+ describe('daynight handling', () => {
+ it('capitalizes a daynight string value into an array', () => {
+ const config = buildConfig({ type: 'wmts', daynight: 'day' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].daynight).toEqual(['Day']);
+ });
+
+ it('capitalizes daynight array values', () => {
+ const config = buildConfig({ type: 'wmts', daynight: ['day', 'night'] });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].daynight).toEqual(['Day', 'Night']);
+ });
+
+ it('does not transform daynight when it is an empty array', () => {
+ const config = buildConfig({ type: 'wmts', daynight: [] });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].daynight).toEqual([]);
+ });
+
+ it('does not set daynight when not present on layer', () => {
+ const config = buildConfig({ type: 'wmts' });
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result[0].daynight).toBeUndefined();
+ });
+ });
+
+ describe('general behaviour', () => {
+ it('does not mutate the original config layers', () => {
+ const config = buildConfig({ type: 'wmts' });
+ const originalType = config.layers.layer1.type;
+ buildLayerFacetProps(config, selectedDate);
+ expect(config.layers.layer1.type).toBe(originalType);
+ });
+
+ it('returns an array with one entry per layer', () => {
+ const config = {
+ layers: {
+ layer1: { id: 'layer1', type: 'wmts' },
+ layer2: { id: 'layer2', type: 'vector' },
+ },
+ measurements: {},
+ categories: {},
+ };
+ const result = buildLayerFacetProps(config, selectedDate);
+ expect(result).toHaveLength(2);
+ });
+ });
});
diff --git a/web/js/modules/product-picker/reducers.test.js b/web/js/modules/product-picker/reducers.test.js
index 04cce6a78..eccf51b82 100644
--- a/web/js/modules/product-picker/reducers.test.js
+++ b/web/js/modules/product-picker/reducers.test.js
@@ -1,3 +1,457 @@
-test('reducers module test', () => {
+import { productPickerReducer, getInitialState } from './reducers';
+import {
+ SAVE_SEARCH_STATE,
+ INIT_STATE,
+ COLLAPSE_FACET,
+ SELECT_CATEGORY_TYPE,
+ SELECT_MEASUREMENT,
+ SELECT_SOURCE,
+ SELECT_LAYER,
+ SHOW_MEASUREMENTS,
+ TOGGLE_FEATURED_TAB,
+ TOGGLE_MEASUREMENTS_TAB,
+ TOGGLE_RECENT_LAYERS_TAB,
+ TOGGLE_SEARCH_MODE,
+ TOGGLE_CATEGORY_MODE,
+ TOGGLE_MOBILE_FACETS,
+ CLEAR_RECENT_LAYERS,
+ CLEAR_SINGLE_RECENT_LAYER,
+ PROJ_SWITCH,
+ RESET_STATE,
+} from './constants';
+jest.mock('googleTagManager', () => ({
+ pushEvent: jest.fn(),
+}), { virtual: true });
+
+import googleTagManager from 'googleTagManager';
+
+const baseState = {
+ mode: 'category',
+ category: undefined,
+ categoryType: undefined,
+ filters: [],
+ showMobileFacets: true,
+ searchTerm: '',
+ selectedLayer: undefined,
+ selectedMeasurement: undefined,
+ selectedMeasurementSourceIndex: 0,
+ searchConfig: undefined,
+ collapsedFacets: {},
+ recentLayers: [],
+};
+
+describe('getInitialState', () => {
+ it('returns state with first categoryGroupOrder entry as categoryType', () => {
+ const result = getInitialState({
+ categories: { science: {}, hazards: {} },
+ categoryGroupOrder: ['science', 'hazards'],
+ });
+ expect(result.categoryType).toBe('science');
+ });
+
+ it('throws when categories length does not match categoryGroupOrder length', () => {
+ expect(() =>
+ getInitialState({
+ categories: { science: {} },
+ categoryGroupOrder: ['science', 'hazards'],
+ }),
+ ).toThrow('Number of category groups did not match defined category group order.');
+ });
+
+ it('returns productPickerState base properties', () => {
+ const result = getInitialState({
+ categories: { science: {} },
+ categoryGroupOrder: ['science'],
+ });
+ expect(result.mode).toBe('category');
+ expect(result.filters).toEqual([]);
+ expect(result.recentLayers).toEqual([]);
+ });
+});
+
+describe('productPickerReducer', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ getInitialState({
+ categories: { science: {}, hazards: {} },
+ categoryGroupOrder: ['science', 'hazards'],
+ });
+ });
+
+ it('returns default state when no action matches', () => {
+ const result = productPickerReducer(baseState, { type: '@@INIT' });
+ expect(result).toEqual(baseState);
+ });
+
+ it('returns initial productPickerState when called with undefined state', () => {
+ const result = productPickerReducer(undefined, { type: '@@INIT' });
+ expect(result.mode).toBe('category');
+ expect(result.filters).toEqual([]);
+ });
+
+ describe('INIT_STATE', () => {
+ it('sets searchConfig and keeps existing mode when mode is set', () => {
+ const state = { ...baseState, mode: 'search' };
+ const searchConfig = { index: {} };
+ const result = productPickerReducer(state, {
+ type: INIT_STATE,
+ searchConfig,
+ projection: 'geographic',
+ });
+ expect(result.searchConfig).toBe(searchConfig);
+ expect(result.mode).toBe('search');
+ });
+
+ it('sets mode to "category" for geographic projection when mode is empty', () => {
+ const state = { ...baseState, mode: '' };
+ const result = productPickerReducer(state, {
+ type: INIT_STATE,
+ searchConfig: {},
+ projection: 'geographic',
+ });
+ expect(result.mode).toBe('category');
+ });
+
+ it('sets mode to "measurements" for non-geographic projection when mode is empty', () => {
+ const state = { ...baseState, mode: '' };
+ const result = productPickerReducer(state, {
+ type: INIT_STATE,
+ searchConfig: {},
+ projection: 'arctic',
+ });
+ expect(result.mode).toBe('measurements');
+ });
+ });
+
+ describe('SAVE_SEARCH_STATE', () => {
+ it('updates filters, searchTerm, and searchConfig', () => {
+ const filters = [{ field: 'category', value: 'Atmosphere' }];
+ const searchTerm = 'aerosol';
+ const searchConfig = { index: {} };
+ const result = productPickerReducer(baseState, {
+ type: SAVE_SEARCH_STATE,
+ filters,
+ searchTerm,
+ searchConfig,
+ });
+ expect(result.filters).toBe(filters);
+ expect(result.searchTerm).toBe(searchTerm);
+ expect(result.searchConfig).toBe(searchConfig);
+ });
+ });
+
+ describe('COLLAPSE_FACET', () => {
+ it('toggles a facet field to true when previously undefined', () => {
+ const result = productPickerReducer(baseState, {
+ type: COLLAPSE_FACET,
+ field: 'category',
+ });
+ expect(result.collapsedFacets.category).toBe(true);
+ });
+
+ it('toggles a facet field to false when previously true', () => {
+ const state = { ...baseState, collapsedFacets: { category: true } };
+ const result = productPickerReducer(state, {
+ type: COLLAPSE_FACET,
+ field: 'category',
+ });
+ expect(result.collapsedFacets.category).toBe(false);
+ });
+
+ it('toggles a facet field to true when previously false', () => {
+ const state = { ...baseState, collapsedFacets: { category: false } };
+ const result = productPickerReducer(state, {
+ type: COLLAPSE_FACET,
+ field: 'category',
+ });
+ expect(result.collapsedFacets.category).toBe(true);
+ });
+ });
+
+ describe('SELECT_CATEGORY_TYPE', () => {
+ it('sets mode to "category" and updates categoryType', () => {
+ const result = productPickerReducer(baseState, {
+ type: SELECT_CATEGORY_TYPE,
+ value: 'hazards',
+ });
+ expect(result.mode).toBe('category');
+ expect(result.categoryType).toBe('hazards');
+ expect(result.category).toBeNull();
+ expect(result.selectedLayer).toBeNull();
+ expect(result.selectedMeasurement).toBeNull();
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ });
+
+ it('calls googleTagManager.pushEvent with the correct payload', () => {
+ productPickerReducer(baseState, {
+ type: SELECT_CATEGORY_TYPE,
+ value: 'science',
+ });
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'layers_meta_category',
+ layers: { meta_category: 'science' },
+ });
+ });
+ });
+
+ describe('SELECT_MEASUREMENT', () => {
+ it('sets selectedMeasurement when value differs from current', () => {
+ const state = { ...baseState, selectedMeasurement: 'aerosol' };
+ const result = productPickerReducer(state, {
+ type: SELECT_MEASUREMENT,
+ value: 'temperature',
+ });
+ expect(result.selectedMeasurement).toBe('temperature');
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ });
+
+ it('sets selectedMeasurement to null when value matches current (toggle off)', () => {
+ const state = { ...baseState, selectedMeasurement: 'aerosol' };
+ const result = productPickerReducer(state, {
+ type: SELECT_MEASUREMENT,
+ value: 'aerosol',
+ });
+ expect(result.selectedMeasurement).toBeNull();
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ });
+ });
+
+ describe('SELECT_SOURCE', () => {
+ it('updates selectedMeasurementSourceIndex', () => {
+ const result = productPickerReducer(baseState, {
+ type: SELECT_SOURCE,
+ value: 3,
+ });
+ expect(result.selectedMeasurementSourceIndex).toBe(3);
+ });
+ });
+
+ describe('SELECT_LAYER', () => {
+ it('updates selectedLayer', () => {
+ const result = productPickerReducer(baseState, {
+ type: SELECT_LAYER,
+ value: 'MODIS_Terra_CorrectedReflectance_TrueColor',
+ });
+ expect(result.selectedLayer).toBe('MODIS_Terra_CorrectedReflectance_TrueColor');
+ });
+ });
+
+ describe('SHOW_MEASUREMENTS', () => {
+ it('sets mode to "measurements" and updates category and selectedMeasurement', () => {
+ const category = { title: 'Atmosphere' };
+ const result = productPickerReducer(baseState, {
+ type: SHOW_MEASUREMENTS,
+ value: { category, selectedMeasurement: 'aerosol' },
+ });
+ expect(result.mode).toBe('measurements');
+ expect(result.category).toBe(category);
+ expect(result.selectedMeasurement).toBe('aerosol');
+ });
+
+ it('calls googleTagManager.pushEvent with category title', () => {
+ const category = { title: 'Hazards' };
+ productPickerReducer(baseState, {
+ type: SHOW_MEASUREMENTS,
+ value: { category, selectedMeasurement: null },
+ });
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'layers_category',
+ layers: { category: 'Hazards' },
+ });
+ });
+ });
+
+ describe('TOGGLE_SEARCH_MODE', () => {
+ it('sets mode to "search" and resets related fields', () => {
+ const state = {
+ ...baseState,
+ selectedLayer: 'some-layer',
+ category: { title: 'Atmosphere' },
+ selectedMeasurementSourceIndex: 2,
+ };
+ const result = productPickerReducer(state, { type: TOGGLE_SEARCH_MODE });
+ expect(result.mode).toBe('search');
+ expect(result.selectedLayer).toBeNull();
+ expect(result.showMobileFacets).toBe(true);
+ expect(result.category).toBeNull();
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ expect(result.categoryType).toBe('science');
+ });
+ });
+
+ describe('TOGGLE_FEATURED_TAB', () => {
+ it('sets categoryType to "featured" and resolves selectedMeasurement from config', () => {
+ const config = {
+ categories: {
+ featured: {
+ All: { measurements: ['Aerosol Optical Depth'] },
+ },
+ },
+ measurements: {
+ 'Aerosol Optical Depth': { id: 'aerosol-id' },
+ },
+ };
+ const result = productPickerReducer(baseState, {
+ type: TOGGLE_FEATURED_TAB,
+ config,
+ });
+ expect(result.categoryType).toBe('featured');
+ expect(result.category).toBeNull();
+ expect(result.mode).toBe('measurements');
+ expect(result.selectedLayer).toBeNull();
+ expect(result.selectedMeasurement).toBe('aerosol-id');
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ });
+
+ it('handles missing featured config gracefully', () => {
+ const result = productPickerReducer(baseState, {
+ type: TOGGLE_FEATURED_TAB,
+ config: {},
+ });
+ expect(result.categoryType).toBe('featured');
+ expect(result.selectedMeasurement).toBeUndefined();
+ });
+ });
+
+ describe('TOGGLE_MEASUREMENTS_TAB', () => {
+ it('sets mode to "measurements" and categoryType to "measurements"', () => {
+ const result = productPickerReducer(baseState, { type: TOGGLE_MEASUREMENTS_TAB });
+ expect(result.mode).toBe('measurements');
+ expect(result.categoryType).toBe('measurements');
+ });
+ });
+
+ describe('TOGGLE_RECENT_LAYERS_TAB', () => {
+ it('sets categoryType to "recent" and updates recentLayers', () => {
+ const recentLayers = [{ id: 'layer1' }];
+ const result = productPickerReducer(baseState, {
+ type: TOGGLE_RECENT_LAYERS_TAB,
+ recentLayers,
+ });
+ expect(result.categoryType).toBe('recent');
+ expect(result.recentLayers).toBe(recentLayers);
+ expect(result.category).toBeNull();
+ expect(result.selectedMeasurement).toBeNull();
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ });
+ });
+
+ describe('TOGGLE_CATEGORY_MODE', () => {
+ it('sets mode to "category" and resets selection fields', () => {
+ const state = {
+ ...baseState,
+ mode: 'search',
+ category: { title: 'Atmosphere' },
+ selectedLayer: 'layer1',
+ selectedMeasurement: 'aerosol',
+ selectedMeasurementSourceIndex: 2,
+ };
+ const result = productPickerReducer(state, { type: TOGGLE_CATEGORY_MODE });
+ expect(result.mode).toBe('category');
+ expect(result.category).toBeNull();
+ expect(result.selectedLayer).toBeNull();
+ expect(result.selectedMeasurement).toBeNull();
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ });
+ });
+
+ describe('TOGGLE_MOBILE_FACETS', () => {
+ it('toggles showMobileFacets from true to false', () => {
+ const state = { ...baseState, showMobileFacets: true };
+ const result = productPickerReducer(state, { type: TOGGLE_MOBILE_FACETS });
+ expect(result.showMobileFacets).toBe(false);
+ });
+
+ it('toggles showMobileFacets from false to true', () => {
+ const state = { ...baseState, showMobileFacets: false };
+ const result = productPickerReducer(state, { type: TOGGLE_MOBILE_FACETS });
+ expect(result.showMobileFacets).toBe(true);
+ });
+ });
+
+ describe('CLEAR_RECENT_LAYERS', () => {
+ it('resets recentLayers to empty array', () => {
+ const state = { ...baseState, recentLayers: [{ id: 'layer1' }] };
+ const result = productPickerReducer(state, { type: CLEAR_RECENT_LAYERS });
+ expect(result.recentLayers).toEqual([]);
+ });
+ });
+
+ describe('CLEAR_SINGLE_RECENT_LAYER', () => {
+ it('replaces recentLayers with the provided list', () => {
+ const recentLayers = [{ id: 'layer2' }];
+ const state = { ...baseState, recentLayers: [{ id: 'layer1' }, { id: 'layer2' }] };
+ const result = productPickerReducer(state, {
+ type: CLEAR_SINGLE_RECENT_LAYER,
+ recentLayers,
+ });
+ expect(result.recentLayers).toBe(recentLayers);
+ });
+ });
+
+ describe('PROJ_SWITCH', () => {
+ it('sets mode to "category" and categoryType to first group order for geographic', () => {
+ const state = { ...baseState, mode: 'category' };
+ const result = productPickerReducer(state, {
+ type: PROJ_SWITCH,
+ projection: 'geographic',
+ });
+ expect(result.mode).toBe('category');
+ expect(result.categoryType).toBe('science');
+ expect(result.filters).toEqual([]);
+ expect(result.searchTerm).toBe('');
+ expect(result.selectedLayer).toBeNull();
+ expect(result.category).toBeNull();
+ expect(result.selectedMeasurement).toBeNull();
+ expect(result.selectedMeasurementSourceIndex).toBe(0);
+ });
+
+ it('sets mode to "measurements" for arctic projection', () => {
+ const state = { ...baseState, mode: 'category' };
+ const result = productPickerReducer(state, {
+ type: PROJ_SWITCH,
+ projection: 'arctic',
+ });
+ expect(result.mode).toBe('measurements');
+ expect(result.categoryType).toBe('measurements');
+ });
+
+ it('sets mode to "measurements" for antarctic projection', () => {
+ const state = { ...baseState, mode: 'category' };
+ const result = productPickerReducer(state, {
+ type: PROJ_SWITCH,
+ projection: 'antarctic',
+ });
+ expect(result.mode).toBe('measurements');
+ expect(result.categoryType).toBe('measurements');
+ });
+
+ it('preserves "search" mode when switching projections', () => {
+ const state = { ...baseState, mode: 'search' };
+ const result = productPickerReducer(state, {
+ type: PROJ_SWITCH,
+ projection: 'arctic',
+ });
+ expect(result.mode).toBe('search');
+ });
+ });
+
+ describe('RESET_STATE', () => {
+ it('resets to productPickerState with first categoryGroupOrder as categoryType', () => {
+ const dirtyState = {
+ ...baseState,
+ mode: 'search',
+ searchTerm: 'aerosol',
+ selectedLayer: 'some-layer',
+ filters: [{ field: 'category' }],
+ };
+ const result = productPickerReducer(dirtyState, { type: RESET_STATE });
+ expect(result.mode).toBe('category');
+ expect(result.searchTerm).toBe('');
+ expect(result.selectedLayer).toBeUndefined();
+ expect(result.filters).toEqual([]);
+ expect(result.categoryType).toBe('science');
+ });
+ });
});
diff --git a/web/js/modules/product-picker/search-config.test.js b/web/js/modules/product-picker/search-config.test.js
index 5b4f553ec..902f6ef0f 100644
--- a/web/js/modules/product-picker/search-config.test.js
+++ b/web/js/modules/product-picker/search-config.test.js
@@ -1,3 +1,373 @@
-test('seardh-config module test', () => {
+import initSearch from './search-config';
+import { getTitles } from '../layers/selectors';
+import { getLayersForProjection } from './selectors';
+import { getSelectedDate } from '../date/selectors';
+import { formatDisplayDate } from '../date/util';
+jest.mock('../layers/selectors', () => ({
+ getTitles: jest.fn(),
+}));
+
+jest.mock('./selectors', () => ({
+ getLayersForProjection: jest.fn(),
+}));
+
+jest.mock('../date/selectors', () => ({
+ getSelectedDate: jest.fn(),
+}));
+
+jest.mock('../date/util', () => ({
+ formatDisplayDate: jest.fn(() => 'Jan 01, 2024'),
+}));
+
+jest.mock('./facet-config', () => [
+ { field: 'type' },
+ { field: 'coverage', hideZeroCount: true },
+ { field: 'categories' },
+]);
+
+const makeLayer = (overrides = {}) => ({
+ id: 'layer1',
+ type: 'Raster',
+ coverage: ['Always Available'],
+ categories: ['Atmosphere'],
+ ...overrides,
+});
+
+const makeState = (overrides = {}) => ({
+ productPicker: {
+ filters: [],
+ searchTerm: '',
+ ...overrides.productPicker,
+ },
+ config: { layers: {} },
+ proj: { id: 'geographic' },
+ ...overrides,
+});
+
+describe('initSearch', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ getSelectedDate.mockReturnValue(new Date('2024-01-01'));
+ getLayersForProjection.mockReturnValue([]);
+ getTitles.mockReturnValue({ title: '', subtitle: '', tags: '' });
+ });
+
+ describe('return value shape', () => {
+ it('returns alwaysSearchOnInitialLoad as true', () => {
+ const config = initSearch(makeState());
+ expect(config.alwaysSearchOnInitialLoad).toBe(true);
+ });
+
+ it('returns trackUrlState as false', () => {
+ const config = initSearch(makeState());
+ expect(config.trackUrlState).toBe(false);
+ });
+
+ it('returns searchQuery as empty object', () => {
+ const config = initSearch(makeState());
+ expect(config.searchQuery).toEqual({});
+ });
+
+ it('returns onSearch as a function', () => {
+ const config = initSearch(makeState());
+ expect(typeof config.onSearch).toBe('function');
+ });
+
+ it('returns initialState with filters and searchTerm from productPicker', () => {
+ const filters = [{ field: 'type', values: ['Raster'] }];
+ const state = makeState({ productPicker: { filters, searchTerm: 'aerosol' } });
+ const config = initSearch(state);
+ expect(config.initialState.filters).toBe(filters);
+ expect(config.initialState.searchTerm).toBe('aerosol');
+ });
+ });
+
+ describe('updateCoverageFilter', () => {
+ it('does not throw when filters is empty', () => {
+ const state = makeState({ productPicker: { filters: [], searchTerm: '' } });
+ expect(() => initSearch(state)).not.toThrow();
+ });
+
+ it('updates stale coverage filter values to use formatted date', () => {
+ formatDisplayDate.mockReturnValue('Jan 01, 2024');
+ const filters = [{ field: 'coverage', values: ['Available Dec 31, 2023'] }];
+ const state = makeState({ productPicker: { filters, searchTerm: '' } });
+ initSearch(state);
+ expect(filters[0].values[0]).toBe('Available Jan 01, 2024');
+ });
+
+ it('does not change coverage filter values that already contain formatted date', () => {
+ formatDisplayDate.mockReturnValue('Jan 01, 2024');
+ const filters = [{ field: 'coverage', values: ['Available Jan 01, 2024'] }];
+ const state = makeState({ productPicker: { filters, searchTerm: '' } });
+ initSearch(state);
+ expect(filters[0].values[0]).toBe('Available Jan 01, 2024');
+ });
+
+ it('does not change coverage filter values containing "Always"', () => {
+ formatDisplayDate.mockReturnValue('Jan 01, 2024');
+ const filters = [{ field: 'coverage', values: ['Always Available'] }];
+ const state = makeState({ productPicker: { filters, searchTerm: '' } });
+ initSearch(state);
+ expect(filters[0].values[0]).toBe('Always Available');
+ });
+
+ it('does not alter non-coverage filter fields', () => {
+ const filters = [{ field: 'type', values: ['Raster'] }];
+ const state = makeState({ productPicker: { filters, searchTerm: '' } });
+ initSearch(state);
+ expect(filters[0].values[0]).toBe('Raster');
+ });
+
+ it('handles multiple filters and only updates coverage field', () => {
+ formatDisplayDate.mockReturnValue('Jan 01, 2024');
+ const filters = [
+ { field: 'type', values: ['Raster'] },
+ { field: 'coverage', values: ['Available Dec 31, 2023'] },
+ ];
+ const state = makeState({ productPicker: { filters, searchTerm: '' } });
+ initSearch(state);
+ expect(filters[0].values[0]).toBe('Raster');
+ expect(filters[1].values[0]).toBe('Available Jan 01, 2024');
+ });
+ });
+
+ describe('facet counts initialisation', () => {
+ it('populates facet counts from initial layers array', () => {
+ const layer = makeLayer({ type: 'Raster', coverage: ['Always Available'] });
+ getLayersForProjection.mockReturnValue([layer]);
+ const config = initSearch(makeState());
+ expect(config.initialState).toBeDefined();
+ });
+
+ it('handles layers with array field values for facets', () => {
+ const layer = makeLayer({ categories: ['Atmosphere', 'Land'] });
+ getLayersForProjection.mockReturnValue([layer]);
+ expect(() => initSearch(makeState())).not.toThrow();
+ });
+
+ it('handles layers with undefined facet fields gracefully', () => {
+ const layer = makeLayer({ type: undefined, coverage: undefined, categories: undefined });
+ getLayersForProjection.mockReturnValue([layer]);
+ expect(() => initSearch(makeState())).not.toThrow();
+ });
+ });
+
+ describe('onSearch', () => {
+ it('returns results matching an empty search term and no filters', async () => {
+ const layer = makeLayer();
+ getLayersForProjection.mockReturnValue([layer]);
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: '' });
+ expect(response.results).toContain(layer);
+ expect(response.totalResults).toBe(1);
+ });
+
+ it('returns totalResults equal to results length', async () => {
+ const layers = [makeLayer({ id: 'l1' }), makeLayer({ id: 'l2' })];
+ getLayersForProjection.mockReturnValue(layers);
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: '' });
+ expect(response.totalResults).toBe(response.results.length);
+ });
+
+ it('returns facets object', async () => {
+ const layer = makeLayer();
+ getLayersForProjection.mockReturnValue([layer]);
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: '' });
+ expect(response.facets).toBeDefined();
+ });
+
+ it('filters results by a single filter field value', async () => {
+ const rasterLayer = makeLayer({ id: 'raster', type: 'Raster' });
+ const vectorLayer = makeLayer({ id: 'vector', type: 'Vector' });
+ getLayersForProjection.mockReturnValue([rasterLayer, vectorLayer]);
+ getTitles.mockReturnValue({ title: '', subtitle: '', tags: '' });
+ const config = initSearch(makeState());
+ const response = await config.onSearch({
+ filters: [{ field: 'type', values: ['Raster'] }],
+ searchTerm: '',
+ });
+ expect(response.results).toContain(rasterLayer);
+ expect(response.results).not.toContain(vectorLayer);
+ });
+
+ it('filters results by search term matching layer id', async () => {
+ const aerosolLayer = makeLayer({ id: 'aerosol_layer' });
+ const tempLayer = makeLayer({ id: 'temperature_layer' });
+ getLayersForProjection.mockReturnValue([aerosolLayer, tempLayer]);
+ getTitles.mockImplementation((config, id) => ({
+ title: id,
+ subtitle: '',
+ tags: '',
+ }));
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: 'aerosol' });
+ expect(response.results).toContain(aerosolLayer);
+ expect(response.results).not.toContain(tempLayer);
+ });
+
+ it('filters results by search term matching layer title', async () => {
+ const layer1 = makeLayer({ id: 'layer1' });
+ const layer2 = makeLayer({ id: 'layer2' });
+ getLayersForProjection.mockReturnValue([layer1, layer2]);
+ getTitles.mockImplementation((config, id) => ({
+ title: id === 'layer1' ? 'Aerosol Optical Depth' : 'Sea Surface Temperature',
+ subtitle: '',
+ tags: '',
+ }));
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: 'aerosol' });
+ expect(response.results).toContain(layer1);
+ expect(response.results).not.toContain(layer2);
+ });
+
+ it('filters results by search term matching subtitle', async () => {
+ const layer1 = makeLayer({ id: 'layer1' });
+ const layer2 = makeLayer({ id: 'layer2' });
+ getLayersForProjection.mockReturnValue([layer1, layer2]);
+ getTitles.mockImplementation((config, id) => ({
+ title: '',
+ subtitle: id === 'layer1' ? 'MODIS Terra' : 'VIIRS NOAA',
+ tags: '',
+ }));
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: 'modis' });
+ expect(response.results).toContain(layer1);
+ expect(response.results).not.toContain(layer2);
+ });
+
+ it('filters results by search term matching tags', async () => {
+ const layer1 = makeLayer({ id: 'layer1' });
+ const layer2 = makeLayer({ id: 'layer2' });
+ getLayersForProjection.mockReturnValue([layer1, layer2]);
+ getTitles.mockImplementation((config, id) => ({
+ title: '',
+ subtitle: '',
+ tags: id === 'layer1' ? 'fire smoke aerosol' : 'sea surface',
+ }));
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: 'smoke' });
+ expect(response.results).toContain(layer1);
+ expect(response.results).not.toContain(layer2);
+ });
+
+ it('filters results by search term matching conceptIds shortName', async () => {
+ const layer1 = makeLayer({ id: 'layer1', conceptIds: [{ value: '', shortName: 'MOD04_L2' }] });
+ const layer2 = makeLayer({ id: 'layer2', conceptIds: [] });
+ getLayersForProjection.mockReturnValue([layer1, layer2]);
+ getTitles.mockReturnValue({ title: '', subtitle: '', tags: '' });
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: 'mod04' });
+ expect(response.results).toContain(layer1);
+ expect(response.results).not.toContain(layer2);
+ });
+
+ it('returns no results when search term matches nothing', async () => {
+ const layer = makeLayer({ id: 'aerosol_layer' });
+ getLayersForProjection.mockReturnValue([layer]);
+ getTitles.mockReturnValue({ title: 'Aerosol', subtitle: '', tags: '' });
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: 'zzznomatch' });
+ expect(response.results).toHaveLength(0);
+ expect(response.totalResults).toBe(0);
+ });
+
+ it('matches layers with multiple space-separated search terms', async () => {
+ const layer1 = makeLayer({ id: 'aerosol_optical_depth' });
+ const layer2 = makeLayer({ id: 'sea_surface_temp' });
+ getLayersForProjection.mockReturnValue([layer1, layer2]);
+ getTitles.mockImplementation((config, id) => ({
+ title: id === 'aerosol_optical_depth' ? 'Aerosol Optical Depth' : 'Sea Surface Temp',
+ subtitle: '',
+ tags: '',
+ }));
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: 'aerosol optical' });
+ expect(response.results).toContain(layer1);
+ expect(response.results).not.toContain(layer2);
+ });
+
+ it('applies "None" filter matching layers with no value for that field', async () => {
+ const layerWithType = makeLayer({ id: 'layer1', type: 'Raster' });
+ const layerWithoutType = makeLayer({ id: 'layer2', type: undefined });
+ getLayersForProjection.mockReturnValue([layerWithType, layerWithoutType]);
+ getTitles.mockReturnValue({ title: '', subtitle: '', tags: '' });
+ const config = initSearch(makeState());
+ const response = await config.onSearch({
+ filters: [{ field: 'type', values: ['None'] }],
+ searchTerm: '',
+ });
+ expect(response.results).toContain(layerWithoutType);
+ expect(response.results).not.toContain(layerWithType);
+ });
+
+ it('returns facets with type value format', async () => {
+ const layer = makeLayer({ type: 'Raster' });
+ getLayersForProjection.mockReturnValue([layer]);
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: '' });
+ expect(response.facets.type).toBeDefined();
+ expect(response.facets.type[0].type).toBe('value');
+ expect(Array.isArray(response.facets.type[0].data)).toBe(true);
+ });
+
+ it('facet data is sorted alphabetically for non-hideZeroCount fields', async () => {
+ const layers = [
+ makeLayer({ id: 'l1', type: 'Raster' }),
+ makeLayer({ id: 'l2', type: 'Vector' }),
+ makeLayer({ id: 'l3', type: 'Granule' }),
+ ];
+ getLayersForProjection.mockReturnValue(layers);
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: '' });
+ const typeData = response.facets.type[0].data;
+ const values = typeData.map((d) => d.value);
+ expect(values).toEqual([...values].sort((a, b) => a.localeCompare(b)));
+ });
+
+ it('hideZeroCount facet fields filter out zero count entries', async () => {
+ const layer = makeLayer({ coverage: ['Always Available'] });
+ getLayersForProjection.mockReturnValue([layer]);
+ const config = initSearch(makeState());
+ const response = await config.onSearch({ filters: [], searchTerm: '' });
+ const coverageData = response.facets.coverage[0].data;
+ coverageData.forEach((item) => {
+ expect(item.count).toBeGreaterThan(0);
+ });
+ });
+
+ it('applies multiple filters together (AND logic)', async () => {
+ const matchingLayer = makeLayer({ id: 'l1', type: 'Raster', categories: ['Atmosphere'] });
+ const wrongType = makeLayer({ id: 'l2', type: 'Vector', categories: ['Atmosphere'] });
+ const wrongCat = makeLayer({ id: 'l3', type: 'Raster', categories: ['Land'] });
+ getLayersForProjection.mockReturnValue([matchingLayer, wrongType, wrongCat]);
+ getTitles.mockReturnValue({ title: '', subtitle: '', tags: '' });
+ const config = initSearch(makeState());
+ const response = await config.onSearch({
+ filters: [
+ { field: 'type', values: ['Raster'] },
+ { field: 'categories', values: ['Atmosphere'] },
+ ],
+ searchTerm: '',
+ });
+ expect(response.results).toContain(matchingLayer);
+ expect(response.results).not.toContain(wrongType);
+ expect(response.results).not.toContain(wrongCat);
+ });
+ });
+
+ describe('proj handling', () => {
+ it('handles null proj gracefully', () => {
+ const state = makeState({ proj: null });
+ expect(() => initSearch(state)).not.toThrow();
+ });
+
+ it('sets projectionRef from proj.id', () => {
+ const state = makeState({ proj: { id: 'arctic' } });
+ expect(() => initSearch(state)).not.toThrow();
+ });
+ });
});
diff --git a/web/js/modules/product-picker/selectors.test.js b/web/js/modules/product-picker/selectors.test.js
index c4e1cdccf..b50d1299e 100644
--- a/web/js/modules/product-picker/selectors.test.js
+++ b/web/js/modules/product-picker/selectors.test.js
@@ -1,3 +1,430 @@
-test('selectors module test', () => {
+import {
+ getLayersForProjection,
+ getSourcesForProjection,
+ getCategoryConfig,
+} from './selectors';
+import buildLayerFacetProps from './format-config';
+import { getSelectedDate } from '../date/selectors';
+import util from '../../util/util';
+jest.mock('./format-config');
+jest.mock('../date/selectors', () => ({
+ getSelectedDate: jest.fn(),
+}));
+jest.mock('../../util/util', () => ({
+ __esModule: true,
+ default: {
+ decodeHTML: jest.fn((val) => val.replace('&amp;', '&')),
+ },
+}));
+
+const selectedDate = new Date('2024-01-01');
+
+const makeState = (overrides = {}) => ({
+ config: {
+ layerOrder: [],
+ layers: {},
+ measurements: {},
+ categories: {},
+ categoryGroupOrder: [],
+ ...overrides.config,
+ },
+ proj: { id: 'geographic', ...overrides.proj },
+ productPicker: {
+ selectedMeasurement: null,
+ categoryType: 'science',
+ ...overrides.productPicker,
+ },
+ ...overrides,
+});
+
+describe('getLayersForProjection', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ getSelectedDate.mockReturnValue(selectedDate);
+ });
+
+ it('returns only layers that have the active projection', () => {
+ buildLayerFacetProps.mockReturnValue([
+ { id: 'layer1', projections: { geographic: {} } },
+ { id: 'layer2', projections: { arctic: {} } },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1', 'layer2'] } });
+ const result = getLayersForProjection(state);
+ expect(result.map((l) => l.id)).toEqual(['layer1']);
+ });
+
+ it('returns empty array when no layers match the active projection', () => {
+ buildLayerFacetProps.mockReturnValue([
+ { id: 'layer1', projections: { arctic: {} } },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1'] } });
+ const result = getLayersForProjection(state);
+ expect(result).toEqual([]);
+ });
+
+ it('filters out layers without a projections property', () => {
+ buildLayerFacetProps.mockReturnValue([
+ { id: 'layer1' },
+ { id: 'layer2', projections: { geographic: {} } },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1', 'layer2'] } });
+ const result = getLayersForProjection(state);
+ expect(result.map((l) => l.id)).toEqual(['layer2']);
+ });
+
+ it('sorts layers by their position in layerOrder', () => {
+ buildLayerFacetProps.mockReturnValue([
+ { id: 'layer3', projections: { geographic: {} } },
+ { id: 'layer1', projections: { geographic: {} } },
+ { id: 'layer2', projections: { geographic: {} } },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1', 'layer2', 'layer3'] } });
+ const result = getLayersForProjection(state);
+ expect(result.map((l) => l.id)).toEqual(['layer1', 'layer2', 'layer3']);
+ });
+
+ it('uses projection-specific title when available', () => {
+ buildLayerFacetProps.mockReturnValue([
+ {
+ id: 'layer1',
+ title: 'Default Title',
+ projections: { geographic: { title: 'Geo Title' } },
+ },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1'] } });
+ const result = getLayersForProjection(state);
+ expect(result[0].title).toBe('Geo Title');
+ });
+
+ it('keeps original title when projection metadata has no title', () => {
+ buildLayerFacetProps.mockReturnValue([
+ {
+ id: 'layer1',
+ title: 'Default Title',
+ projections: { geographic: {} },
+ },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1'] } });
+ const result = getLayersForProjection(state);
+ expect(result[0].title).toBe('Default Title');
+ });
+
+ it('uses projection-specific subtitle when available', () => {
+ buildLayerFacetProps.mockReturnValue([
+ {
+ id: 'layer1',
+ subtitle: 'Default Subtitle',
+ projections: { geographic: { subtitle: 'Geo Subtitle' } },
+ },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1'] } });
+ const result = getLayersForProjection(state);
+ expect(result[0].subtitle).toBe('Geo Subtitle');
+ });
+
+ it('keeps original subtitle when projection metadata has no subtitle', () => {
+ buildLayerFacetProps.mockReturnValue([
+ {
+ id: 'layer1',
+ subtitle: 'Default Subtitle',
+ projections: { geographic: {} },
+ },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1'] } });
+ const result = getLayersForProjection(state);
+ expect(result[0].subtitle).toBe('Default Subtitle');
+ });
+
+ it('decodes HTML entities in subtitle', () => {
+ util.decodeHTML.mockReturnValue('NASA & GSFC');
+ buildLayerFacetProps.mockReturnValue([
+ {
+ id: 'layer1',
+ subtitle: 'NASA &amp; GSFC',
+ projections: { geographic: {} },
+ },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1'] } });
+ const result = getLayersForProjection(state);
+ expect(util.decodeHTML).toHaveBeenCalledWith('NASA &amp; GSFC');
+ expect(result[0].subtitle).toBe('NASA & GSFC');
+ });
+
+ it('does not call decodeHTML when subtitle has no HTML entities', () => {
+ buildLayerFacetProps.mockReturnValue([
+ {
+ id: 'layer1',
+ subtitle: 'Plain Subtitle',
+ projections: { geographic: {} },
+ },
+ ]);
+ const state = makeState({ config: { layerOrder: ['layer1'] } });
+ getLayersForProjection(state);
+ expect(util.decodeHTML).not.toHaveBeenCalled();
+ });
+
+ it('handles null proj gracefully by returning empty array', () => {
+ buildLayerFacetProps.mockReturnValue([
+ { id: 'layer1', projections: { geographic: {} } },
+ ]);
+ const state = makeState({ proj: null });
+ const result = getLayersForProjection(state);
+ expect(result).toEqual([]);
+ });
+
+ it('passes config and selectedDate to buildLayerFacetProps', () => {
+ buildLayerFacetProps.mockReturnValue([]);
+ const state = makeState();
+ getLayersForProjection(state);
+ expect(buildLayerFacetProps).toHaveBeenCalledWith(state.config, selectedDate);
+ });
+});
+
+describe('getSourcesForProjection', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('returns undefined when no measurement matches selectedMeasurement', () => {
+ const state = makeState({
+ config: {
+ measurements: { m1: { id: 'measure-1', sources: {} } },
+ layers: {},
+ },
+ productPicker: { selectedMeasurement: 'non-existent' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns sources sorted by title for the active projection', () => {
+ const state = makeState({
+ config: {
+ measurements: {
+ m1: {
+ id: 'measure-1',
+ sources: {
+ s1: { title: 'Zebra Source', settings: ['layer1'] },
+ s2: { title: 'Alpha Source', settings: ['layer2'] },
+ },
+ },
+ },
+ layers: {
+ layer1: { projections: { geographic: {} }, layergroup: 'Some Group' },
+ layer2: { projections: { geographic: {} }, layergroup: 'Some Group' },
+ },
+ },
+ productPicker: { selectedMeasurement: 'measure-1' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result[0].title).toBe('Alpha Source');
+ expect(result[1].title).toBe('Zebra Source');
+ });
+
+ it('excludes sources with no layers in the active projection', () => {
+ const state = makeState({
+ config: {
+ measurements: {
+ m1: {
+ id: 'measure-1',
+ sources: {
+ s1: { title: 'Arctic Only', settings: ['layer1'] },
+ },
+ },
+ },
+ layers: {
+ layer1: { projections: { arctic: {} }, layergroup: 'Some Group' },
+ },
+ },
+ productPicker: { selectedMeasurement: 'measure-1' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes orbital track layers for non-track measurement groups', () => {
+ const state = makeState({
+ config: {
+ measurements: {
+ m1: {
+ id: 'measure-1',
+ sources: {
+ s1: { title: 'Orbit Source', settings: ['orbitLayer'] },
+ },
+ },
+ },
+ layers: {
+ orbitLayer: { projections: { geographic: {} }, layergroup: 'Orbital Track' },
+ },
+ },
+ productPicker: { selectedMeasurement: 'measure-1' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toEqual([]);
+ });
+
+ it('includes orbital track layers when measurement is the orbital-track group', () => {
+ const state = makeState({
+ config: {
+ measurements: {
+ m1: {
+ id: 'orbital-track',
+ sources: {
+ s1: { title: 'Orbit Source', settings: ['orbitLayer'] },
+ },
+ },
+ },
+ layers: {
+ orbitLayer: { projections: { geographic: {} }, layergroup: 'Orbital Track' },
+ },
+ },
+ productPicker: { selectedMeasurement: 'orbital-track' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toHaveLength(1);
+ expect(result[0].title).toBe('Orbit Source');
+ });
+
+ it('returns undefined when sources is falsy (no current measurement)', () => {
+ const state = makeState({
+ config: {
+ measurements: {},
+ layers: {},
+ },
+ productPicker: { selectedMeasurement: 'measure-1' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toBeUndefined();
+ });
+
+ it('skips layers that are missing from config.layers', () => {
+ const state = makeState({
+ config: {
+ measurements: {
+ m1: {
+ id: 'measure-1',
+ sources: {
+ s1: { title: 'Source A', settings: ['missingLayer', 'layer1'] },
+ },
+ },
+ },
+ layers: {
+ layer1: { projections: { geographic: {} }, layergroup: 'Some Group' },
+ },
+ },
+ productPicker: { selectedMeasurement: 'measure-1' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toHaveLength(1);
+ });
+
+ it('skips layers that have no projections property', () => {
+ const state = makeState({
+ config: {
+ measurements: {
+ m1: {
+ id: 'measure-1',
+ sources: {
+ s1: { title: 'Source A', settings: ['layer1'] },
+ },
+ },
+ },
+ layers: {
+ layer1: { layergroup: 'Some Group' },
+ },
+ },
+ productPicker: { selectedMeasurement: 'measure-1' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toEqual([]);
+ });
+
+ it('includes non-orbital-track layers in geographic projection', () => {
+ const state = makeState({
+ config: {
+ measurements: {
+ m1: {
+ id: 'measure-1',
+ sources: {
+ s1: { title: 'Normal Source', settings: ['layer1'] },
+ },
+ },
+ },
+ layers: {
+ layer1: { projections: { geographic: {} }, layergroup: 'Science' },
+ },
+ },
+ productPicker: { selectedMeasurement: 'measure-1' },
+ });
+ const result = getSourcesForProjection(state);
+ expect(result).toHaveLength(1);
+ expect(result[0].title).toBe('Normal Source');
+ });
+});
+
+describe('getCategoryConfig', () => {
+ it('returns categories[firstTab] when categoryType is "measurements"', () => {
+ const scienceCategory = { measurements: ['m1'] };
+ const state = makeState({
+ config: {
+ categories: { science: scienceCategory, hazards: {} },
+ categoryGroupOrder: ['science', 'hazards'],
+ },
+ productPicker: { categoryType: 'measurements' },
+ });
+ const result = getCategoryConfig(state);
+ expect(result).toBe(scienceCategory);
+ });
+
+ it('returns categories[categoryType] when categoryType is not "measurements"', () => {
+ const hazardsCategory = { measurements: ['m2'] };
+ const state = makeState({
+ config: {
+ categories: { science: {}, hazards: hazardsCategory },
+ categoryGroupOrder: ['science', 'hazards'],
+ },
+ productPicker: { categoryType: 'hazards' },
+ });
+ const result = getCategoryConfig(state);
+ expect(result).toBe(hazardsCategory);
+ });
+
+ it('returns undefined when categoryType does not match any category key', () => {
+ const state = makeState({
+ config: {
+ categories: { science: {}, hazards: {} },
+ categoryGroupOrder: ['science', 'hazards'],
+ },
+ productPicker: { categoryType: 'nonexistent' },
+ });
+ const result = getCategoryConfig(state);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns featured category when categoryType is "featured"', () => {
+ const featuredCategory = { All: { measurements: ['m1'] } };
+ const state = makeState({
+ config: {
+ categories: { science: {}, featured: featuredCategory },
+ categoryGroupOrder: ['science', 'featured'],
+ },
+ productPicker: { categoryType: 'featured' },
+ });
+ const result = getCategoryConfig(state);
+ expect(result).toBe(featuredCategory);
+ });
+
+ it('uses the first entry of categoryGroupOrder as firstTab', () => {
+ const firstTabCategory = { measurements: ['m1'] };
+ const state = makeState({
+ config: {
+ categories: { land: firstTabCategory, ocean: {} },
+ categoryGroupOrder: ['land', 'ocean'],
+ },
+ productPicker: { categoryType: 'measurements' },
+ });
+ const result = getCategoryConfig(state);
+ expect(result).toBe(firstTabCategory);
+ });
});
diff --git a/web/js/modules/projection/actions.test.js b/web/js/modules/projection/actions.test.js
index 22bc698b0..7fec2c990 100644
--- a/web/js/modules/projection/actions.test.js
+++ b/web/js/modules/projection/actions.test.js
@@ -1,3 +1,117 @@
-test('actions module test', () => {
+import changeProjection from './actions';
+import { CHANGE_PROJECTION } from './constants';
+import { onProjectionSwitch } from '../product-picker/actions';
+import { stop } from '../animation/actions';
+jest.mock('./constants', () => ({
+ CHANGE_PROJECTION: 'CHANGE_PROJECTION',
+}));
+
+jest.mock('../product-picker/actions', () => ({
+ onProjectionSwitch: jest.fn((id) => ({ type: 'ON_PROJECTION_SWITCH', id })),
+}));
+
+jest.mock('../animation/actions', () => ({
+ stop: jest.fn(() => ({ type: 'STOP' })),
+}));
+
+describe('changeProjection', () => {
+ let dispatch;
+
+ beforeEach(() => {
+ dispatch = jest.fn();
+ jest.clearAllMocks();
+ });
+
+ const buildGetState = (overrides = {}) => () => ({
+ config: {
+ projections: {
+ arctic: { crs: 'EPSG:3413' },
+ },
+ ...overrides.config,
+ },
+ animation: {
+ isPlaying: false,
+ ...(overrides.animation || {}),
+ },
+ });
+
+ it('returns a thunk function', () => {
+ const thunk = changeProjection('arctic');
+ expect(typeof thunk).toBe('function');
+ });
+
+ it('dispatches onProjectionSwitch with the given id', () => {
+ const getState = buildGetState();
+ changeProjection('arctic')(dispatch, getState);
+ expect(onProjectionSwitch).toHaveBeenCalledWith('arctic');
+ expect(dispatch).toHaveBeenCalledWith({ type: 'ON_PROJECTION_SWITCH', id: 'arctic' });
+ });
+
+ it('dispatches CHANGE_PROJECTION with id and selected projection', () => {
+ const getState = buildGetState();
+ changeProjection('arctic')(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith({
+ type: CHANGE_PROJECTION,
+ id: 'arctic',
+ selected: { crs: 'EPSG:3413' },
+ });
+ });
+
+ it('does not dispatch stop when animation is not playing', () => {
+ const getState = buildGetState({ animation: { isPlaying: false } });
+ changeProjection('arctic')(dispatch, getState);
+ expect(stop).not.toHaveBeenCalled();
+ });
+
+ it('dispatches stop when animation is playing', () => {
+ const getState = buildGetState({ animation: { isPlaying: true } });
+ changeProjection('arctic')(dispatch, getState);
+ expect(stop).toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({ type: 'STOP' });
+ });
+
+ it('dispatches in correct order when animation is playing', () => {
+ const getState = buildGetState({ animation: { isPlaying: true } });
+ changeProjection('arctic')(dispatch, getState);
+ const calls = dispatch.mock.calls.map((c) => c[0]);
+ expect(calls[0]).toEqual({ type: 'ON_PROJECTION_SWITCH', id: 'arctic' });
+ expect(calls[1]).toEqual({ type: 'STOP' });
+ expect(calls[2]).toEqual({ type: CHANGE_PROJECTION, id: 'arctic', selected: { crs: 'EPSG:3413' } });
+ });
+
+ it('dispatches in correct order when animation is not playing', () => {
+ const getState = buildGetState({ animation: { isPlaying: false } });
+ changeProjection('arctic')(dispatch, getState);
+ const calls = dispatch.mock.calls.map((c) => c[0]);
+ expect(calls[0]).toEqual({ type: 'ON_PROJECTION_SWITCH', id: 'arctic' });
+ expect(calls[1]).toEqual({ type: CHANGE_PROJECTION, id: 'arctic', selected: { crs: 'EPSG:3413' } });
+ expect(calls.length).toBe(2);
+ });
+
+ it('throws an error when projection id is invalid', () => {
+ const getState = buildGetState();
+ expect(() => changeProjection('invalid')(dispatch, getState)).toThrow(
+ 'Invalid projection: invalid',
+ );
+ });
+
+ it('throws an error when projections config is empty', () => {
+ const getState = () => ({
+ config: { projections: {} },
+ animation: { isPlaying: false },
+ });
+ expect(() => changeProjection('arctic')(dispatch, getState)).toThrow(
+ 'Invalid projection: arctic',
+ );
+ });
+
+ it('does not dispatch anything when projection is invalid', () => {
+ const getState = buildGetState();
+ try {
+ changeProjection('invalid')(dispatch, getState);
+ } catch {
+ }
+ expect(dispatch).not.toHaveBeenCalled();
+ });
});
diff --git a/web/js/modules/projection/reducer.test.js b/web/js/modules/projection/reducer.test.js
index 8378bdb57..c495a316a 100644
--- a/web/js/modules/projection/reducer.test.js
+++ b/web/js/modules/projection/reducer.test.js
@@ -1,3 +1,97 @@
-test('reducer module test', () => {
+import projectionReducer, { projectionState } from './reducer';
+import { CHANGE_PROJECTION } from './constants';
+jest.mock('./constants', () => ({
+ CHANGE_PROJECTION: 'CHANGE_PROJECTION',
+}));
+
+describe('projectionState', () => {
+ it('has a default id of geographic', () => {
+ expect(projectionState.id).toBe('geographic');
+ });
+
+ it('has a default selected of empty object', () => {
+ expect(projectionState.selected).toEqual({});
+ });
+});
+
+describe('projectionReducer', () => {
+ it('returns the default state when called with no arguments', () => {
+ const state = projectionReducer(undefined, {});
+ expect(state).toEqual(projectionState);
+ });
+
+ it('returns the existing state for an unknown action type', () => {
+ const existingState = { id: 'arctic', selected: { crs: 'EPSG:3413' } };
+ const state = projectionReducer(existingState, { type: 'UNKNOWN_ACTION' });
+ expect(state).toEqual(existingState);
+ });
+
+ it('returns the default state for an unknown action type when state is undefined', () => {
+ const state = projectionReducer(undefined, { type: 'UNKNOWN_ACTION' });
+ expect(state).toEqual(projectionState);
+ });
+
+ it('handles CHANGE_PROJECTION and updates id', () => {
+ const action = {
+ type: CHANGE_PROJECTION,
+ id: 'arctic',
+ selected: { crs: 'EPSG:3413' },
+ };
+ const state = projectionReducer(undefined, action);
+ expect(state.id).toBe('arctic');
+ });
+
+ it('handles CHANGE_PROJECTION and updates selected', () => {
+ const action = {
+ type: CHANGE_PROJECTION,
+ id: 'arctic',
+ selected: { crs: 'EPSG:3413' },
+ };
+ const state = projectionReducer(undefined, action);
+ expect(state.selected).toEqual({ crs: 'EPSG:3413' });
+ });
+
+ it('handles CHANGE_PROJECTION and preserves other state properties', () => {
+ const existingState = { id: 'geographic', selected: {}, extraProp: 'value' };
+ const action = {
+ type: CHANGE_PROJECTION,
+ id: 'antarctic',
+ selected: { crs: 'EPSG:3031' },
+ };
+ const state = projectionReducer(existingState, action);
+ expect(state.extraProp).toBe('value');
+ });
+
+ it('handles CHANGE_PROJECTION from a non-default initial state', () => {
+ const existingState = { id: 'arctic', selected: { crs: 'EPSG:3413' } };
+ const action = {
+ type: CHANGE_PROJECTION,
+ id: 'antarctic',
+ selected: { crs: 'EPSG:3031' },
+ };
+ const state = projectionReducer(existingState, action);
+ expect(state).toEqual({ id: 'antarctic', selected: { crs: 'EPSG:3031' } });
+ });
+
+ it('does not mutate the existing state on CHANGE_PROJECTION', () => {
+ const existingState = { id: 'geographic', selected: {} };
+ const action = {
+ type: CHANGE_PROJECTION,
+ id: 'arctic',
+ selected: { crs: 'EPSG:3413' },
+ };
+ projectionReducer(existingState, action);
+ expect(existingState).toEqual({ id: 'geographic', selected: {} });
+ });
+
+ it('handles CHANGE_PROJECTION with an empty selected object', () => {
+ const action = {
+ type: CHANGE_PROJECTION,
+ id: 'geographic',
+ selected: {},
+ };
+ const state = projectionReducer(undefined, action);
+ expect(state).toEqual({ id: 'geographic', selected: {} });
+ });
});
diff --git a/web/js/modules/projection/util.test.js b/web/js/modules/projection/util.test.js
index cd5bc636b..a00b808f5 100644
--- a/web/js/modules/projection/util.test.js
+++ b/web/js/modules/projection/util.test.js
@@ -1,5 +1,5 @@
import update from 'immutability-helper';
-import { mapLocationToProjState, getProjInitialState } from './util';
+import { mapLocationToProjState, getProjInitialState, parseProjection } from './util';
import fixtures from '../../fixtures';
const state = fixtures.getState();
@@ -12,8 +12,10 @@ const config = {
},
projections: {
'some-test-projection': proj,
+ geographic: { id: 'geographic' },
},
};
+
test('getProjInitialState with given projeciton [projection-initial-state]', () => {
const response = {
id: 'some-test-projection',
@@ -23,6 +25,7 @@ test('getProjInitialState with given projeciton [projection-initial-state]', ()
expect(initialState.id).toBe(response.id);
expect(initialState.selected.id).toBe(response.selected.id);
});
+
test('Default proj should be geographic [projection-default-geographic]', () => {
const emptyConfig = {
defaults: {},
@@ -34,6 +37,41 @@ test('Default proj should be geographic [projection-default-geographic]', () =>
const initialState = getProjInitialState(emptyConfig);
expect(initialState.id).toBe(response.id);
});
+
+test('getProjInitialState returns empty object for selected when projection not found', () => {
+ const emptyConfig = {
+ defaults: {},
+ };
+ const initialState = getProjInitialState(emptyConfig);
+ expect(initialState.selected).toEqual({});
+});
+
+test('getProjInitialState returns correct selected object when projection exists', () => {
+ const initialState = getProjInitialState(config);
+ expect(initialState.selected).toEqual(proj);
+});
+
+test('parseProjection returns the projection string when it exists in config', () => {
+ const result = parseProjection('some-test-projection', config);
+ expect(result).toBe('some-test-projection');
+});
+
+test('parseProjection returns geographic when projection does not exist in config', () => {
+ const result = parseProjection('non-existent-projection', config);
+ expect(result).toBe('geographic');
+});
+
+test('parseProjection returns geographic when config has no projections', () => {
+ const emptyConfig = { projections: {} };
+ const result = parseProjection('arctic', emptyConfig);
+ expect(result).toBe('geographic');
+});
+
+test('parseProjection returns geographic for undefined projection string', () => {
+ const result = parseProjection(undefined, config);
+ expect(result).toBe('geographic');
+});
+
test('mapLocationToProjState: Update proj:id key onload [projection-update-id]', () => {
const stateMock = {
config,
@@ -48,6 +86,67 @@ test('mapLocationToProjState: Update proj:id key onload [projection-update-id]',
expect(newState.proj.id).toBe('some-test-projection');
});
+test('mapLocationToProjState: sets geographic selected when no p or switch param', () => {
+ const localState = update(state, {
+ config: { $set: config },
+ });
+ const stateFromLocation = {
+ proj: { id: 'geographic' },
+ };
+ const newState = mapLocationToProjState({}, stateFromLocation, localState);
+ expect(newState.proj.selected).toEqual({ id: 'geographic' });
+});
+
+test('mapLocationToProjState: sets selected to undefined when geographic not in config', () => {
+ const configWithoutGeographic = {
+ defaults: { projection: 'some-test-projection' },
+ projections: {
+ 'some-test-projection': proj,
+ },
+ };
+ const localState = update(state, {
+ config: { $set: configWithoutGeographic },
+ });
+ const stateFromLocation = {
+ proj: { id: 'some-test-projection' },
+ };
+ const newState = mapLocationToProjState({}, stateFromLocation, localState);
+ expect(newState.proj.selected).toBeUndefined();
+});
+
+test('mapLocationToProjState: p parameter updates selected based on proj.id', () => {
+ const localState = update(state, {
+ config: { $set: config },
+ });
+ const stateFromLocation = {
+ proj: { id: 'some-test-projection' },
+ };
+ const newState = mapLocationToProjState({ p: 'some-test-projection' }, stateFromLocation, localState);
+ expect(newState.proj.selected).toEqual(proj);
+});
+
+test('mapLocationToProjState: p parameter does not update when proj.id not found in config', () => {
+ const localState = update(state, {
+ config: { $set: config },
+ });
+ const stateFromLocation = {
+ proj: { id: 'non-existent' },
+ };
+ const newState = mapLocationToProjState({ p: 'non-existent' }, stateFromLocation, localState);
+ expect(newState.proj.selected).toBeUndefined();
+});
+
+test('mapLocationToProjState: p parameter preserves existing proj properties', () => {
+ const localState = update(state, {
+ config: { $set: config },
+ });
+ const stateFromLocation = {
+ proj: { id: 'some-test-projection', extraProp: 'preserved' },
+ };
+ const newState = mapLocationToProjState({ p: 'some-test-projection' }, stateFromLocation, localState);
+ expect(newState.proj.extraProp).toBe('preserved');
+});
+
test('legacy switch parameter for projection [projection-legacy-switch]', () => {
const param = {
switch: 'some-test-projection',
@@ -68,3 +167,27 @@ test('legacy switch parameter for projection [projection-legacy-switch]', () =>
expect(newStateFromLocation.proj.id).toBe('some-test-projection');
expect(newStateFromLocation.proj.selected.id).toBe('some-test-projection');
});
+
+test('mapLocationToProjState: switch parameter does not update when id not found in config', () => {
+ const param = {
+ switch: 'non-existent-projection',
+ };
+ const stateFromLocation = {
+ proj,
+ };
+ const localState = update(state, {
+ config: { $set: config },
+ });
+ const newStateFromLocation = mapLocationToProjState(param, stateFromLocation, localState);
+ expect(newStateFromLocation.proj).toEqual(proj);
+});
+
+test('mapLocationToProjState: returns stateFromLocation unchanged when switch projection not in config', () => {
+ const param = { switch: 'invalid-proj' };
+ const stateFromLocation = { proj: { id: 'geographic', selected: { id: 'geographic' } } };
+ const localState = update(state, {
+ config: { $set: config },
+ });
+ const newState = mapLocationToProjState(param, stateFromLocation, localState);
+ expect(newState.proj.id).toBe('geographic');
+});
diff --git a/web/js/modules/screen-size/actions.test.js b/web/js/modules/screen-size/actions.test.js
index 22bc698b0..2ea435347 100644
--- a/web/js/modules/screen-size/actions.test.js
+++ b/web/js/modules/screen-size/actions.test.js
@@ -1,3 +1,141 @@
-test('actions module test', () => {
+import setScreenInfo from './actions';
+import { SET_SCREEN_INFO } from './constants';
+jest.mock('react-device-detect', () => ({
+ isMobileOnly: false,
+ isTablet: false,
+}));
+
+const reactDeviceDetect = require('react-device-detect');
+
+describe('setScreenInfo', () => {
+ beforeEach(() => {
+ reactDeviceDetect.isMobileOnly = false;
+ reactDeviceDetect.isTablet = false;
+ });
+
+ it('returns the correct action type', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = setScreenInfo();
+ expect(result.type).toBe(SET_SCREEN_INFO);
+ });
+
+ it('returns correct screenWidth and screenHeight from window', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1280 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 800 });
+
+ const result = setScreenInfo();
+ expect(result.screenWidth).toBe(1280);
+ expect(result.screenHeight).toBe(800);
+ });
+
+ it('sets isMobileDevice to true when screenWidth < 768', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 375 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 667 });
+
+ const result = setScreenInfo();
+ expect(result.isMobileDevice).toBe(true);
+ });
+
+ it('sets isMobileDevice to false when screenWidth >= 768 and no mobile flags', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = setScreenInfo();
+ expect(result.isMobileDevice).toBe(false);
+ });
+
+ it('sets isMobileDevice to true when isMobileOnly is true', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+ reactDeviceDetect.isMobileOnly = true;
+
+ const result = setScreenInfo();
+ expect(result.isMobileDevice).toBe(true);
+ });
+
+ it('sets isMobileDevice to true when isTablet is true', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+ reactDeviceDetect.isTablet = true;
+
+ const result = setScreenInfo();
+ expect(result.isMobileDevice).toBe(true);
+ });
+
+ it('sets orientation to portrait when screenHeight > screenWidth', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 375 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 667 });
+
+ const result = setScreenInfo();
+ expect(result.orientation).toBe('portrait');
+ });
+
+ it('sets orientation to landscape when screenWidth >= screenHeight', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = setScreenInfo();
+ expect(result.orientation).toBe('landscape');
+ });
+
+ it('sets orientation to landscape when screenWidth equals screenHeight', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 768 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = setScreenInfo();
+ expect(result.orientation).toBe('landscape');
+ });
+
+ it('sets isMobilePhone from isMobileOnly', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+ reactDeviceDetect.isMobileOnly = true;
+
+ const result = setScreenInfo();
+ expect(result.isMobilePhone).toBe(true);
+ });
+
+ it('sets isMobilePhone to false when isMobileOnly is false', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = setScreenInfo();
+ expect(result.isMobilePhone).toBe(false);
+ });
+
+ it('sets isMobileTablet from isTablet', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+ reactDeviceDetect.isTablet = true;
+
+ const result = setScreenInfo();
+ expect(result.isMobileTablet).toBe(true);
+ });
+
+ it('sets isMobileTablet to false when isTablet is false', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = setScreenInfo();
+ expect(result.isMobileTablet).toBe(false);
+ });
+
+ it('returns the full action shape', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = setScreenInfo();
+ expect(result).toEqual({
+ type: SET_SCREEN_INFO,
+ screenHeight: 768,
+ screenWidth: 1024,
+ isMobileDevice: false,
+ orientation: 'landscape',
+ isMobilePhone: false,
+ isMobileTablet: false,
+ });
+ });
});
diff --git a/web/js/modules/screen-size/reducer.test.js b/web/js/modules/screen-size/reducer.test.js
index 8378bdb57..6d5a33bae 100644
--- a/web/js/modules/screen-size/reducer.test.js
+++ b/web/js/modules/screen-size/reducer.test.js
@@ -1,3 +1,232 @@
-test('reducer module test', () => {
+import { initialState, getInitialState, screenSizeReducer } from './reducer';
+import { SET_SCREEN_INFO } from './constants';
+describe('initialState', () => {
+ it('has the correct default shape', () => {
+ expect(initialState).toEqual({
+ screenHeight: '',
+ screenWidth: '',
+ isMobileDevice: false,
+ orientation: '',
+ breakpoints: {},
+ isMobilePhone: false,
+ isMobileTablet: false,
+ });
+ });
+});
+
+describe('getInitialState', () => {
+ const breakpoints = {
+ extraSmall: 480,
+ small: 768,
+ medium: 992,
+ large: 1200,
+ };
+ it('returns full state shape when window is defined', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = getInitialState();
+ expect(result).toEqual({
+ breakpoints,
+ screenHeight: 768,
+ screenWidth: 1024,
+ isMobileDevice: false,
+ orientation: 'landscape',
+ isMobilePhone: false,
+ isMobileTablet: false,
+ });
+ });
+
+ it('sets isMobileDevice to true when screenWidth < 768', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 375 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 667 });
+
+ const result = getInitialState();
+ expect(result.isMobileDevice).toBe(true);
+ });
+
+ it('sets isMobileDevice to false when screenWidth >= 768', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 768 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 1024 });
+
+ const result = getInitialState();
+ expect(result.isMobileDevice).toBe(false);
+ });
+
+ it('sets orientation to portrait when screenHeight > screenWidth', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 375 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 667 });
+
+ const result = getInitialState();
+ expect(result.orientation).toBe('portrait');
+ });
+
+ it('sets orientation to landscape when screenWidth >= screenHeight', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = getInitialState();
+ expect(result.orientation).toBe('landscape');
+ });
+
+ it('sets orientation to landscape when screenWidth equals screenHeight', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 768 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = getInitialState();
+ expect(result.orientation).toBe('landscape');
+ });
+
+ it('always sets isMobilePhone to false', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 375 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 667 });
+
+ const result = getInitialState();
+ expect(result.isMobilePhone).toBe(false);
+ });
+
+ it('always sets isMobileTablet to false', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 375 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 667 });
+
+ const result = getInitialState();
+ expect(result.isMobileTablet).toBe(false);
+ });
+
+ it('returns the correct breakpoints', () => {
+ Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1024 });
+ Object.defineProperty(window, 'innerHeight', { writable: true, configurable: true, value: 768 });
+
+ const result = getInitialState();
+ expect(result.breakpoints).toEqual(breakpoints);
+ });
+});
+
+describe('screenSizeReducer', () => {
+ it('returns the initialState when no state is provided and action is unknown', () => {
+ const result = screenSizeReducer(undefined, { type: '@@INIT' });
+ expect(result).toEqual(initialState);
+ });
+
+ it('returns the existing state for an unknown action type', () => {
+ const state = { ...initialState, screenWidth: 1024 };
+ const result = screenSizeReducer(state, { type: 'UNKNOWN_ACTION' });
+ expect(result).toBe(state);
+ });
+
+ it('handles SET_SCREEN_INFO and returns updated state', () => {
+ const action = {
+ type: SET_SCREEN_INFO,
+ screenHeight: 768,
+ screenWidth: 1024,
+ isMobileDevice: false,
+ orientation: 'landscape',
+ isMobilePhone: false,
+ isMobileTablet: false,
+ };
+
+ const result = screenSizeReducer(initialState, action);
+ expect(result).toEqual({
+ ...initialState,
+ screenHeight: 768,
+ screenWidth: 1024,
+ isMobileDevice: false,
+ orientation: 'landscape',
+ isMobilePhone: false,
+ isMobileTablet: false,
+ });
+ });
+
+ it('updates isMobileDevice to true on SET_SCREEN_INFO', () => {
+ const action = {
+ type: SET_SCREEN_INFO,
+ screenHeight: 667,
+ screenWidth: 375,
+ isMobileDevice: true,
+ orientation: 'portrait',
+ isMobilePhone: true,
+ isMobileTablet: false,
+ };
+
+ const result = screenSizeReducer(initialState, action);
+ expect(result.isMobileDevice).toBe(true);
+ });
+
+ it('updates orientation to portrait on SET_SCREEN_INFO', () => {
+ const action = {
+ type: SET_SCREEN_INFO,
+ screenHeight: 667,
+ screenWidth: 375,
+ isMobileDevice: true,
+ orientation: 'portrait',
+ isMobilePhone: true,
+ isMobileTablet: false,
+ };
+
+ const result = screenSizeReducer(initialState, action);
+ expect(result.orientation).toBe('portrait');
+ });
+
+ it('updates isMobilePhone on SET_SCREEN_INFO', () => {
+ const action = {
+ type: SET_SCREEN_INFO,
+ screenHeight: 667,
+ screenWidth: 375,
+ isMobileDevice: true,
+ orientation: 'portrait',
+ isMobilePhone: true,
+ isMobileTablet: false,
+ };
+
+ const result = screenSizeReducer(initialState, action);
+ expect(result.isMobilePhone).toBe(true);
+ });
+
+ it('updates isMobileTablet on SET_SCREEN_INFO', () => {
+ const action = {
+ type: SET_SCREEN_INFO,
+ screenHeight: 768,
+ screenWidth: 1024,
+ isMobileDevice: true,
+ orientation: 'landscape',
+ isMobilePhone: false,
+ isMobileTablet: true,
+ };
+
+ const result = screenSizeReducer(initialState, action);
+ expect(result.isMobileTablet).toBe(true);
+ });
+
+ it('preserves existing state keys not touched by SET_SCREEN_INFO', () => {
+ const stateWithBreakpoints = { ...initialState, breakpoints: { small: 768 } };
+ const action = {
+ type: SET_SCREEN_INFO,
+ screenHeight: 768,
+ screenWidth: 1024,
+ isMobileDevice: false,
+ orientation: 'landscape',
+ isMobilePhone: false,
+ isMobileTablet: false,
+ };
+
+ const result = screenSizeReducer(stateWithBreakpoints, action);
+ expect(result.breakpoints).toEqual({ small: 768 });
+ });
+
+ it('does not mutate the original state on SET_SCREEN_INFO', () => {
+ const state = { ...initialState };
+ const action = {
+ type: SET_SCREEN_INFO,
+ screenHeight: 768,
+ screenWidth: 1024,
+ isMobileDevice: false,
+ orientation: 'landscape',
+ isMobilePhone: false,
+ isMobileTablet: false,
+ };
+
+ screenSizeReducer(state, action);
+ expect(state).toEqual(initialState);
+ });
});
diff --git a/web/js/modules/settings/actions.test.js b/web/js/modules/settings/actions.test.js
index 22bc698b0..3580fff37 100644
--- a/web/js/modules/settings/actions.test.js
+++ b/web/js/modules/settings/actions.test.js
@@ -1,3 +1,143 @@
-test('actions module test', () => {
+import {
+ changeTemperatureUnit,
+ changeDatelineVisibility,
+ changeCoordinateFormat,
+} from './actions';
+import {
+ CHANGE_TEMPERATURE_UNIT,
+ CHANGE_DATELINE_VISIBILITY,
+ CHANGE_COORDINATE_FORMAT,
+} from './constants';
+import safeLocalStorage from '../../util/local-storage';
+import util from '../../util/util';
+import { LOCATION_SEARCH_COORDINATE_FORMAT } from '../../util/constants';
+jest.mock('../../util/local-storage', () => ({
+ keys: {
+ GLOBAL_TEMPERATURE_UNIT: 'GLOBAL_TEMPERATURE_UNIT',
+ ALWAYS_SHOW_DATELINES: 'ALWAYS_SHOW_DATELINES',
+ COORDINATE_FORMAT: 'COORDINATE_FORMAT',
+ },
+ setItem: jest.fn(),
+ removeItem: jest.fn(),
+}));
+
+jest.mock('../../util/util', () => ({
+ events: {
+ trigger: jest.fn(),
+ },
+}));
+
+jest.mock('../../util/constants', () => ({
+ LOCATION_SEARCH_COORDINATE_FORMAT: 'LOCATION_SEARCH_COORDINATE_FORMAT',
+}));
+
+const { events } = util;
+const { GLOBAL_TEMPERATURE_UNIT, ALWAYS_SHOW_DATELINES, COORDINATE_FORMAT } = safeLocalStorage.keys;
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+describe('changeTemperatureUnit', () => {
+ test('returns correct action type and value when value is provided', () => {
+ const result = changeTemperatureUnit('celsius');
+ expect(result).toEqual({ type: CHANGE_TEMPERATURE_UNIT, value: 'celsius' });
+ });
+
+ test('calls setItem when value is truthy', () => {
+ changeTemperatureUnit('fahrenheit');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(GLOBAL_TEMPERATURE_UNIT, 'fahrenheit');
+ expect(safeLocalStorage.removeItem).not.toHaveBeenCalled();
+ });
+
+ test('calls removeItem when value is falsy (undefined)', () => {
+ changeTemperatureUnit(undefined);
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith(GLOBAL_TEMPERATURE_UNIT);
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ test('calls removeItem when value is null', () => {
+ changeTemperatureUnit(null);
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith(GLOBAL_TEMPERATURE_UNIT);
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ test('calls removeItem when value is empty string', () => {
+ changeTemperatureUnit('');
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith(GLOBAL_TEMPERATURE_UNIT);
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ test('returns value as undefined when no value is provided', () => {
+ const result = changeTemperatureUnit(undefined);
+ expect(result).toEqual({ type: CHANGE_TEMPERATURE_UNIT, value: undefined });
+ });
+});
+
+describe('changeDatelineVisibility', () => {
+ test('returns correct action type and value when value is provided', () => {
+ const result = changeDatelineVisibility(true);
+ expect(result).toEqual({ type: CHANGE_DATELINE_VISIBILITY, value: true });
+ });
+
+ test('calls setItem when value is truthy', () => {
+ changeDatelineVisibility(true);
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(ALWAYS_SHOW_DATELINES, true);
+ expect(safeLocalStorage.removeItem).not.toHaveBeenCalled();
+ });
+
+ test('calls removeItem when value is falsy (false)', () => {
+ changeDatelineVisibility(false);
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith(ALWAYS_SHOW_DATELINES);
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ test('calls removeItem when value is null', () => {
+ changeDatelineVisibility(null);
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith(ALWAYS_SHOW_DATELINES);
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ test('calls removeItem when value is undefined', () => {
+ changeDatelineVisibility(undefined);
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith(ALWAYS_SHOW_DATELINES);
+ expect(safeLocalStorage.setItem).not.toHaveBeenCalled();
+ });
+
+ test('returns falsy value in action when value is falsy', () => {
+ const result = changeDatelineVisibility(false);
+ expect(result).toEqual({ type: CHANGE_DATELINE_VISIBILITY, value: false });
+ });
+});
+
+describe('changeCoordinateFormat', () => {
+ test('returns correct action type and value', () => {
+ const result = changeCoordinateFormat('DD');
+ expect(result).toEqual({ type: CHANGE_COORDINATE_FORMAT, value: 'DD' });
+ });
+
+ test('calls setItem with correct key and value', () => {
+ changeCoordinateFormat('DMS');
+ expect(safeLocalStorage.setItem).toHaveBeenCalledWith(COORDINATE_FORMAT, 'DMS');
+ });
+
+ test('triggers LOCATION_SEARCH_COORDINATE_FORMAT event', () => {
+ changeCoordinateFormat('DDM');
+ expect(events.trigger).toHaveBeenCalledWith(LOCATION_SEARCH_COORDINATE_FORMAT);
+ });
+
+ test('calls setItem before triggering event', () => {
+ const callOrder = [];
+ safeLocalStorage.setItem.mockImplementation(() => callOrder.push('setItem'));
+ events.trigger.mockImplementation(() => callOrder.push('trigger'));
+
+ changeCoordinateFormat('DD');
+ expect(callOrder).toEqual(['setItem', 'trigger']);
+ });
+
+ test('returns correct value for different format strings', () => {
+ const result = changeCoordinateFormat('DDM');
+ expect(result).toEqual({ type: CHANGE_COORDINATE_FORMAT, value: 'DDM' });
+ });
});
diff --git a/web/js/modules/settings/reducer.test.js b/web/js/modules/settings/reducer.test.js
index 8378bdb57..dff7ca4b0 100644
--- a/web/js/modules/settings/reducer.test.js
+++ b/web/js/modules/settings/reducer.test.js
@@ -1,3 +1,174 @@
-test('reducer module test', () => {
+import {
+ initialState,
+ getInitialState,
+ settingsReducer,
+} from './reducer';
+import safeLocalStorage from '../../util/local-storage';
+jest.mock('../../util/local-storage', () => ({
+ keys: {
+ GLOBAL_TEMPERATURE_UNIT: 'GLOBAL_TEMPERATURE_UNIT',
+ ALWAYS_SHOW_DATELINES: 'ALWAYS_SHOW_DATELINES',
+ COORDINATE_FORMAT: 'COORDINATE_FORMAT',
+ },
+ getItem: jest.fn(),
+}));
+
+jest.mock('./constants', () => ({
+ CHANGE_TEMPERATURE_UNIT: 'CHANGE_TEMPERATURE_UNIT',
+ CHANGE_DATELINE_VISIBILITY: 'CHANGE_DATELINE_VISIBILITY',
+ CHANGE_COORDINATE_FORMAT: 'CHANGE_COORDINATE_FORMAT',
+}));
+
+import {
+ CHANGE_TEMPERATURE_UNIT,
+ CHANGE_DATELINE_VISIBILITY,
+ CHANGE_COORDINATE_FORMAT,
+} from './constants';
+
+beforeEach(() => {
+ jest.clearAllMocks();
+});
+
+describe('initialState', () => {
+ test('has correct default globalTemperatureUnit', () => {
+ expect(initialState.globalTemperatureUnit).toBe('');
+ });
+
+ test('has correct default alwaysShowDatelines', () => {
+ expect(initialState.alwaysShowDatelines).toBe(false);
+ });
+
+ test('has correct default coordinateFormat', () => {
+ expect(initialState.coordinateFormat).toBe('');
+ });
+});
+
+describe('getInitialState', () => {
+ test('returns default coordinateFormat when COORDINATE_FORMAT is null in storage', () => {
+ safeLocalStorage.getItem.mockImplementation((key) => {
+ if (key === 'COORDINATE_FORMAT') return null;
+ if (key === 'GLOBAL_TEMPERATURE_UNIT') return 'celsius';
+ if (key === 'ALWAYS_SHOW_DATELINES') return null;
+ return null;
+ });
+
+ const result = getInitialState();
+ expect(result.coordinateFormat).toBe('latlon-dd');
+ });
+
+ test('returns stored coordinateFormat when COORDINATE_FORMAT is not null', () => {
+ safeLocalStorage.getItem.mockImplementation((key) => {
+ if (key === 'COORDINATE_FORMAT') return 'DMS';
+ if (key === 'GLOBAL_TEMPERATURE_UNIT') return 'celsius';
+ if (key === 'ALWAYS_SHOW_DATELINES') return null;
+ return null;
+ });
+
+ const result = getInitialState();
+ expect(result.coordinateFormat).toBe('DMS');
+ });
+
+ test('returns stored globalTemperatureUnit when COORDINATE_FORMAT is null', () => {
+ safeLocalStorage.getItem.mockImplementation((key) => {
+ if (key === 'COORDINATE_FORMAT') return null;
+ if (key === 'GLOBAL_TEMPERATURE_UNIT') return 'fahrenheit';
+ if (key === 'ALWAYS_SHOW_DATELINES') return null;
+ return null;
+ });
+
+ const result = getInitialState();
+ expect(result.globalTemperatureUnit).toBe('fahrenheit');
+ });
+
+ test('returns stored globalTemperatureUnit when COORDINATE_FORMAT is not null', () => {
+ safeLocalStorage.getItem.mockImplementation((key) => {
+ if (key === 'COORDINATE_FORMAT') return 'DD';
+ if (key === 'GLOBAL_TEMPERATURE_UNIT') return 'fahrenheit';
+ if (key === 'ALWAYS_SHOW_DATELINES') return null;
+ return null;
+ });
+
+ const result = getInitialState();
+ expect(result.globalTemperatureUnit).toBe('fahrenheit');
+ });
+
+ test('returns alwaysShowDatelines as true when ALWAYS_SHOW_DATELINES is truthy in storage', () => {
+ safeLocalStorage.getItem.mockImplementation((key) => {
+ if (key === 'COORDINATE_FORMAT') return null;
+ if (key === 'GLOBAL_TEMPERATURE_UNIT') return null;
+ if (key === 'ALWAYS_SHOW_DATELINES') return 'true';
+ return null;
+ });
+
+ const result = getInitialState();
+ expect(result.alwaysShowDatelines).toBe(true);
+ });
+
+ test('returns alwaysShowDatelines as false when ALWAYS_SHOW_DATELINES is null in storage', () => {
+ safeLocalStorage.getItem.mockImplementation((key) => {
+ if (key === 'COORDINATE_FORMAT') return null;
+ if (key === 'GLOBAL_TEMPERATURE_UNIT') return null;
+ if (key === 'ALWAYS_SHOW_DATELINES') return null;
+ return null;
+ });
+
+ const result = getInitialState();
+ expect(result.alwaysShowDatelines).toBe(false);
+ });
+});
+
+describe('settingsReducer', () => {
+ test('returns initialState when no state is provided and action is unknown', () => {
+ const result = settingsReducer(undefined, { type: 'UNKNOWN' });
+ expect(result).toEqual(initialState);
+ });
+
+ test('returns current state for unknown action type', () => {
+ const currentState = { globalTemperatureUnit: 'celsius', alwaysShowDatelines: true, coordinateFormat: 'DD' };
+ const result = settingsReducer(currentState, { type: 'UNKNOWN' });
+ expect(result).toEqual(currentState);
+ });
+
+ test('handles CHANGE_TEMPERATURE_UNIT and updates globalTemperatureUnit', () => {
+ const result = settingsReducer(initialState, { type: CHANGE_TEMPERATURE_UNIT, value: 'celsius' });
+ expect(result.globalTemperatureUnit).toBe('celsius');
+ });
+
+ test('CHANGE_TEMPERATURE_UNIT does not mutate other state fields', () => {
+ const currentState = { globalTemperatureUnit: '', alwaysShowDatelines: true, coordinateFormat: 'DMS' };
+ const result = settingsReducer(currentState, { type: CHANGE_TEMPERATURE_UNIT, value: 'fahrenheit' });
+ expect(result.alwaysShowDatelines).toBe(true);
+ expect(result.coordinateFormat).toBe('DMS');
+ });
+
+ test('handles CHANGE_DATELINE_VISIBILITY and updates alwaysShowDatelines', () => {
+ const result = settingsReducer(initialState, { type: CHANGE_DATELINE_VISIBILITY, value: true });
+ expect(result.alwaysShowDatelines).toBe(true);
+ });
+
+ test('CHANGE_DATELINE_VISIBILITY does not mutate other state fields', () => {
+ const currentState = { globalTemperatureUnit: 'celsius', alwaysShowDatelines: false, coordinateFormat: 'DD' };
+ const result = settingsReducer(currentState, { type: CHANGE_DATELINE_VISIBILITY, value: true });
+ expect(result.globalTemperatureUnit).toBe('celsius');
+ expect(result.coordinateFormat).toBe('DD');
+ });
+
+ test('handles CHANGE_COORDINATE_FORMAT and updates coordinateFormat', () => {
+ const result = settingsReducer(initialState, { type: CHANGE_COORDINATE_FORMAT, value: 'DDM' });
+ expect(result.coordinateFormat).toBe('DDM');
+ });
+
+ test('CHANGE_COORDINATE_FORMAT does not mutate other state fields', () => {
+ const currentState = { globalTemperatureUnit: 'celsius', alwaysShowDatelines: true, coordinateFormat: '' };
+ const result = settingsReducer(currentState, { type: CHANGE_COORDINATE_FORMAT, value: 'DMS' });
+ expect(result.globalTemperatureUnit).toBe('celsius');
+ expect(result.alwaysShowDatelines).toBe(true);
+ });
+
+ test('reducer returns a new state object and does not mutate the original', () => {
+ const currentState = { globalTemperatureUnit: '', alwaysShowDatelines: false, coordinateFormat: '' };
+ const result = settingsReducer(currentState, { type: CHANGE_TEMPERATURE_UNIT, value: 'celsius' });
+ expect(result).not.toBe(currentState);
+ });
});
diff --git a/web/js/modules/settings/util.test.js b/web/js/modules/settings/util.test.js
index 52737bc5d..7a2b665cd 100644
--- a/web/js/modules/settings/util.test.js
+++ b/web/js/modules/settings/util.test.js
@@ -1,14 +1,177 @@
import {
unitConvert,
convertPaletteValue,
+ getTemperatureUnitFromAbbrev,
+ getAbbrevFromTemperatureUnit,
+ checkTemperatureUnitConversion,
} from './util';
-test('is unitConvert successfully converting units', () => {
- const actual = unitConvert(32, 'Fahrenheit', 'Celsius');
- expect(actual).toBe(0);
+describe('getTemperatureUnitFromAbbrev', () => {
+ test('returns Kelvin for K', () => {
+ expect(getTemperatureUnitFromAbbrev('K')).toBe('Kelvin');
+ });
+
+ test('returns Celsius for °C', () => {
+ expect(getTemperatureUnitFromAbbrev('°C')).toBe('Celsius');
+ });
+
+ test('returns Fahrenheit for °F', () => {
+ expect(getTemperatureUnitFromAbbrev('°F')).toBe('Fahrenheit');
+ });
+
+ test('returns undefined for unknown abbreviation', () => {
+ expect(getTemperatureUnitFromAbbrev('X')).toBeUndefined();
+ });
+});
+
+describe('getAbbrevFromTemperatureUnit', () => {
+ test('returns K for Kelvin', () => {
+ expect(getAbbrevFromTemperatureUnit('Kelvin')).toBe('K');
+ });
+
+ test('returns °C for Celsius', () => {
+ expect(getAbbrevFromTemperatureUnit('Celsius')).toBe('°C');
+ });
+
+ test('returns °F for Fahrenheit', () => {
+ expect(getAbbrevFromTemperatureUnit('Fahrenheit')).toBe('°F');
+ });
+
+ test('returns undefined for unknown unit', () => {
+ expect(getAbbrevFromTemperatureUnit('Unknown')).toBeUndefined();
+ });
+});
+
+describe('unitConvert', () => {
+ test('converts Fahrenheit to Celsius', () => {
+ expect(unitConvert(32, 'Fahrenheit', 'Celsius')).toBe(0);
+ });
+
+ test('converts Celsius to Fahrenheit', () => {
+ expect(unitConvert(0, 'Celsius', 'Fahrenheit')).toBe(32);
+ });
+
+ test('converts Celsius to Kelvin', () => {
+ expect(unitConvert(0, 'Celsius', 'Kelvin')).toBe(273.15);
+ });
+
+ test('converts Fahrenheit to Kelvin', () => {
+ expect(unitConvert(32, 'Fahrenheit', 'Kelvin')).toBeCloseTo(273.15, 1);
+ });
+
+ test('converts Kelvin to Celsius', () => {
+ expect(unitConvert(273.15, 'Kelvin', 'Celsius')).toBeCloseTo(0, 1);
+ });
+
+ test('converts Kelvin to Fahrenheit', () => {
+ expect(unitConvert(273.15, 'Kelvin', 'Fahrenheit')).toBeCloseTo(32, 1);
+ });
+
+ test('returns undefined for unknown initialUnit', () => {
+ expect(unitConvert(100, 'Unknown', 'Celsius')).toBeUndefined();
+ });
+
+ test('returns undefined when initialUnit is Celsius but targetUnit is unknown', () => {
+ expect(unitConvert(100, 'Celsius', 'Unknown')).toBeUndefined();
+ });
+
+ test('returns undefined when initialUnit is Fahrenheit but targetUnit is unknown', () => {
+ expect(unitConvert(100, 'Fahrenheit', 'Unknown')).toBeUndefined();
+ });
+
+ test('returns undefined when initialUnit is Kelvin but targetUnit is unknown', () => {
+ expect(unitConvert(100, 'Kelvin', 'Unknown')).toBeUndefined();
+ });
});
-test('is convertPaletteValue returning the correct string', () => {
- const actual = convertPaletteValue('32', 'Fahrenheit', 'Celsius');
- expect(actual).toBe('0.00 °C');
+describe('checkTemperatureUnitConversion', () => {
+ test('needsConversion is true when units differ', () => {
+ const result = checkTemperatureUnitConversion('°C', 'Fahrenheit');
+ expect(result.needsConversion).toBe(true);
+ });
+
+ test('needsConversion is false when units are the same', () => {
+ const result = checkTemperatureUnitConversion('°C', 'Celsius');
+ expect(result.needsConversion).toBe(false);
+ });
+
+ test('needsConversion is false when legendTempUnit is undefined (unknown abbrev)', () => {
+ const result = checkTemperatureUnitConversion('X', 'Celsius');
+ expect(result.needsConversion).toBe(false);
+ });
+
+ test('needsConversion is false when globalTemperatureUnit is falsy', () => {
+ const result = checkTemperatureUnitConversion('°C', '');
+ expect(result.needsConversion).toBe(false);
+ });
+
+ test('needsConversion is false when both units and globalTemperatureUnit are falsy', () => {
+ const result = checkTemperatureUnitConversion('', '');
+ expect(result.needsConversion).toBe(false);
+ });
+
+ test('returns correct legendTempUnit', () => {
+ const result = checkTemperatureUnitConversion('K', 'Celsius');
+ expect(result.legendTempUnit).toBe('Kelvin');
+ });
+
+ test('returns undefined legendTempUnit for unknown abbreviation', () => {
+ const result = checkTemperatureUnitConversion('Z', 'Celsius');
+ expect(result.legendTempUnit).toBeUndefined();
+ });
+
+ test('needsConversion is true when Kelvin abbrev differs from globalTemperatureUnit Fahrenheit', () => {
+ const result = checkTemperatureUnitConversion('K', 'Fahrenheit');
+ expect(result.needsConversion).toBe(true);
+ });
+});
+
+describe('convertPaletteValue', () => {
+ test('converts a single value from Fahrenheit to Celsius', () => {
+ expect(convertPaletteValue('32', 'Fahrenheit', 'Celsius')).toBe('0.00 °C');
+ });
+
+ test('converts a single value from Celsius to Fahrenheit', () => {
+ expect(convertPaletteValue('0', 'Celsius', 'Fahrenheit')).toBe('32.00 °F');
+ });
+
+ test('converts a single value from Celsius to Kelvin', () => {
+ expect(convertPaletteValue('0', 'Celsius', 'Kelvin')).toBe('273.15 K');
+ });
+
+ test('converts a single value from Kelvin to Celsius', () => {
+ expect(convertPaletteValue('273.15', 'Kelvin', 'Celsius')).toBe('0.00 °C');
+ });
+
+ test('converts a range value (double dash) from Celsius to Fahrenheit', () => {
+ expect(convertPaletteValue('0.0 – 100.0', 'Celsius', 'Fahrenheit')).toBe('32.00 – 212.00 °F');
+ });
+
+ test('converts a range value from Fahrenheit to Celsius', () => {
+ expect(convertPaletteValue('32.0 – 212.0', 'Fahrenheit', 'Celsius')).toBe('0.00 – 100.00 °C');
+ });
+
+ test('converts a range value from Kelvin to Fahrenheit', () => {
+ const result = convertPaletteValue('273.15 – 373.15', 'Kelvin', 'Fahrenheit');
+ expect(result).toMatch(/°F$/);
+ });
+
+ test('handles a prefixed single value (e.g. < 180.0)', () => {
+ const result = convertPaletteValue('< 32.0', 'Fahrenheit', 'Celsius');
+ expect(result).toBe('< 0.00 °C');
+ });
+
+ test('handles a prefixed range min value', () => {
+ const result = convertPaletteValue('≥ 0.0 – 100.0', 'Celsius', 'Fahrenheit');
+ expect(result).toBe('≥ 32.00 – 212.00 °F');
+ });
+
+ test('converts a single Kelvin value to Celsius', () => {
+ expect(convertPaletteValue('373.15', 'Kelvin', 'Celsius')).toBe('100.00 °C');
+ });
+
+ test('converts a range from Celsius to Kelvin', () => {
+ const result = convertPaletteValue('0.0 – 100.0', 'Celsius', 'Kelvin');
+ expect(result).toBe('273.15 – 373.15 K');
+ });
});
diff --git a/web/js/modules/sidebar/actions.test.js b/web/js/modules/sidebar/actions.test.js
index 22bc698b0..7fdcd83a3 100644
--- a/web/js/modules/sidebar/actions.test.js
+++ b/web/js/modules/sidebar/actions.test.js
@@ -1,3 +1,95 @@
-test('actions module test', () => {
+import {
+ changeTab,
+ toggleSidebarCollapse,
+ collapseSidebar,
+ expandSidebar,
+} from './actions';
+import {
+ CHANGE_TAB,
+ TOGGLE_COLLAPSE,
+ COLLAPSE_SIDEBAR,
+ EXPAND_SIDEBAR,
+ TOGGLE_MOBILE_COLLAPSE,
+ MOBILE_COLLAPSE_SIDEBAR,
+ MOBILE_EXPAND_SIDEBAR,
+} from './constants';
+describe('changeTab', () => {
+ it('dispatches CHANGE_TAB when activeTab differs from str', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ sidebar: { activeTab: 'home' } });
+
+ changeTab('settings')(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: CHANGE_TAB, activeTab: 'settings' });
+ });
+
+ it('does not dispatch when activeTab equals str', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ sidebar: { activeTab: 'settings' } });
+
+ changeTab('settings')(dispatch, getState);
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
+
+describe('toggleSidebarCollapse', () => {
+ it('dispatches TOGGLE_MOBILE_COLLAPSE on mobile', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ screenSize: { isMobileDevice: true } });
+
+ toggleSidebarCollapse()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: TOGGLE_MOBILE_COLLAPSE });
+ });
+
+ it('dispatches TOGGLE_COLLAPSE on desktop', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ screenSize: { isMobileDevice: false } });
+
+ toggleSidebarCollapse()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: TOGGLE_COLLAPSE });
+ });
+});
+
+describe('collapseSidebar', () => {
+ it('dispatches MOBILE_COLLAPSE_SIDEBAR on mobile', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ screenSize: { isMobileDevice: true } });
+
+ collapseSidebar()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: MOBILE_COLLAPSE_SIDEBAR });
+ });
+
+ it('dispatches COLLAPSE_SIDEBAR on desktop', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ screenSize: { isMobileDevice: false } });
+
+ collapseSidebar()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: COLLAPSE_SIDEBAR });
+ });
+});
+
+describe('expandSidebar', () => {
+ it('dispatches MOBILE_EXPAND_SIDEBAR on mobile', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ screenSize: { isMobileDevice: true } });
+
+ expandSidebar()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: MOBILE_EXPAND_SIDEBAR });
+ });
+
+ it('dispatches EXPAND_SIDEBAR on desktop', () => {
+ const dispatch = jest.fn();
+ const getState = jest.fn().mockReturnValue({ screenSize: { isMobileDevice: false } });
+
+ expandSidebar()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({ type: EXPAND_SIDEBAR });
+ });
});
diff --git a/web/js/modules/sidebar/reducers.test.js b/web/js/modules/sidebar/reducers.test.js
index 04cce6a78..178f8e1e9 100644
--- a/web/js/modules/sidebar/reducers.test.js
+++ b/web/js/modules/sidebar/reducers.test.js
@@ -1,3 +1,124 @@
-test('reducers module test', () => {
+import sidebarReducer, { sidebarState } from './reducers';
+import {
+ CHANGE_TAB,
+ TOGGLE_COLLAPSE,
+ COLLAPSE_SIDEBAR,
+ EXPAND_SIDEBAR,
+ TOGGLE_MOBILE_COLLAPSE,
+ MOBILE_COLLAPSE_SIDEBAR,
+ MOBILE_EXPAND_SIDEBAR,
+} from './constants';
+const defaultState = {
+ isCollapsed: false,
+ activeTab: 'layers',
+ previousTab: null,
+ mobileCollapsed: true,
+};
+
+describe('sidebarReducer', () => {
+ it('returns the default state when no action is matched', () => {
+ const state = sidebarReducer(defaultState, { type: '@@INIT' });
+ expect(state).toEqual(defaultState);
+ });
+
+ it('returns the initial sidebarState when state is undefined', () => {
+ const state = sidebarReducer(undefined, { type: '@@INIT' });
+ expect(state).toEqual(sidebarState);
+ });
+
+ it('handles CHANGE_TAB by updating activeTab and setting previousTab', () => {
+ const state = sidebarReducer(defaultState, { type: CHANGE_TAB, activeTab: 'events' });
+ expect(state.activeTab).toBe('events');
+ expect(state.previousTab).toBe('layers');
+ });
+
+ it('handles TOGGLE_COLLAPSE by flipping isCollapsed from false to true', () => {
+ const state = sidebarReducer(
+ {...defaultState, isCollapsed: false }, { type: TOGGLE_COLLAPSE },
+ );
+ expect(state.isCollapsed).toBe(true);
+ });
+
+ it('handles TOGGLE_COLLAPSE by flipping isCollapsed from true to false', () => {
+ const state = sidebarReducer(
+ {...defaultState, isCollapsed: true }, { type: TOGGLE_COLLAPSE },
+ );
+ expect(state.isCollapsed).toBe(false);
+ });
+
+ it('handles COLLAPSE_SIDEBAR by setting isCollapsed to true', () => {
+ const state = sidebarReducer(
+ {...defaultState, isCollapsed: false }, { type: COLLAPSE_SIDEBAR },
+ );
+ expect(state.isCollapsed).toBe(true);
+ });
+
+ it('handles COLLAPSE_SIDEBAR when already collapsed', () => {
+ const state = sidebarReducer(
+ {...defaultState, isCollapsed: true }, { type: COLLAPSE_SIDEBAR },
+ );
+ expect(state.isCollapsed).toBe(true);
+ });
+
+ it('handles EXPAND_SIDEBAR by setting isCollapsed to false', () => {
+ const state = sidebarReducer(
+ {...defaultState, isCollapsed: true }, { type: EXPAND_SIDEBAR },
+ );
+ expect(state.isCollapsed).toBe(false);
+ });
+
+ it('handles EXPAND_SIDEBAR when already expanded', () => {
+ const state = sidebarReducer(
+ {...defaultState, isCollapsed: false }, { type: EXPAND_SIDEBAR },
+ );
+ expect(state.isCollapsed).toBe(false);
+ });
+
+ it('handles TOGGLE_MOBILE_COLLAPSE by flipping mobileCollapsed from true to false', () => {
+ const state = sidebarReducer(
+ {...defaultState, mobileCollapsed: true }, { type: TOGGLE_MOBILE_COLLAPSE },
+ );
+ expect(state.mobileCollapsed).toBe(false);
+ });
+
+ it('handles TOGGLE_MOBILE_COLLAPSE by flipping mobileCollapsed from false to true', () => {
+ const state = sidebarReducer(
+ {...defaultState, mobileCollapsed: false }, { type: TOGGLE_MOBILE_COLLAPSE },
+ );
+ expect(state.mobileCollapsed).toBe(true);
+ });
+
+ it('handles MOBILE_COLLAPSE_SIDEBAR by setting mobileCollapsed to true', () => {
+ const state = sidebarReducer(
+ {...defaultState, mobileCollapsed: false }, { type: MOBILE_COLLAPSE_SIDEBAR },
+ );
+ expect(state.mobileCollapsed).toBe(true);
+ });
+
+ it('handles MOBILE_COLLAPSE_SIDEBAR when already collapsed', () => {
+ const state = sidebarReducer(
+ {...defaultState, mobileCollapsed: true }, { type: MOBILE_COLLAPSE_SIDEBAR },
+ );
+ expect(state.mobileCollapsed).toBe(true);
+ });
+
+ it('handles MOBILE_EXPAND_SIDEBAR by setting mobileCollapsed to false', () => {
+ const state = sidebarReducer(
+ {...defaultState, mobileCollapsed: true }, { type: MOBILE_EXPAND_SIDEBAR },
+ );
+ expect(state.mobileCollapsed).toBe(false);
+ });
+
+ it('handles MOBILE_EXPAND_SIDEBAR when already expanded', () => {
+ const state = sidebarReducer(
+ {...defaultState, mobileCollapsed: false }, { type: MOBILE_EXPAND_SIDEBAR },
+ );
+ expect(state.mobileCollapsed).toBe(false);
+ });
+
+ it('does not mutate the original state', () => {
+ const frozen = Object.freeze({ ...defaultState });
+ expect(() => sidebarReducer(frozen, { type: COLLAPSE_SIDEBAR })).not.toThrow();
+ });
});
diff --git a/web/js/modules/sidebar/util.test.js b/web/js/modules/sidebar/util.test.js
index 4072f4f95..8e6371d3e 100644
--- a/web/js/modules/sidebar/util.test.js
+++ b/web/js/modules/sidebar/util.test.js
@@ -1,3 +1,114 @@
-test('util module test', () => {
+import mapLocationToSidebarState from './util';
+const defaultState = {
+ sidebar: {
+ isCollapsed: false,
+ activeTab: 'layers',
+ previousTab: null,
+ mobileCollapsed: true,
+ },
+};
+
+const defaultStateFromLocation = {
+ sidebar: {},
+};
+
+describe('mapLocationToSidebarState', () => {
+ it('sets activeTab to "events" when parameters.e is truthy', () => {
+ const result = mapLocationToSidebarState(
+ { e: true },
+ defaultStateFromLocation,
+ defaultState,
+ {},
+ );
+ expect(result.sidebar.activeTab).toBe('events');
+ });
+
+ it('sets activeTab to "download" when parameters.sh is truthy', () => {
+ const result = mapLocationToSidebarState(
+ { sh: true },
+ defaultStateFromLocation,
+ defaultState,
+ {},
+ );
+ expect(result.sidebar.activeTab).toBe('download');
+ });
+
+ it('sets activeTab to "layers" when neither parameters.e nor parameters.sh are set', () => {
+ const result = mapLocationToSidebarState(
+ {},
+ defaultStateFromLocation,
+ defaultState,
+ {},
+ );
+ expect(result.sidebar.activeTab).toBe('layers');
+ });
+
+ it('prioritizes "events" over "download" when both parameters.e and parameters.sh are truthy', () => {
+ const result = mapLocationToSidebarState(
+ { e: true, sh: true },
+ defaultStateFromLocation,
+ defaultState,
+ {},
+ );
+ expect(result.sidebar.activeTab).toBe('events');
+ });
+
+ it('preserves existing sidebar state properties from state.sidebar', () => {
+ const stateWithExtras = {
+ sidebar: {
+ isCollapsed: true,
+ activeTab: 'layers',
+ previousTab: 'events',
+ mobileCollapsed: false,
+ },
+ };
+ const result = mapLocationToSidebarState(
+ {},
+ defaultStateFromLocation,
+ stateWithExtras,
+ {},
+ );
+ expect(result.sidebar.isCollapsed).toBe(true);
+ expect(result.sidebar.previousTab).toBe('events');
+ expect(result.sidebar.mobileCollapsed).toBe(false);
+ });
+
+ it('returns an updated stateFromLocation object with the sidebar property set', () => {
+ const stateFromLocation = { sidebar: {}, someOtherProp: 'value' };
+ const result = mapLocationToSidebarState(
+ { sh: true },
+ stateFromLocation,
+ defaultState,
+ {},
+ );
+ expect(result.someOtherProp).toBe('value');
+ expect(result.sidebar).toBeDefined();
+ });
+
+ it('does not mutate the original stateFromLocation object', () => {
+ const stateFromLocation = Object.freeze({ sidebar: {} });
+ expect(() =>
+ mapLocationToSidebarState({}, stateFromLocation, defaultState, {}),
+ ).not.toThrow();
+ });
+
+ it('does not mutate the original state object', () => {
+ const frozenState = Object.freeze({
+ sidebar: Object.freeze({ ...defaultState.sidebar }),
+ });
+ expect(() =>
+ mapLocationToSidebarState({}, defaultStateFromLocation, frozenState, {}),
+ ).not.toThrow();
+ });
+
+ it('sets activeTab to "layers" when parameters.e is falsy and parameters.sh is falsy', () => {
+ const result = mapLocationToSidebarState(
+ { e: null, sh: 0 },
+ defaultStateFromLocation,
+ defaultState,
+ {},
+ );
+ expect(result.sidebar.activeTab).toBe('layers');
+ });
});
diff --git a/web/js/modules/smart-handoff/actions.test.js b/web/js/modules/smart-handoff/actions.test.js
index 22bc698b0..7c1c7f235 100644
--- a/web/js/modules/smart-handoff/actions.test.js
+++ b/web/js/modules/smart-handoff/actions.test.js
@@ -1,3 +1,307 @@
-test('actions module test', () => {
+import {
+ selectCollection,
+ fetchAvailableTools,
+ validateLayersConceptIds,
+} from './actions';
+import {
+ SELECT_COLLECTION,
+ SET_AVAILABLE_TOOLS,
+ SET_VALID_LAYERS_CONCEPTIDS,
+} from './constants';
+import { getCollectionsUrl, getConceptUrl } from './selectors';
+import { cmrFetch } from '../../util/cmr';
+jest.mock('./selectors');
+jest.mock('../../util/cmr');
+
+describe('selectCollection', () => {
+ it('returns the correct action object', () => {
+ const result = selectCollection('C1234-PODAAC', 'layer-1');
+ expect(result).toEqual({
+ type: SELECT_COLLECTION,
+ conceptId: 'C1234-PODAAC',
+ layerId: 'layer-1',
+ });
+ });
+
+ it('handles undefined arguments', () => {
+ const result = selectCollection(undefined, undefined);
+ expect(result).toEqual({
+ type: SELECT_COLLECTION,
+ conceptId: undefined,
+ layerId: undefined,
+ });
+ });
+});
+
+describe('fetchAvailableTools', () => {
+ let dispatch;
+ let getState;
+
+ beforeEach(() => {
+ dispatch = jest.fn();
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('dispatches SET_AVAILABLE_TOOLS with tools on success', async () => {
+ const mockState = {
+ config: {
+ features: {
+ smartHandoffs: [
+ { conceptId: 'T1000', toolName: 'ToolA' },
+ { conceptId: 'T2000', toolName: 'ToolB' },
+ ],
+ },
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ getConceptUrl.mockImplementation(() => (conceptId) => `https://cmr.nasa.gov/concept/${conceptId}`);
+
+ cmrFetch
+ .mockResolvedValueOnce({ json: async () => ({ PotentialAction: { actionA: true } }) })
+ .mockResolvedValueOnce({ json: async () => ({ PotentialAction: { actionB: false } }) });
+
+ await fetchAvailableTools()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_AVAILABLE_TOOLS,
+ availableTools: [
+ { name: 'ToolA', action: { actionA: true } },
+ { name: 'ToolB', action: { actionB: false } },
+ ],
+ requestFailed: false,
+ });
+ });
+
+ it('dispatches SET_AVAILABLE_TOOLS with empty tools and requestFailed true on error', async () => {
+ const mockState = {
+ config: {
+ features: {
+ smartHandoffs: [{ conceptId: 'T1000', toolName: 'ToolA' }],
+ },
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+ getConceptUrl.mockImplementation(() => () => 'https://cmr.nasa.gov/concept/T1000');
+ cmrFetch.mockRejectedValueOnce(new Error('Network failure'));
+
+ await fetchAvailableTools()(dispatch, getState);
+
+ expect(console.error).toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_AVAILABLE_TOOLS,
+ availableTools: [],
+ requestFailed: true,
+ });
+ });
+
+ it('dispatches SET_AVAILABLE_TOOLS with empty arrays when smartHandoffs is empty', async () => {
+ const mockState = {
+ config: {
+ features: {
+ smartHandoffs: [],
+ },
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+ getConceptUrl.mockImplementation(() => () => '');
+
+ await fetchAvailableTools()(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_AVAILABLE_TOOLS,
+ availableTools: [],
+ requestFailed: false,
+ });
+ });
+});
+
+describe('validateLayersConceptIds', () => {
+ let dispatch;
+ let getState;
+
+ beforeEach(() => {
+ dispatch = jest.fn();
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('dispatches SET_VALID_LAYERS_CONCEPTIDS with valid layers on success', async () => {
+ const mockState = {
+ smartHandoffs: {
+ validatedConceptIds: {},
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ const layers = [
+ { id: 'layer-1', conceptIds: [{ value: 'C1000' }, { value: 'C2000' }] },
+ ];
+
+ getCollectionsUrl.mockImplementation(() => (id) => `https://cmr.nasa.gov/collections/${id}`);
+
+ cmrFetch
+ .mockResolvedValueOnce({ json: async () => ({ feed: { entry: [{ id: 'C1000' }] } }) })
+ .mockResolvedValueOnce({ json: async () => ({ feed: { entry: [] } }) });
+
+ await validateLayersConceptIds(layers)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [layers[0]],
+ validatedConceptIds: { C1000: true, C2000: false },
+ requestFailed: false,
+ });
+ });
+
+ it('skips fetching for already validated concept IDs', async () => {
+ const mockState = {
+ smartHandoffs: {
+ validatedConceptIds: { C1000: true },
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ const layers = [
+ { id: 'layer-1', conceptIds: [{ value: 'C1000' }] },
+ ];
+
+ getCollectionsUrl.mockImplementation(() => (id) => `https://cmr.nasa.gov/collections/${id}`);
+
+ await validateLayersConceptIds(layers)(dispatch, getState);
+
+ expect(cmrFetch).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [layers[0]],
+ validatedConceptIds: { C1000: true },
+ requestFailed: false,
+ });
+ });
+
+ it('excludes layers with no valid concept IDs', async () => {
+ const mockState = {
+ smartHandoffs: {
+ validatedConceptIds: {},
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ const layers = [
+ { id: 'layer-1', conceptIds: [{ value: 'C9999' }] },
+ ];
+
+ getCollectionsUrl.mockImplementation(() => (id) => `https://cmr.nasa.gov/collections/${id}`);
+ cmrFetch.mockResolvedValueOnce({ json: async () => ({ feed: { entry: [] } }) });
+
+ await validateLayersConceptIds(layers)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [],
+ validatedConceptIds: { C9999: false },
+ requestFailed: false,
+ });
+ });
+
+ it('handles layers with no conceptIds array', async () => {
+ const mockState = {
+ smartHandoffs: {
+ validatedConceptIds: {},
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ const layers = [{ id: 'layer-no-ids' }];
+
+ getCollectionsUrl.mockImplementation(() => (id) => `https://cmr.nasa.gov/collections/${id}`);
+
+ await validateLayersConceptIds(layers)(dispatch, getState);
+
+ expect(cmrFetch).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [],
+ validatedConceptIds: {},
+ requestFailed: false,
+ });
+ });
+
+ it('handles layers with conceptIds containing falsy values', async () => {
+ const mockState = {
+ smartHandoffs: {
+ validatedConceptIds: {},
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ const layers = [{ id: 'layer-1', conceptIds: [{ value: null }, { value: '' }] }];
+
+ getCollectionsUrl.mockImplementation(() => (id) => `https://cmr.nasa.gov/collections/${id}`);
+
+ await validateLayersConceptIds(layers)(dispatch, getState);
+
+ expect(cmrFetch).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [],
+ validatedConceptIds: {},
+ requestFailed: false,
+ });
+ });
+
+ it('dispatches SET_VALID_LAYERS_CONCEPTIDS with requestFailed true on error', async () => {
+ const mockState = {
+ smartHandoffs: {
+ validatedConceptIds: {},
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ const layers = [{ id: 'layer-1', conceptIds: [{ value: 'C1000' }] }];
+
+ getCollectionsUrl.mockImplementation(() => () => 'https://cmr.nasa.gov/collections/C1000');
+ cmrFetch.mockRejectedValueOnce(new Error('Fetch error'));
+
+ await validateLayersConceptIds(layers)(dispatch, getState);
+
+ expect(console.error).toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [],
+ validatedConceptIds: {},
+ requestFailed: true,
+ });
+ });
+
+ it('handles feed.entry missing from response gracefully', async () => {
+ const mockState = {
+ smartHandoffs: {
+ validatedConceptIds: {},
+ },
+ };
+ getState = jest.fn().mockReturnValue(mockState);
+
+ const layers = [{ id: 'layer-1', conceptIds: [{ value: 'C3000' }] }];
+
+ getCollectionsUrl.mockImplementation(() => (id) => `https://cmr.nasa.gov/collections/${id}`);
+ cmrFetch.mockResolvedValueOnce({ json: async () => ({}) });
+
+ await validateLayersConceptIds(layers)(dispatch, getState);
+
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [],
+ validatedConceptIds: { C3000: false },
+ requestFailed: false,
+ });
+ });
});
diff --git a/web/js/modules/smart-handoff/reducer.test.js b/web/js/modules/smart-handoff/reducer.test.js
index 8378bdb57..22f2db2c8 100644
--- a/web/js/modules/smart-handoff/reducer.test.js
+++ b/web/js/modules/smart-handoff/reducer.test.js
@@ -1,3 +1,186 @@
-test('reducer module test', () => {
+import {
+ smartHandoffReducer,
+ initialState,
+ getInitialState,
+} from './reducer';
+import {
+ SELECT_COLLECTION,
+ SET_AVAILABLE_TOOLS,
+ SET_VALID_LAYERS_CONCEPTIDS,
+} from './constants';
+describe('initialState', () => {
+ it('has the correct default shape', () => {
+ expect(initialState).toEqual({
+ conceptId: null,
+ layerId: null,
+ availableTools: [],
+ validatedLayers: [],
+ validatedConceptIds: {},
+ isLoadingTools: true,
+ isValidatingCollections: true,
+ requestFailed: false,
+ });
+ });
+});
+
+describe('getInitialState', () => {
+ it('merges initialState with configuredTools from config', () => {
+ const config = {
+ features: {
+ smartHandoffs: [{ conceptId: 'T1000', toolName: 'ToolA' }],
+ },
+ };
+ const result = getInitialState(config);
+ expect(result).toEqual({
+ ...initialState,
+ configuredTools: config.features.smartHandoffs,
+ });
+ });
+
+ it('sets configuredTools to an empty array when smartHandoffs is empty', () => {
+ const config = { features: { smartHandoffs: [] } };
+ const result = getInitialState(config);
+ expect(result.configuredTools).toEqual([]);
+ });
+});
+
+describe('smartHandoffReducer', () => {
+ it('returns initialState when called with no arguments', () => {
+ const result = smartHandoffReducer(undefined, {});
+ expect(result).toEqual(initialState);
+ });
+
+ it('returns current state for an unknown action type', () => {
+ const state = { ...initialState, conceptId: 'C9999' };
+ const result = smartHandoffReducer(state, { type: 'UNKNOWN_ACTION' });
+ expect(result).toBe(state);
+ });
+
+ describe('SELECT_COLLECTION', () => {
+ it('sets conceptId and layerId from the action', () => {
+ const action = {
+ type: SELECT_COLLECTION,
+ conceptId: 'C1234-PODAAC',
+ layerId: 'layer-abc',
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.conceptId).toBe('C1234-PODAAC');
+ expect(result.layerId).toBe('layer-abc');
+ });
+
+ it('preserves the rest of the state', () => {
+ const action = {
+ type: SELECT_COLLECTION,
+ conceptId: 'C1234-PODAAC',
+ layerId: 'layer-abc',
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.availableTools).toEqual(initialState.availableTools);
+ expect(result.validatedLayers).toEqual(initialState.validatedLayers);
+ expect(result.isLoadingTools).toBe(initialState.isLoadingTools);
+ expect(result.isValidatingCollections).toBe(initialState.isValidatingCollections);
+ expect(result.requestFailed).toBe(initialState.requestFailed);
+ });
+
+ it('overwrites a previously set conceptId and layerId', () => {
+ const stateWithSelection = {
+ ...initialState,
+ conceptId: 'C0000',
+ layerId: 'old-layer',
+ };
+ const action = {
+ type: SELECT_COLLECTION,
+ conceptId: 'C9999',
+ layerId: 'new-layer',
+ };
+ const result = smartHandoffReducer(stateWithSelection, action);
+ expect(result.conceptId).toBe('C9999');
+ expect(result.layerId).toBe('new-layer');
+ });
+ });
+
+ describe('SET_AVAILABLE_TOOLS', () => {
+ it('sets availableTools, sets isLoadingTools to false, and sets requestFailed', () => {
+ const tools = [{ name: 'ToolA', action: {} }];
+ const action = {
+ type: SET_AVAILABLE_TOOLS,
+ availableTools: tools,
+ requestFailed: false,
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.availableTools).toEqual(tools);
+ expect(result.isLoadingTools).toBe(false);
+ expect(result.requestFailed).toBe(false);
+ });
+
+ it('sets requestFailed to true when the request failed', () => {
+ const action = {
+ type: SET_AVAILABLE_TOOLS,
+ availableTools: [],
+ requestFailed: true,
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.requestFailed).toBe(true);
+ expect(result.isLoadingTools).toBe(false);
+ expect(result.availableTools).toEqual([]);
+ });
+
+ it('preserves the rest of the state', () => {
+ const action = {
+ type: SET_AVAILABLE_TOOLS,
+ availableTools: [],
+ requestFailed: false,
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.conceptId).toBe(initialState.conceptId);
+ expect(result.layerId).toBe(initialState.layerId);
+ expect(result.validatedLayers).toEqual(initialState.validatedLayers);
+ expect(result.isValidatingCollections).toBe(initialState.isValidatingCollections);
+ });
+ });
+
+ describe('SET_VALID_LAYERS_CONCEPTIDS', () => {
+ it('sets validatedLayers, validatedConceptIds, sets isValidatingCollections to false, and sets requestFailed', () => {
+ const validatedLayers = [{ id: 'layer-1' }];
+ const validatedConceptIds = { C1000: true, C2000: false };
+ const action = {
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers,
+ validatedConceptIds,
+ requestFailed: false,
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.validatedLayers).toEqual(validatedLayers);
+ expect(result.validatedConceptIds).toEqual(validatedConceptIds);
+ expect(result.isValidatingCollections).toBe(false);
+ expect(result.requestFailed).toBe(false);
+ });
+
+ it('sets requestFailed to true when the request failed', () => {
+ const action = {
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [],
+ validatedConceptIds: {},
+ requestFailed: true,
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.requestFailed).toBe(true);
+ expect(result.isValidatingCollections).toBe(false);
+ });
+
+ it('preserves the rest of the state', () => {
+ const action = {
+ type: SET_VALID_LAYERS_CONCEPTIDS,
+ validatedLayers: [],
+ validatedConceptIds: {},
+ requestFailed: false,
+ };
+ const result = smartHandoffReducer(initialState, action);
+ expect(result.conceptId).toBe(initialState.conceptId);
+ expect(result.layerId).toBe(initialState.layerId);
+ expect(result.availableTools).toEqual(initialState.availableTools);
+ expect(result.isLoadingTools).toBe(initialState.isLoadingTools);
+ });
+ });
});
diff --git a/web/js/modules/smart-handoff/selectors.test.js b/web/js/modules/smart-handoff/selectors.test.js
index c4e1cdccf..9678742e8 100644
--- a/web/js/modules/smart-handoff/selectors.test.js
+++ b/web/js/modules/smart-handoff/selectors.test.js
@@ -1,3 +1,225 @@
-test('selectors module test', () => {
+import {
+ getBaseCmrUrl,
+ getGranulesUrl,
+ getCollectionsUrl,
+ getConceptUrl,
+ getValidLayersForHandoffs,
+} from './selectors';
+import { getActiveLayers, memoizedAvailable } from '../layers/selectors';
+import { buildGranulesUrl, buildCollectionsUrl, buildConceptUrl } from '../../util/cmr';
+jest.mock('../layers/selectors');
+jest.mock('../../util/cmr');
+
+const mockState = {
+ config: {
+ features: {
+ cmr: {
+ url: 'https://cmr.nasa.gov',
+ },
+ },
+ },
+ proj: {
+ id: 'geographic',
+ },
+};
+
+describe('getBaseCmrUrl', () => {
+ it('returns the CMR base URL from state', () => {
+ expect(getBaseCmrUrl(mockState)).toBe('https://cmr.nasa.gov');
+ });
+});
+
+describe('getGranulesUrl', () => {
+ it('returns a function', () => {
+ const result = getGranulesUrl(mockState);
+ expect(typeof result).toBe('function');
+ });
+
+ it('calls buildGranulesUrl with the base URL and provided params', () => {
+ buildGranulesUrl.mockReturnValue('https://cmr.nasa.gov/granules?foo=bar');
+ const getUrl = getGranulesUrl(mockState);
+ const result = getUrl({ foo: 'bar' });
+ expect(buildGranulesUrl).toHaveBeenCalledWith('https://cmr.nasa.gov', { foo: 'bar' });
+ expect(result).toBe('https://cmr.nasa.gov/granules?foo=bar');
+ });
+
+ it('calls buildGranulesUrl with empty params by default', () => {
+ buildGranulesUrl.mockReturnValue('https://cmr.nasa.gov/granules');
+ const getUrl = getGranulesUrl(mockState);
+ const result = getUrl();
+ expect(buildGranulesUrl).toHaveBeenCalledWith('https://cmr.nasa.gov', {});
+ expect(result).toBe('https://cmr.nasa.gov/granules');
+ });
+});
+
+describe('getCollectionsUrl', () => {
+ it('returns a function', () => {
+ const result = getCollectionsUrl(mockState);
+ expect(typeof result).toBe('function');
+ });
+
+ it('calls buildCollectionsUrl with the base URL and provided id', () => {
+ buildCollectionsUrl.mockReturnValue('https://cmr.nasa.gov/collections/C1000');
+ const getUrl = getCollectionsUrl(mockState);
+ const result = getUrl('C1000');
+ expect(buildCollectionsUrl).toHaveBeenCalledWith('https://cmr.nasa.gov', 'C1000');
+ expect(result).toBe('https://cmr.nasa.gov/collections/C1000');
+ });
+
+ it('passes undefined id to buildCollectionsUrl when not provided', () => {
+ buildCollectionsUrl.mockReturnValue('https://cmr.nasa.gov/collections/undefined');
+ const getUrl = getCollectionsUrl(mockState);
+ getUrl(undefined);
+ expect(buildCollectionsUrl).toHaveBeenCalledWith('https://cmr.nasa.gov', undefined);
+ });
+});
+
+describe('getConceptUrl', () => {
+ it('returns a function', () => {
+ const result = getConceptUrl(mockState);
+ expect(typeof result).toBe('function');
+ });
+
+ it('calls buildConceptUrl with the base URL and provided id', () => {
+ buildConceptUrl.mockReturnValue('https://cmr.nasa.gov/concepts/T1000');
+ const getUrl = getConceptUrl(mockState);
+ const result = getUrl('T1000');
+ expect(buildConceptUrl).toHaveBeenCalledWith('https://cmr.nasa.gov', 'T1000');
+ expect(result).toBe('https://cmr.nasa.gov/concepts/T1000');
+ });
+
+ it('passes undefined id to buildConceptUrl when not provided', () => {
+ buildConceptUrl.mockReturnValue('https://cmr.nasa.gov/concepts/undefined');
+ const getUrl = getConceptUrl(mockState);
+ getUrl(undefined);
+ expect(buildConceptUrl).toHaveBeenCalledWith('https://cmr.nasa.gov', undefined);
+ });
+});
+
+describe('getValidLayersForHandoffs', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ const makeLayer = (overrides = {}) => ({
+ id: 'layer-1',
+ projections: { geographic: {} },
+ disableSmartHandoff: false,
+ conceptIds: [{ type: 'STD', value: 'C1000', version: '1' }],
+ ...overrides,
+ });
+
+ it('returns layers that are available, in projection, not disabled, and have valid conceptIds', () => {
+ const layer = makeLayer();
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([layer]);
+ });
+
+ it('excludes layers that are not available', () => {
+ const layer = makeLayer();
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => false);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes layers not in the current projection', () => {
+ const layer = makeLayer({ projections: { arctic: {} } });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes layers with disableSmartHandoff set to true', () => {
+ const layer = makeLayer({ disableSmartHandoff: true });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes layers with no conceptIds', () => {
+ const layer = makeLayer({ conceptIds: undefined });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes layers with an empty conceptIds array', () => {
+ const layer = makeLayer({ conceptIds: [] });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes layers where all conceptIds are missing type', () => {
+ const layer = makeLayer({ conceptIds: [{ value: 'C1000', version: '1' }] });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes layers where all conceptIds are missing value', () => {
+ const layer = makeLayer({ conceptIds: [{ type: 'STD', version: '1' }] });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('excludes layers where all conceptIds are missing version', () => {
+ const layer = makeLayer({ conceptIds: [{ type: 'STD', value: 'C1000' }] });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
+
+ it('includes a layer if at least one conceptId has all required fields', () => {
+ const layer = makeLayer({
+ conceptIds: [
+ { type: 'STD', value: 'C1000', version: '1' },
+ { value: 'C2000' },
+ ],
+ });
+ getActiveLayers.mockReturnValue([layer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([layer]);
+ });
+
+ it('filters multiple layers correctly', () => {
+ const validLayer = makeLayer({ id: 'layer-valid' });
+ const invalidLayer = makeLayer({ id: 'layer-invalid', disableSmartHandoff: true });
+ getActiveLayers.mockReturnValue([validLayer, invalidLayer]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([validLayer]);
+ });
+
+ it('returns an empty array when there are no active layers', () => {
+ getActiveLayers.mockReturnValue([]);
+ memoizedAvailable.mockReturnValue(() => true);
+
+ const result = getValidLayersForHandoffs(mockState);
+ expect(result).toEqual([]);
+ });
});
diff --git a/web/js/modules/smart-handoff/util.test.js b/web/js/modules/smart-handoff/util.test.js
index 4072f4f95..5b47fe6e7 100644
--- a/web/js/modules/smart-handoff/util.test.js
+++ b/web/js/modules/smart-handoff/util.test.js
@@ -1,3 +1,349 @@
-test('util module test', () => {
+import openEarthDataSearch, {
+ getStartEndDates,
+ parseSmartHandoff,
+ serializeSmartHandoff,
+} from './util';
+import { TOOLS_EARTHDATA_SEARCH } from './constants';
+import googleTagManager from 'googleTagManager';
+import { parseTemplate } from 'url-template';
+jest.mock('googleTagManager', () => ({ pushEvent: jest.fn() }));
+jest.mock('url-template', () => ({ parseTemplate: jest.fn() }));
+
+describe('getStartEndDates', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('returns day-bounded dates for a non-granule layer', () => {
+ const layer = { type: 'wms', id: 'layer-1' };
+ const selectedDate = '2023-06-15';
+ const granuleLayers = {};
+ const result = getStartEndDates(layer, selectedDate, granuleLayers);
+ expect(result.startDate).toBe('2023-06-15T00:00:00.000Z');
+ expect(result.endDate).toBe('2023-06-15T23:59:59.999Z');
+ });
+
+ it('returns granule-bounded dates for a granule layer with dates', () => {
+ const layer = { type: 'granule', id: 'layer-g' };
+ const selectedDate = '2023-06-15';
+ const granuleLayers = {
+ 'layer-g': {
+ dates: ['2023-06-15T01:00:00.000Z', '2023-06-15T06:00:00.000Z', '2023-06-15T12:00:00.000Z'],
+ },
+ };
+ const result = getStartEndDates(layer, selectedDate, granuleLayers);
+ expect(result.startDate).toBe('2023-06-15T01:00:00.000Z');
+ expect(result.endDate).toBe('2023-06-15T12:00:00.000Z');
+ });
+
+ it('returns day-bounded dates for a granule layer with empty granuleLayers object', () => {
+ const layer = { type: 'granule', id: 'layer-g' };
+ const selectedDate = '2023-06-15';
+ const granuleLayers = {};
+ const result = getStartEndDates(layer, selectedDate, granuleLayers);
+ expect(result.startDate).toBe('2023-06-15T00:00:00.000Z');
+ expect(result.endDate).toBe('2023-06-15T23:59:59.999Z');
+ });
+
+ it('formats startDate and endDate with the correct UTC time for non-granule layers', () => {
+ const layer = { type: 'wms', id: 'layer-1' };
+ const selectedDate = '2020-01-01';
+ const granuleLayers = {};
+ const result = getStartEndDates(layer, selectedDate, granuleLayers);
+ expect(result.startDate).toMatch(/^2020-01-01T00:00:00\.000Z$/);
+ expect(result.endDate).toMatch(/^2020-01-01T23:59:59\.999Z$/);
+ });
+
+ it('returns an object with startDate and endDate keys', () => {
+ const layer = { type: 'wms', id: 'layer-1' };
+ const result = getStartEndDates(layer, '2023-01-01', {});
+ expect(result).toHaveProperty('startDate');
+ expect(result).toHaveProperty('endDate');
+ });
+});
+
+describe('parseSmartHandoff', () => {
+ it('splits the state string into layerId and conceptId', () => {
+ const result = parseSmartHandoff('layer-abc,C1234-PODAAC');
+ expect(result).toEqual({ layerId: 'layer-abc', conceptId: 'C1234-PODAAC' });
+ });
+
+ it('handles a state string with extra commas gracefully', () => {
+ const result = parseSmartHandoff('layer-abc,C1234,extra');
+ expect(result.layerId).toBe('layer-abc');
+ expect(result.conceptId).toBe('C1234');
+ });
+
+ it('returns undefined for both values when given an empty string', () => {
+ const result = parseSmartHandoff(',');
+ expect(result.layerId).toBe('');
+ expect(result.conceptId).toBe('');
+ });
+});
+
+describe('serializeSmartHandoff', () => {
+ it('returns layerId,conceptId when activeTab is download and both ids are set', () => {
+ const currentItemState = { layerId: 'layer-1', conceptId: 'C1000' };
+ const state = { sidebar: { activeTab: 'download' } };
+ const result = serializeSmartHandoff(currentItemState, state);
+ expect(result).toBe('layer-1,C1000');
+ });
+
+ it('returns undefined when activeTab is not download', () => {
+ const currentItemState = { layerId: 'layer-1', conceptId: 'C1000' };
+ const state = { sidebar: { activeTab: 'layers' } };
+ const result = serializeSmartHandoff(currentItemState, state);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when layerId is missing', () => {
+ const currentItemState = { layerId: null, conceptId: 'C1000' };
+ const state = { sidebar: { activeTab: 'download' } };
+ const result = serializeSmartHandoff(currentItemState, state);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when conceptId is missing', () => {
+ const currentItemState = { layerId: 'layer-1', conceptId: null };
+ const state = { sidebar: { activeTab: 'download' } };
+ const result = serializeSmartHandoff(currentItemState, state);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when both layerId and conceptId are missing', () => {
+ const currentItemState = { layerId: null, conceptId: null };
+ const state = { sidebar: { activeTab: 'download' } };
+ const result = serializeSmartHandoff(currentItemState, state);
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when sidebar state is missing', () => {
+ const currentItemState = { layerId: 'layer-1', conceptId: 'C1000' };
+ const state = {};
+ const result = serializeSmartHandoff(currentItemState, state);
+ expect(result).toBeUndefined();
+ });
+});
+
+describe('openEarthDataSearch', () => {
+ let mockExpand;
+ let mockWindowOpen;
+
+ beforeEach(() => {
+ mockExpand = jest.fn().mockReturnValue('https://search.earthdata.nasa.gov/search?p=C1000');
+ parseTemplate.mockReturnValue({ expand: mockExpand });
+ mockWindowOpen = jest.spyOn(window, 'open').mockImplementation(() => {});
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ const makeTools = (action) => [
+ { name: TOOLS_EARTHDATA_SEARCH, action },
+ ];
+
+ const makeAction = (overrides = {}) => ({
+ Target: { UrlTemplate: 'https://search.earthdata.nasa.gov/search{?p,q}' },
+ QueryInput: [],
+ ...overrides,
+ });
+
+ it('opens a new window with the expanded URL', () => {
+ const tools = makeTools(makeAction());
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: true,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockWindowOpen).toHaveBeenCalledWith(
+ 'https://search.earthdata.nasa.gov/search?p=C1000',
+ '_blank',
+ );
+ });
+
+ it('pushes a googleTagManager event with the selected collection', () => {
+ const tools = makeTools(makeAction());
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'smart_handoffs_open_eds_data_query',
+ selected_collection: 'C1000',
+ });
+ });
+
+ it('does nothing when no matching tool is found', () => {
+ const tools = [{ name: 'other-tool', action: makeAction() }];
+ const options = { conceptId: 'C1000' };
+ openEarthDataSearch(tools, options);
+ expect(mockWindowOpen).not.toHaveBeenCalled();
+ expect(googleTagManager.pushEvent).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when the matching tool has no action', () => {
+ const tools = [{ name: TOOLS_EARTHDATA_SEARCH }];
+ const options = { conceptId: 'C1000' };
+ openEarthDataSearch(tools, options);
+ expect(mockWindowOpen).not.toHaveBeenCalled();
+ expect(googleTagManager.pushEvent).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when tools array is empty', () => {
+ openEarthDataSearch([], { conceptId: 'C1000' });
+ expect(mockWindowOpen).not.toHaveBeenCalled();
+ expect(googleTagManager.pushEvent).not.toHaveBeenCalled();
+ });
+
+ it('builds temporal range param from QueryInput', () => {
+ const tools = makeTools(makeAction({
+ QueryInput: [{ ValueType: 'temporalRange', ValueName: 'temporal' }],
+ }));
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockExpand).toHaveBeenCalledWith(
+ expect.objectContaining({ temporal: '2023-01-01T00:00:00.000Z,2023-01-01T23:59:59.999Z' }),
+ );
+ });
+
+ it('builds bounding box param from QueryInput when showBoundingBox is true', () => {
+ const tools = makeTools(makeAction({
+ QueryInput: [{ ValueType: 'https://schema.org/box', ValueName: 'bounding_box' }],
+ }));
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: true,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockExpand).toHaveBeenCalledWith(
+ expect.objectContaining({ bounding_box: '-180,-90,180,90' }),
+ );
+ });
+
+ it('sets bounding box param to undefined when showBoundingBox is false', () => {
+ const tools = makeTools(makeAction({
+ QueryInput: [{ ValueType: 'https://schema.org/box', ValueName: 'bounding_box' }],
+ }));
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockExpand).toHaveBeenCalledWith(
+ expect.objectContaining({ bounding_box: undefined }),
+ );
+ });
+
+ it('builds projection param from QueryInput', () => {
+ const tools = makeTools(makeAction({
+ QueryInput: [{ ValueType: 'https://spatialreference.org/ref/epsg/', ValueName: 'proj' }],
+ }));
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockExpand).toHaveBeenCalledWith(
+ expect.objectContaining({ proj: 'EPSG:4326' }),
+ );
+ });
+
+ it('builds conceptId param from QueryInput with ValueType conceptId', () => {
+ const tools = makeTools(makeAction({
+ QueryInput: [{ ValueType: 'conceptId', ValueName: 'p' }],
+ }));
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockExpand).toHaveBeenCalledWith(
+ expect.objectContaining({ p: 'C1000' }),
+ );
+ });
+
+ it('builds conceptId param from QueryInput with ValueType edscTextQuery', () => {
+ const tools = makeTools(makeAction({
+ QueryInput: [{ ValueType: 'edscTextQuery', ValueName: 'q' }],
+ }));
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockExpand).toHaveBeenCalledWith(
+ expect.objectContaining({ q: 'C1000' }),
+ );
+ });
+
+ it('omits temporal param when startDate and endDate are missing', () => {
+ const tools = makeTools(makeAction({
+ QueryInput: [{ ValueType: 'temporalRange', ValueName: 'temporal' }],
+ }));
+ const options = {
+ projection: 'EPSG:4326',
+ conceptId: 'C1000',
+ startDate: undefined,
+ endDate: undefined,
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(mockExpand).toHaveBeenCalledWith(
+ expect.not.objectContaining({ temporal: expect.anything() }),
+ );
+ });
+
+ it('logs errors for undefined option values', () => {
+ const tools = makeTools(makeAction());
+ const options = {
+ projection: undefined,
+ conceptId: 'C1000',
+ startDate: '2023-01-01T00:00:00.000Z',
+ endDate: '2023-01-01T23:59:59.999Z',
+ currentExtent: { southWest: '-180,-90', northEast: '180,90' },
+ showBoundingBox: false,
+ };
+ openEarthDataSearch(tools, options);
+ expect(console.error).toHaveBeenCalledWith('projection is undefined.');
+ });
});
diff --git a/web/js/modules/tour/actions.test.js b/web/js/modules/tour/actions.test.js
index 22bc698b0..6d0e1ac70 100644
--- a/web/js/modules/tour/actions.test.js
+++ b/web/js/modules/tour/actions.test.js
@@ -1,3 +1,46 @@
-test('actions module test', () => {
+import { startTour, selectStory, endTour } from './actions';
+import { START, UPDATE_SELECTED, END_TOUR } from './constants';
+describe('startTour', () => {
+ it('returns an action with type START', () => {
+ const result = startTour();
+ expect(result).toEqual({ type: START });
+ });
+
+ it('returns an object', () => {
+ expect(typeof startTour()).toBe('object');
+ });
+});
+
+describe('selectStory', () => {
+ it('returns an action with type UPDATE_SELECTED and the given id', () => {
+ const result = selectStory(42);
+ expect(result).toEqual({ type: UPDATE_SELECTED, id: 42 });
+ });
+
+ it('handles string ids', () => {
+ const result = selectStory('story-1');
+ expect(result).toEqual({ type: UPDATE_SELECTED, id: 'story-1' });
+ });
+
+ it('handles undefined id', () => {
+ const result = selectStory(undefined);
+ expect(result).toEqual({ type: UPDATE_SELECTED, id: undefined });
+ });
+
+ it('handles null id', () => {
+ const result = selectStory(null);
+ expect(result).toEqual({ type: UPDATE_SELECTED, id: null });
+ });
+});
+
+describe('endTour', () => {
+ it('returns an action with type END_TOUR', () => {
+ const result = endTour();
+ expect(result).toEqual({ type: END_TOUR });
+ });
+
+ it('returns an object', () => {
+ expect(typeof endTour()).toBe('object');
+ });
});
diff --git a/web/js/modules/tour/reducers.test.js b/web/js/modules/tour/reducers.test.js
index 04cce6a78..1af8e3b15 100644
--- a/web/js/modules/tour/reducers.test.js
+++ b/web/js/modules/tour/reducers.test.js
@@ -1,3 +1,90 @@
-test('reducers module test', () => {
+import tourReducer from './reducers';
+import {
+ START, UPDATE_SELECTED, END_TOUR, TOUR_KEY_PRESS_CLOSE,
+} from './constants';
+const INITIAL_STATE = {
+ selected: '',
+ active: false,
+};
+
+describe('tourReducer', () => {
+ it('returns the initial state when no state is provided', () => {
+ const result = tourReducer(undefined, {});
+ expect(result).toEqual(INITIAL_STATE);
+ });
+
+ it('returns the current state for an unknown action type', () => {
+ const state = { selected: 'story-1', active: true };
+ const result = tourReducer(state, { type: 'UNKNOWN_ACTION' });
+ expect(result).toBe(state);
+ });
+
+ describe('END_TOUR', () => {
+ it('sets selected to empty string and active to false', () => {
+ const state = { selected: 'story-1', active: true };
+ const result = tourReducer(state, { type: END_TOUR });
+ expect(result).toEqual({ selected: '', active: false });
+ });
+
+ it('does not mutate the original state', () => {
+ const state = { selected: 'story-1', active: true };
+ tourReducer(state, { type: END_TOUR });
+ expect(state).toEqual({ selected: 'story-1', active: true });
+ });
+ });
+
+ describe('TOUR_KEY_PRESS_CLOSE', () => {
+ it('sets selected to empty string and active to false', () => {
+ const state = { selected: 'story-2', active: true };
+ const result = tourReducer(state, { type: TOUR_KEY_PRESS_CLOSE });
+ expect(result).toEqual({ selected: '', active: false });
+ });
+
+ it('does not mutate the original state', () => {
+ const state = { selected: 'story-2', active: true };
+ tourReducer(state, { type: TOUR_KEY_PRESS_CLOSE });
+ expect(state).toEqual({ selected: 'story-2', active: true });
+ });
+ });
+
+ describe('START', () => {
+ it('sets selected to empty string and active to true', () => {
+ const state = { selected: 'story-3', active: false };
+ const result = tourReducer(state, { type: START });
+ expect(result).toEqual({ selected: '', active: true });
+ });
+
+ it('does not mutate the original state', () => {
+ const state = { selected: 'story-3', active: false };
+ tourReducer(state, { type: START });
+ expect(state).toEqual({ selected: 'story-3', active: false });
+ });
+ });
+
+ describe('UPDATE_SELECTED', () => {
+ it('sets selected to the action id and active to true', () => {
+ const state = { selected: '', active: false };
+ const result = tourReducer(state, { type: UPDATE_SELECTED, id: 'story-4' });
+ expect(result).toEqual({ selected: 'story-4', active: true });
+ });
+
+ it('handles numeric ids', () => {
+ const state = { selected: '', active: false };
+ const result = tourReducer(state, { type: UPDATE_SELECTED, id: 99 });
+ expect(result).toEqual({ selected: 99, active: true });
+ });
+
+ it('handles undefined id', () => {
+ const state = { selected: 'story-1', active: true };
+ const result = tourReducer(state, { type: UPDATE_SELECTED, id: undefined });
+ expect(result).toEqual({ selected: undefined, active: true });
+ });
+
+ it('does not mutate the original state', () => {
+ const state = { selected: '', active: false };
+ tourReducer(state, { type: UPDATE_SELECTED, id: 'story-4' });
+ expect(state).toEqual({ selected: '', active: false });
+ });
+ });
});
diff --git a/web/js/modules/tour/util.test.js b/web/js/modules/tour/util.test.js
index 4072f4f95..5b888310c 100644
--- a/web/js/modules/tour/util.test.js
+++ b/web/js/modules/tour/util.test.js
@@ -1,3 +1,131 @@
-test('util module test', () => {
+import { checkTourBuildTimestamp, mapLocationToTourState } from './util';
+import googleTagManager from 'googleTagManager';
+import safeLocalStorage from '../../util/local-storage';
+jest.mock('googleTagManager', () => ({
+ pushEvent: jest.fn(),
+}));
+
+jest.mock('../../util/local-storage', () => ({
+ keys: { HIDE_TOUR: 'hideTour' },
+ enabled: true,
+ getItem: jest.fn(),
+ removeItem: jest.fn(),
+}));
+
+describe('checkTourBuildTimestamp', () => {
+ const baseConfig = {
+ parameters: {},
+ buildDate: null,
+ };
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ delete window.location;
+ window.location = { search: '' };
+ });
+
+ it('returns false when safeLocalStorage is not enabled', () => {
+ safeLocalStorage.enabled = false;
+ const result = checkTourBuildTimestamp(baseConfig);
+ expect(result).toBe(false);
+ safeLocalStorage.enabled = true;
+ });
+
+ it('does not return false for permalink when config.parameters.tour is set', () => {
+ window.location = { search: '?tour=true' };
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const result = checkTourBuildTimestamp({ parameters: { tour: true }, buildDate: null });
+ expect(result).toBe(true);
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'tour_start' });
+ });
+
+ it('returns false when hideTour is set but no buildDate in config', () => {
+ safeLocalStorage.getItem.mockReturnValue('2023-01-01');
+ const result = checkTourBuildTimestamp({ parameters: {}, buildDate: null });
+ expect(result).toBe(false);
+ });
+
+ it('returns true and removes HIDE_TOUR when buildDate is newer than tourDate', () => {
+ safeLocalStorage.getItem.mockReturnValue('2023-01-01');
+ const result = checkTourBuildTimestamp({ parameters: {}, buildDate: '2024-01-01' });
+ expect(result).toBe(true);
+ expect(safeLocalStorage.removeItem).toHaveBeenCalledWith('hideTour');
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith(
+ expect.objectContaining({ event: 'tour_start_hidden' }),
+ );
+ });
+
+ it('returns false when buildDate is older than tourDate', () => {
+ safeLocalStorage.getItem.mockReturnValue('2025-01-01');
+ const result = checkTourBuildTimestamp({ parameters: {}, buildDate: '2024-01-01' });
+ expect(result).toBe(false);
+ expect(safeLocalStorage.removeItem).not.toHaveBeenCalled();
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith(
+ expect.objectContaining({ event: 'tour_start_hidden' }),
+ );
+ });
+
+ it('returns false when buildDate equals tourDate', () => {
+ safeLocalStorage.getItem.mockReturnValue('2024-06-01');
+ const result = checkTourBuildTimestamp({ parameters: {}, buildDate: '2024-06-01' });
+ expect(result).toBe(false);
+ });
+
+ it('returns true and fires tour_start event when no hideTour is set', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const result = checkTourBuildTimestamp({ parameters: {}, buildDate: null });
+ expect(result).toBe(true);
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({ event: 'tour_start' });
+ });
+});
+
+describe('mapLocationToTourState', () => {
+ const baseState = {};
+ const baseConfig = {};
+ const baseStateFromLocation = {
+ tour: { active: false },
+ embed: { isEmbedModeActive: false },
+ };
+
+ it('sets tour.active to true and embed.isEmbedModeActive to true when tr and em are set', () => {
+ const parameters = { tr: 'true', em: 'true' };
+ const result = mapLocationToTourState(parameters, baseStateFromLocation, baseState, baseConfig);
+ expect(result.tour.active).toBe(true);
+ expect(result.embed.isEmbedModeActive).toBe(true);
+ });
+
+ it('sets tour.active to true but does not change embed when tr is set and em is not true', () => {
+ const parameters = { tr: 'true', em: 'false' };
+ const result = mapLocationToTourState(parameters, baseStateFromLocation, baseState, baseConfig);
+ expect(result.tour.active).toBe(true);
+ expect(result.embed.isEmbedModeActive).toBe(false);
+ });
+
+ it('sets tour.active to true but does not change embed when tr is set and em is absent', () => {
+ const parameters = { tr: 'true' };
+ const result = mapLocationToTourState(parameters, baseStateFromLocation, baseState, baseConfig);
+ expect(result.tour.active).toBe(true);
+ expect(result.embed.isEmbedModeActive).toBe(false);
+ });
+
+ it('sets tour.active to false when tr is not set', () => {
+ const parameters = {};
+ const result = mapLocationToTourState(parameters, baseStateFromLocation, baseState, baseConfig);
+ expect(result.tour.active).toBe(false);
+ });
+
+ it('sets tour.active to false when tr is not set even if em is true', () => {
+ const parameters = { em: 'true' };
+ const result = mapLocationToTourState(parameters, baseStateFromLocation, baseState, baseConfig);
+ expect(result.tour.active).toBe(false);
+ });
+
+ it('does not mutate the original stateFromLocation object', () => {
+ const parameters = { tr: 'true', em: 'true' };
+ const original = { tour: { active: false }, embed: { isEmbedModeActive: false } };
+ mapLocationToTourState(parameters, original, baseState, baseConfig);
+ expect(original.tour.active).toBe(false);
+ expect(original.embed.isEmbedModeActive).toBe(false);
+ });
});
diff --git a/web/js/modules/ui/actions.test.js b/web/js/modules/ui/actions.test.js
index 22bc698b0..e850d29e8 100644
--- a/web/js/modules/ui/actions.test.js
+++ b/web/js/modules/ui/actions.test.js
@@ -1,3 +1,253 @@
-test('actions module test', () => {
+import configureStore from 'redux-mock-store';
+import {thunk} from 'redux-thunk';
+import toggleDistractionFreeMode, {
+ toggleKioskMode,
+ toggleStaticMap,
+ toggleReadyForKioskAnimation,
+ toggleCheckedAnimationAvailability,
+ setEICMeasurementComplete,
+ setEICMeasurementAborted,
+ setTravelMode,
+ setEICLegacy,
+} from './actions';
+
+import {
+ TOGGLE_DISTRACTION_FREE_MODE,
+ TOGGLE_KIOSK_MODE,
+ DISPLAY_STATIC_MAP,
+ READY_FOR_KIOSK_ANIMATION,
+ CHECK_ANIMATION_AVAILABILITY,
+ SET_EIC_MEASUREMENT_COMPLETE,
+ SET_EIC_MEASUREMENT_ABORTED,
+ SET_TRAVELING_HYPERWALL,
+ SET_EIC_LEGACY,
+} from './constants';
+
+import { CLOSE as CLOSE_MODAL } from '../modal/constants';
+
+jest.mock('googleTagManager', () => ({
+ pushEvent: jest.fn(),
+}));
+
+import googleTagManager from 'googleTagManager';
+
+const middleware = [thunk];
+const mockStore = configureStore(middleware);
+
+describe('toggleDistractionFreeMode', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('dispatches TOGGLE_DISTRACTION_FREE_MODE with true when distraction free mode is inactive and modal is closed', () => {
+ const store = mockStore({
+ ui: { isDistractionFreeModeActive: false },
+ modal: { isOpen: false },
+ });
+
+ store.dispatch(toggleDistractionFreeMode());
+
+ const actions = store.getActions();
+ expect(actions).toHaveLength(1);
+ expect(actions[0]).toEqual({
+ type: TOGGLE_DISTRACTION_FREE_MODE,
+ isDistractionFreeModeActive: true,
+ });
+ });
+
+ it('calls googleTagManager.pushEvent when distraction free mode is inactive', () => {
+ const store = mockStore({
+ ui: { isDistractionFreeModeActive: false },
+ modal: { isOpen: false },
+ });
+
+ store.dispatch(toggleDistractionFreeMode());
+
+ expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
+ event: 'init_distraction_free_mode',
+ });
+ });
+
+ it('does not call googleTagManager.pushEvent when distraction free mode is already active', () => {
+ const store = mockStore({
+ ui: { isDistractionFreeModeActive: true },
+ modal: { isOpen: false },
+ });
+
+ store.dispatch(toggleDistractionFreeMode());
+
+ expect(googleTagManager.pushEvent).not.toHaveBeenCalled();
+ });
+
+ it('dispatches TOGGLE_DISTRACTION_FREE_MODE with false when distraction free mode is active', () => {
+ const store = mockStore({
+ ui: { isDistractionFreeModeActive: true },
+ modal: { isOpen: false },
+ });
+
+ store.dispatch(toggleDistractionFreeMode());
+
+ const actions = store.getActions();
+ expect(actions).toHaveLength(1);
+ expect(actions[0]).toEqual({
+ type: TOGGLE_DISTRACTION_FREE_MODE,
+ isDistractionFreeModeActive: false,
+ });
+ });
+
+ it('dispatches CLOSE_MODAL when distraction free mode is inactive and modal is open', () => {
+ const store = mockStore({
+ ui: { isDistractionFreeModeActive: false },
+ modal: { isOpen: true },
+ });
+
+ store.dispatch(toggleDistractionFreeMode());
+
+ const actions = store.getActions();
+ expect(actions).toHaveLength(2);
+ expect(actions[0]).toEqual({
+ type: TOGGLE_DISTRACTION_FREE_MODE,
+ isDistractionFreeModeActive: true,
+ });
+ expect(actions[1]).toEqual({ type: CLOSE_MODAL });
+ });
+
+ it('does not dispatch CLOSE_MODAL when distraction free mode is active and modal is open', () => {
+ const store = mockStore({
+ ui: { isDistractionFreeModeActive: true },
+ modal: { isOpen: true },
+ });
+
+ store.dispatch(toggleDistractionFreeMode());
+
+ const actions = store.getActions();
+ expect(actions).toHaveLength(1);
+ expect(actions[0].type).toBe(TOGGLE_DISTRACTION_FREE_MODE);
+ });
+
+ it('does not dispatch CLOSE_MODAL when distraction free mode is inactive and modal is closed', () => {
+ const store = mockStore({
+ ui: { isDistractionFreeModeActive: false },
+ modal: { isOpen: false },
+ });
+
+ store.dispatch(toggleDistractionFreeMode());
+
+ const actions = store.getActions();
+ expect(actions).toHaveLength(1);
+ expect(actions[0].type).toBe(TOGGLE_DISTRACTION_FREE_MODE);
+ });
+});
+
+describe('toggleKioskMode', () => {
+ it('returns the correct action when isActive is true', () => {
+ expect(toggleKioskMode(true)).toEqual({
+ type: TOGGLE_KIOSK_MODE,
+ isActive: true,
+ });
+ });
+
+ it('returns the correct action when isActive is false', () => {
+ expect(toggleKioskMode(false)).toEqual({
+ type: TOGGLE_KIOSK_MODE,
+ isActive: false,
+ });
+ });
+});
+
+describe('toggleStaticMap', () => {
+ it('returns the correct action when isActive is true', () => {
+ expect(toggleStaticMap(true)).toEqual({
+ type: DISPLAY_STATIC_MAP,
+ isActive: true,
+ });
+ });
+
+ it('returns the correct action when isActive is false', () => {
+ expect(toggleStaticMap(false)).toEqual({
+ type: DISPLAY_STATIC_MAP,
+ isActive: false,
+ });
+ });
+});
+
+describe('toggleReadyForKioskAnimation', () => {
+ it('returns the correct action when toggleAnimation is true', () => {
+ expect(toggleReadyForKioskAnimation(true)).toEqual({
+ type: READY_FOR_KIOSK_ANIMATION,
+ toggleAnimation: true,
+ });
+ });
+
+ it('returns the correct action when toggleAnimation is false', () => {
+ expect(toggleReadyForKioskAnimation(false)).toEqual({
+ type: READY_FOR_KIOSK_ANIMATION,
+ toggleAnimation: false,
+ });
+ });
+});
+
+describe('toggleCheckedAnimationAvailability', () => {
+ it('returns the correct action when toggleCheck is true', () => {
+ expect(toggleCheckedAnimationAvailability(true)).toEqual({
+ type: CHECK_ANIMATION_AVAILABILITY,
+ toggleCheck: true,
+ });
+ });
+
+ it('returns the correct action when toggleCheck is false', () => {
+ expect(toggleCheckedAnimationAvailability(false)).toEqual({
+ type: CHECK_ANIMATION_AVAILABILITY,
+ toggleCheck: false,
+ });
+ });
+});
+
+describe('setEICMeasurementComplete', () => {
+ it('returns the correct action', () => {
+ expect(setEICMeasurementComplete()).toEqual({
+ type: SET_EIC_MEASUREMENT_COMPLETE,
+ });
+ });
+});
+
+describe('setEICMeasurementAborted', () => {
+ it('returns the correct action', () => {
+ expect(setEICMeasurementAborted()).toEqual({
+ type: SET_EIC_MEASUREMENT_ABORTED,
+ });
+ });
+});
+
+describe('setTravelMode', () => {
+ it('returns the correct action with a travelMode value', () => {
+ expect(setTravelMode('hyperwall')).toEqual({
+ type: SET_TRAVELING_HYPERWALL,
+ travelMode: 'hyperwall',
+ });
+ });
+
+ it('returns the correct action with a falsy travelMode value', () => {
+ expect(setTravelMode(false)).toEqual({
+ type: SET_TRAVELING_HYPERWALL,
+ travelMode: false,
+ });
+ });
+});
+
+describe('setEICLegacy', () => {
+ it('returns the correct action when isLegacy is true', () => {
+ expect(setEICLegacy(true)).toEqual({
+ type: SET_EIC_LEGACY,
+ isLegacy: true,
+ });
+ });
+
+ it('returns the correct action when isLegacy is false', () => {
+ expect(setEICLegacy(false)).toEqual({
+ type: SET_EIC_LEGACY,
+ isLegacy: false,
+ });
+ });
});
diff --git a/web/js/modules/ui/reducers.test.js b/web/js/modules/ui/reducers.test.js
index 04cce6a78..d6b7b6ed8 100644
--- a/web/js/modules/ui/reducers.test.js
+++ b/web/js/modules/ui/reducers.test.js
@@ -1,3 +1,157 @@
-test('reducers module test', () => {
+import uiReducers, { uiState } from './reducers';
+import {
+ TOGGLE_DISTRACTION_FREE_MODE,
+ TOGGLE_KIOSK_MODE,
+ SET_ERROR_TILES,
+ DISPLAY_STATIC_MAP,
+ CLEAR_ERROR_TILES,
+ READY_FOR_KIOSK_ANIMATION,
+ CHECK_ANIMATION_AVAILABILITY,
+ SET_EIC_MEASUREMENT_COMPLETE,
+ SET_EIC_MEASUREMENT_ABORTED,
+ SET_TRAVELING_HYPERWALL,
+ SET_EIC_LEGACY,
+} from './constants';
+describe('uiReducers', () => {
+ it('returns the initial state when no action is provided', () => {
+ expect(uiReducers(undefined, {})).toEqual(uiState);
+ });
+
+ it('returns the existing state for an unknown action type', () => {
+ const currentState = { ...uiState, eic: 'sa' };
+ expect(uiReducers(currentState, { type: 'UNKNOWN_ACTION' })).toEqual(currentState);
+ });
+
+ it('toggles isDistractionFreeModeActive from false to true on TOGGLE_DISTRACTION_FREE_MODE', () => {
+ const state = { ...uiState, isDistractionFreeModeActive: false };
+ const result = uiReducers(state, { type: TOGGLE_DISTRACTION_FREE_MODE });
+ expect(result.isDistractionFreeModeActive).toBe(true);
+ });
+
+ it('toggles isDistractionFreeModeActive from true to false on TOGGLE_DISTRACTION_FREE_MODE', () => {
+ const state = { ...uiState, isDistractionFreeModeActive: true };
+ const result = uiReducers(state, { type: TOGGLE_DISTRACTION_FREE_MODE });
+ expect(result.isDistractionFreeModeActive).toBe(false);
+ });
+
+ it('sets isKioskModeActive to true on TOGGLE_KIOSK_MODE', () => {
+ const result = uiReducers(uiState, { type: TOGGLE_KIOSK_MODE, isActive: true });
+ expect(result.isKioskModeActive).toBe(true);
+ });
+
+ it('sets isKioskModeActive to false on TOGGLE_KIOSK_MODE', () => {
+ const state = { ...uiState, isKioskModeActive: true };
+ const result = uiReducers(state, { type: TOGGLE_KIOSK_MODE, isActive: false });
+ expect(result.isKioskModeActive).toBe(false);
+ });
+
+ it('sets errorTiles on SET_ERROR_TILES', () => {
+ const errorTiles = { tile1: true, tile2: false };
+ const result = uiReducers(uiState, { type: SET_ERROR_TILES, errorTiles });
+ expect(result.errorTiles).toEqual(errorTiles);
+ });
+
+ it('replaces errorTiles on SET_ERROR_TILES with new values', () => {
+ const state = { ...uiState, errorTiles: { tile1: true } };
+ const errorTiles = { tile2: true };
+ const result = uiReducers(state, { type: SET_ERROR_TILES, errorTiles });
+ expect(result.errorTiles).toEqual({ tile2: true });
+ });
+
+ it('clears errorTiles on CLEAR_ERROR_TILES', () => {
+ const state = { ...uiState, errorTiles: { tile1: true } };
+ const result = uiReducers(state, { type: CLEAR_ERROR_TILES, errorTiles: {} });
+ expect(result.errorTiles).toEqual({});
+ });
+
+ it('sets displayStaticMap to true on DISPLAY_STATIC_MAP', () => {
+ const result = uiReducers(uiState, { type: DISPLAY_STATIC_MAP, isActive: true });
+ expect(result.displayStaticMap).toBe(true);
+ });
+
+ it('sets displayStaticMap to false on DISPLAY_STATIC_MAP', () => {
+ const state = { ...uiState, displayStaticMap: true };
+ const result = uiReducers(state, { type: DISPLAY_STATIC_MAP, isActive: false });
+ expect(result.displayStaticMap).toBe(false);
+ });
+
+ it('sets readyForKioskAnimation to true on READY_FOR_KIOSK_ANIMATION', () => {
+ const result = uiReducers(uiState, { type: READY_FOR_KIOSK_ANIMATION, toggleAnimation: true });
+ expect(result.readyForKioskAnimation).toBe(true);
+ });
+
+ it('sets readyForKioskAnimation to false on READY_FOR_KIOSK_ANIMATION', () => {
+ const state = { ...uiState, readyForKioskAnimation: true };
+ const result = uiReducers(state, { type: READY_FOR_KIOSK_ANIMATION, toggleAnimation: false });
+ expect(result.readyForKioskAnimation).toBe(false);
+ });
+
+ it('sets animationAvailabilityChecked to true on CHECK_ANIMATION_AVAILABILITY', () => {
+ const result = uiReducers(uiState, { type: CHECK_ANIMATION_AVAILABILITY, toggleCheck: true });
+ expect(result.animationAvailabilityChecked).toBe(true);
+ });
+
+ it('sets animationAvailabilityChecked to false on CHECK_ANIMATION_AVAILABILITY', () => {
+ const state = { ...uiState, animationAvailabilityChecked: true };
+ const result = uiReducers(state, { type: CHECK_ANIMATION_AVAILABILITY, toggleCheck: false });
+ expect(result.animationAvailabilityChecked).toBe(false);
+ });
+
+ it('sets eicMeasurementComplete to true on SET_EIC_MEASUREMENT_COMPLETE', () => {
+ const result = uiReducers(uiState, { type: SET_EIC_MEASUREMENT_COMPLETE });
+ expect(result.eicMeasurementComplete).toBe(true);
+ });
+
+ it('does not modify other state properties on SET_EIC_MEASUREMENT_COMPLETE', () => {
+ const result = uiReducers(uiState, { type: SET_EIC_MEASUREMENT_COMPLETE });
+ expect(result.eicMeasurementAborted).toBe(false);
+ expect(result.isKioskModeActive).toBe(false);
+ });
+
+ it('sets eicMeasurementAborted to true on SET_EIC_MEASUREMENT_ABORTED', () => {
+ const result = uiReducers(uiState, { type: SET_EIC_MEASUREMENT_ABORTED });
+ expect(result.eicMeasurementAborted).toBe(true);
+ });
+
+ it('does not modify other state properties on SET_EIC_MEASUREMENT_ABORTED', () => {
+ const result = uiReducers(uiState, { type: SET_EIC_MEASUREMENT_ABORTED });
+ expect(result.eicMeasurementComplete).toBe(false);
+ expect(result.isKioskModeActive).toBe(false);
+ });
+
+ it('sets travelMode on SET_TRAVELING_HYPERWALL', () => {
+ const result = uiReducers(uiState, { type: SET_TRAVELING_HYPERWALL, travelMode: 'hyperwall' });
+ expect(result.travelMode).toBe('hyperwall');
+ });
+
+ it('sets travelMode to empty string on SET_TRAVELING_HYPERWALL', () => {
+ const state = { ...uiState, travelMode: 'hyperwall' };
+ const result = uiReducers(state, { type: SET_TRAVELING_HYPERWALL, travelMode: '' });
+ expect(result.travelMode).toBe('');
+ });
+
+ it('sets eicLegacy to true on SET_EIC_LEGACY', () => {
+ const result = uiReducers(uiState, { type: SET_EIC_LEGACY, isLegacy: true });
+ expect(result.eicLegacy).toBe(true);
+ });
+
+ it('sets eicLegacy to false on SET_EIC_LEGACY', () => {
+ const state = { ...uiState, eicLegacy: true };
+ const result = uiReducers(state, { type: SET_EIC_LEGACY, isLegacy: false });
+ expect(result.eicLegacy).toBe(false);
+ });
+
+ it('does not mutate the original state', () => {
+ const state = { ...uiState };
+ const frozen = Object.freeze(state);
+ expect(() => uiReducers(frozen, { type: TOGGLE_DISTRACTION_FREE_MODE })).not.toThrow();
+ });
+
+ it('preserves unrelated state properties when handling an action', () => {
+ const state = { ...uiState, eic: 'sa', scenario: 'test-scenario' };
+ const result = uiReducers(state, { type: SET_EIC_LEGACY, isLegacy: true });
+ expect(result.eic).toBe('sa');
+ expect(result.scenario).toBe('test-scenario');
+ });
});
diff --git a/web/js/modules/vector-styles/action.test.js b/web/js/modules/vector-styles/action.test.js
deleted file mode 100644
index 7abfaa21a..000000000
--- a/web/js/modules/vector-styles/action.test.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import { SET_SELECTED_VECTORS } from './constants';
-import { selectVectorFeatures } from './actions';
-
-test(
- `selectVectorFeature action returns ${SET_SELECTED_VECTORS} action type [vectorstyles-actions-set-selected]`,
- () => {
- const payload = 'test';
- const expectedAction = {
- type: SET_SELECTED_VECTORS,
- payload,
- };
- expect(selectVectorFeatures(payload)).toEqual(expectedAction);
- },
-);
diff --git a/web/js/modules/vector-styles/actions.test.js b/web/js/modules/vector-styles/actions.test.js
new file mode 100644
index 000000000..5e435dc37
--- /dev/null
+++ b/web/js/modules/vector-styles/actions.test.js
@@ -0,0 +1,237 @@
+import {
+ setFilterRange,
+ setStyle,
+ clearStyle,
+ selectVectorFeatures,
+} from './actions';
+import {
+ SET_FILTER_RANGE,
+ CLEAR_VECTORSTYLE,
+ SET_VECTORSTYLE,
+ SET_SELECTED_VECTORS,
+} from './constants';
+import {
+ setRange as setRangeSelector,
+ setStyleFunction,
+} from './selectors';
+
+jest.mock('./selectors', () => ({
+ setRange: jest.fn(),
+ setStyleFunction: jest.fn(),
+}));
+
+jest.mock('./constants', () => ({
+ SET_FILTER_RANGE: 'SET_FILTER_RANGE',
+ CLEAR_VECTORSTYLE: 'CLEAR_VECTORSTYLE',
+ SET_VECTORSTYLE: 'SET_VECTORSTYLE',
+ SET_SELECTED_VECTORS: 'SET_SELECTED_VECTORS',
+}));
+
+describe('actions.js', () => {
+ let dispatch;
+ let getState;
+ const groupName = 'active';
+ const layerId = 'layer-1';
+ const vectorStyleId = 'style-1';
+ const layer = { id: layerId };
+ const mockVectorStylesObj = { some: 'styles' };
+ const mockState = {
+ vectorStyles: {
+ custom: { existing: 'style' },
+ [groupName]: { rangeData: true },
+ },
+ };
+
+ beforeEach(() => {
+ dispatch = jest.fn();
+ getState = jest.fn().mockReturnValue(mockState);
+ setRangeSelector.mockReturnValue(mockVectorStylesObj);
+ setStyleFunction.mockReturnValue(mockVectorStylesObj);
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('setFilterRange', () => {
+ const props = { min: 0, max: 100, squash: false, noclip: false };
+ const index = 0;
+
+ it('should return a thunk', () => {
+ const thunk = setFilterRange(layerId, props, index, groupName);
+ expect(typeof thunk).toBe('function');
+ });
+
+ it('should call getState', () => {
+ const thunk = setFilterRange(layerId, props, index, groupName);
+ thunk(dispatch, getState);
+ expect(getState).toHaveBeenCalledTimes(1);
+ });
+
+ it('should call setRangeSelector with correct arguments', () => {
+ const thunk = setFilterRange(layerId, props, index, groupName);
+ thunk(dispatch, getState);
+ expect(setRangeSelector).toHaveBeenCalledWith(
+ layerId,
+ props,
+ index,
+ mockState.vectorStyles[groupName],
+ mockState,
+ );
+ });
+
+ it('should dispatch SET_FILTER_RANGE with correct payload', () => {
+ const thunk = setFilterRange(layerId, props, index, groupName);
+ thunk(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_FILTER_RANGE,
+ groupName,
+ activeString: groupName,
+ layerId,
+ vectorStyles: mockVectorStylesObj,
+ props,
+ });
+ });
+
+ it('should dispatch with the returned vectorStyles from setRangeSelector', () => {
+ const customStyles = { custom: 'result' };
+ setRangeSelector.mockReturnValue(customStyles);
+ const thunk = setFilterRange(layerId, props, index, groupName);
+ thunk(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ vectorStyles: customStyles }),
+ );
+ });
+ });
+
+ describe('setStyle', () => {
+ it('should return a thunk', () => {
+ const thunk = setStyle(layer, vectorStyleId, groupName);
+ expect(typeof thunk).toBe('function');
+ });
+
+ it('should call getState', () => {
+ const thunk = setStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(getState).toHaveBeenCalledTimes(1);
+ });
+
+ it('should call setStyleFunction with correct arguments', () => {
+ const thunk = setStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(setStyleFunction).toHaveBeenCalledWith(
+ layer,
+ vectorStyleId,
+ mockState.vectorStyles.custom,
+ null,
+ mockState,
+ );
+ });
+
+ it('should dispatch SET_VECTORSTYLE with correct payload', () => {
+ const thunk = setStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith({
+ type: SET_VECTORSTYLE,
+ layerId: layer.id,
+ vectorStyleId,
+ groupName,
+ activeString: groupName,
+ vectorStyles: mockVectorStylesObj,
+ });
+ });
+
+ it('should dispatch with the returned vectorStyles from setStyleFunction', () => {
+ const customStyles = { updated: 'vectorStyle' };
+ setStyleFunction.mockReturnValue(customStyles);
+ const thunk = setStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ vectorStyles: customStyles }),
+ );
+ });
+ });
+
+ describe('clearStyle', () => {
+ it('should return a thunk', () => {
+ const thunk = clearStyle(layer, vectorStyleId, groupName);
+ expect(typeof thunk).toBe('function');
+ });
+
+ it('should call getState', () => {
+ const thunk = clearStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(getState).toHaveBeenCalledTimes(1);
+ });
+
+ it('should call setStyleFunction with correct arguments', () => {
+ const thunk = clearStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(setStyleFunction).toHaveBeenCalledWith(
+ layer,
+ vectorStyleId,
+ mockState.vectorStyles.custom,
+ null,
+ mockState,
+ );
+ });
+
+ it('should dispatch CLEAR_VECTORSTYLE with correct payload', () => {
+ const thunk = clearStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith({
+ type: CLEAR_VECTORSTYLE,
+ layerId: layer.id,
+ vectorStyleId,
+ groupName,
+ activeString: groupName,
+ vectorStyles: mockVectorStylesObj,
+ });
+ });
+
+ it('should dispatch with the returned vectorStyles from setStyleFunction', () => {
+ const customStyles = { cleared: 'vectorStyle' };
+ setStyleFunction.mockReturnValue(customStyles);
+ const thunk = clearStyle(layer, vectorStyleId, groupName);
+ thunk(dispatch, getState);
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ vectorStyles: customStyles }),
+ );
+ });
+ });
+
+ describe('selectVectorFeatures', () => {
+ it('should return an action object with SET_SELECTED_VECTORS type', () => {
+ const payload = { 'layer-1': ['feature-1', 'feature-2'] };
+ const action = selectVectorFeatures(payload);
+ expect(action).toEqual({
+ type: SET_SELECTED_VECTORS,
+ payload,
+ });
+ });
+
+ it('should include the payload in the action', () => {
+ const payload = { 'layer-2': ['feature-3'] };
+ const action = selectVectorFeatures(payload);
+ expect(action.payload).toBe(payload);
+ });
+
+ it('should handle an empty payload object', () => {
+ const payload = {};
+ const action = selectVectorFeatures(payload);
+ expect(action).toEqual({
+ type: SET_SELECTED_VECTORS,
+ payload: {},
+ });
+ });
+
+ it('should handle a payload with multiple layer ids', () => {
+ const payload = {
+ 'layer-1': ['feature-1'],
+ 'layer-2': ['feature-2', 'feature-3'],
+ };
+ const action = selectVectorFeatures(payload);
+ expect(action.payload).toEqual(payload);
+ });
+ });
+});
diff --git a/web/js/modules/vector-styles/reducer.test.js b/web/js/modules/vector-styles/reducer.test.js
deleted file mode 100644
index 0b70b484a..000000000
--- a/web/js/modules/vector-styles/reducer.test.js
+++ /dev/null
@@ -1,11 +0,0 @@
-import { defaultVectorStyleState, vectorStyleReducer } from './reducers';
-import { SET_SELECTED_VECTORS } from './constants';
-
-test('Set a selected Vector [vectorstyle-reducer-set-selected]', () => {
- const response = vectorStyleReducer(defaultVectorStyleState, {
- type: SET_SELECTED_VECTORS,
- payload: { some_layer_id: ['some_feature_id'] },
- });
-
- expect(response.selected.some_layer_id[0]).toEqual('some_feature_id');
-});
diff --git a/web/js/modules/vector-styles/reducers.test.js b/web/js/modules/vector-styles/reducers.test.js
new file mode 100644
index 000000000..16d5e9ca0
--- /dev/null
+++ b/web/js/modules/vector-styles/reducers.test.js
@@ -0,0 +1,256 @@
+import {
+ defaultVectorStyleState,
+ getInitialVectorStyleState,
+ vectorStyleReducer,
+} from './reducers';
+import {
+ CLEAR_VECTORSTYLE,
+ SET_VECTORSTYLE,
+ SET_FILTER_RANGE,
+ SET_SELECTED_VECTORS,
+} from './constants';
+
+jest.mock('./constants', () => ({
+ CLEAR_VECTORSTYLE: 'CLEAR_VECTORSTYLE',
+ SET_VECTORSTYLE: 'SET_VECTORSTYLE',
+ SET_FILTER_RANGE: 'SET_FILTER_RANGE',
+ SET_SELECTED_VECTORS: 'SET_SELECTED_VECTORS',
+}));
+
+describe('reducers.js', () => {
+ describe('defaultVectorStyleState', () => {
+ it('should have a custom property defaulting to an empty object', () => {
+ expect(defaultVectorStyleState.custom).toEqual({});
+ });
+
+ it('should have an active property defaulting to an empty object', () => {
+ expect(defaultVectorStyleState.active).toEqual({});
+ });
+
+ it('should have an activeB property defaulting to an empty object', () => {
+ expect(defaultVectorStyleState.activeB).toEqual({});
+ });
+
+ it('should have a selected property defaulting to an empty object', () => {
+ expect(defaultVectorStyleState.selected).toEqual({});
+ });
+ });
+
+ describe('getInitialVectorStyleState', () => {
+ it('should return default state merged with custom and customDefault when config has vectorStyles', () => {
+ const config = { vectorStyles: { style1: { color: 'red' } } };
+ const result = getInitialVectorStyleState(config);
+ expect(result.custom).toEqual({ style1: { color: 'red' } });
+ expect(result.customDefault).toEqual({ style1: { color: 'red' } });
+ });
+
+ it('should return empty custom and customDefault when config has no vectorStyles', () => {
+ const result = getInitialVectorStyleState({});
+ expect(result.custom).toEqual({});
+ expect(result.customDefault).toEqual({});
+ });
+
+ it('should return empty custom and customDefault when config is undefined', () => {
+ const result = getInitialVectorStyleState(undefined);
+ expect(result.custom).toEqual({});
+ expect(result.customDefault).toEqual({});
+ });
+
+ it('should include default state properties in the result', () => {
+ const result = getInitialVectorStyleState({});
+ expect(result.active).toEqual({});
+ expect(result.activeB).toEqual({});
+ expect(result.selected).toEqual({});
+ });
+
+ it('should deep clone custom into customDefault so they are not the same reference', () => {
+ const config = { vectorStyles: { style1: { color: 'blue' } } };
+ const result = getInitialVectorStyleState(config);
+ expect(result.custom).not.toBe(result.customDefault);
+ expect(result.custom).toEqual(result.customDefault);
+ });
+
+ it('should use vectorStyles from config as the custom property', () => {
+ const vectorStyles = { styleA: { fill: 'green' } };
+ const config = { vectorStyles };
+ const result = getInitialVectorStyleState(config);
+ expect(result.custom).toBe(vectorStyles);
+ });
+ });
+
+ describe('vectorStyleReducer', () => {
+ const initialState = {
+ custom: {},
+ active: {},
+ activeB: {},
+ selected: {},
+ };
+
+ it('should return the default state when called with no arguments', () => {
+ const result = vectorStyleReducer(undefined, { type: '@@INIT' });
+ expect(result).toEqual(defaultVectorStyleState);
+ });
+
+ it('should return the current state for an unknown action type', () => {
+ const result = vectorStyleReducer(initialState, { type: 'UNKNOWN_ACTION' });
+ expect(result).toBe(initialState);
+ });
+
+ describe('SET_FILTER_RANGE', () => {
+ it('should update the active group by default when no groupName is provided', () => {
+ const vectorStyles = { rangeData: true };
+ const action = { type: SET_FILTER_RANGE, vectorStyles };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.active).toEqual(vectorStyles);
+ });
+
+ it('should update the specified groupName', () => {
+ const vectorStyles = { rangeData: true };
+ const action = { type: SET_FILTER_RANGE, groupName: 'activeB', vectorStyles };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.activeB).toEqual(vectorStyles);
+ });
+
+ it('should not mutate other state properties', () => {
+ const vectorStyles = { rangeData: true };
+ const action = { type: SET_FILTER_RANGE, groupName: 'active', vectorStyles };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.custom).toEqual(initialState.custom);
+ expect(result.selected).toEqual(initialState.selected);
+ expect(result.activeB).toEqual(initialState.activeB);
+ });
+
+ it('should return a new state object', () => {
+ const action = { type: SET_FILTER_RANGE, vectorStyles: {} };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result).not.toBe(initialState);
+ });
+ });
+
+ describe('SET_VECTORSTYLE', () => {
+ it('should update the active group by default when no groupName is provided', () => {
+ const vectorStyles = { styleId: 'style-1' };
+ const action = { type: SET_VECTORSTYLE, vectorStyles };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.active).toEqual(vectorStyles);
+ });
+
+ it('should update the specified groupName', () => {
+ const vectorStyles = { styleId: 'style-2' };
+ const action = { type: SET_VECTORSTYLE, groupName: 'activeB', vectorStyles };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.activeB).toEqual(vectorStyles);
+ });
+
+ it('should not mutate other state properties', () => {
+ const vectorStyles = { styleId: 'style-1' };
+ const action = { type: SET_VECTORSTYLE, groupName: 'active', vectorStyles };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.custom).toEqual(initialState.custom);
+ expect(result.selected).toEqual(initialState.selected);
+ expect(result.activeB).toEqual(initialState.activeB);
+ });
+
+ it('should return a new state object', () => {
+ const action = { type: SET_VECTORSTYLE, vectorStyles: {} };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result).not.toBe(initialState);
+ });
+ });
+
+ describe('CLEAR_VECTORSTYLE', () => {
+ const populatedState = {
+ ...initialState,
+ active: { styleId: 'style-1' },
+ };
+
+ it('should set the active group to the provided vectorStyles', () => {
+ const vectorStyles = { styleId: 'cleared-style' };
+ const action = { type: CLEAR_VECTORSTYLE, vectorStyles };
+ const result = vectorStyleReducer(populatedState, action);
+ expect(result.active).toEqual(vectorStyles);
+ });
+
+ it('should fall back to an empty object when vectorStyles is undefined', () => {
+ const action = { type: CLEAR_VECTORSTYLE, groupName: 'active' };
+ const result = vectorStyleReducer(populatedState, action);
+ expect(result.active).toEqual({});
+ });
+
+ it('should fall back to an empty object when vectorStyles is null', () => {
+ const action = { type: CLEAR_VECTORSTYLE, groupName: 'active', vectorStyles: null };
+ const result = vectorStyleReducer(populatedState, action);
+ expect(result.active).toEqual({});
+ });
+
+ it('should update the specified groupName', () => {
+ const vectorStyles = { styleId: 'style-B' };
+ const action = { type: CLEAR_VECTORSTYLE, groupName: 'activeB', vectorStyles };
+ const result = vectorStyleReducer(populatedState, action);
+ expect(result.activeB).toEqual(vectorStyles);
+ });
+
+ it('should not mutate other state properties', () => {
+ const action = { type: CLEAR_VECTORSTYLE, groupName: 'active', vectorStyles: {} };
+ const result = vectorStyleReducer(populatedState, action);
+ expect(result.custom).toEqual(populatedState.custom);
+ expect(result.selected).toEqual(populatedState.selected);
+ expect(result.activeB).toEqual(populatedState.activeB);
+ });
+
+ it('should return a new state object', () => {
+ const action = { type: CLEAR_VECTORSTYLE, vectorStyles: {} };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result).not.toBe(initialState);
+ });
+ });
+
+ describe('SET_SELECTED_VECTORS', () => {
+ it('should update the selected property with the action payload', () => {
+ const payload = { 'layer-1': ['feature-1', 'feature-2'] };
+ const action = { type: SET_SELECTED_VECTORS, payload };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.selected).toEqual(payload);
+ });
+
+ it('should handle an empty payload', () => {
+ const action = { type: SET_SELECTED_VECTORS, payload: {} };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.selected).toEqual({});
+ });
+
+ it('should handle a payload with multiple layers', () => {
+ const payload = {
+ 'layer-1': ['feature-1'],
+ 'layer-2': ['feature-2', 'feature-3'],
+ };
+ const action = { type: SET_SELECTED_VECTORS, payload };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.selected).toEqual(payload);
+ });
+
+ it('should not be affected by groupName in the action', () => {
+ const payload = { 'layer-1': ['feature-1'] };
+ const action = { type: SET_SELECTED_VECTORS, groupName: 'activeB', payload };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.selected).toEqual(payload);
+ expect(result.activeB).toEqual(initialState.activeB);
+ });
+
+ it('should not mutate other state properties', () => {
+ const payload = { 'layer-1': ['feature-1'] };
+ const action = { type: SET_SELECTED_VECTORS, payload };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result.custom).toEqual(initialState.custom);
+ expect(result.active).toEqual(initialState.active);
+ expect(result.activeB).toEqual(initialState.activeB);
+ });
+
+ it('should return a new state object', () => {
+ const action = { type: SET_SELECTED_VECTORS, payload: {} };
+ const result = vectorStyleReducer(initialState, action);
+ expect(result).not.toBe(initialState);
+ });
+ });
+ });
+});
diff --git a/web/js/modules/vector-styles/selectors.test.js b/web/js/modules/vector-styles/selectors.test.js
index c4e1cdccf..e7dfce0d0 100644
--- a/web/js/modules/vector-styles/selectors.test.js
+++ b/web/js/modules/vector-styles/selectors.test.js
@@ -1,3 +1,783 @@
-test('selectors module test', () => {
+import {
+ getVectorLayers,
+ getAllVectorStyles,
+ getVectorStyle,
+ findIndex,
+ setRange,
+ setStyleFunction,
+ isActive,
+ getKey,
+ clearStyleFunction,
+ applyStyle,
+} from './selectors';
+import {
+ getMinValue,
+ getMaxValue,
+} from './util';
+import {
+ isActive as isPaletteActive,
+ getLookup as getPaletteLookup,
+} from '../palettes/selectors';
+import { stylefunction } from 'ol-mapbox-style';
+import util from '../../util/util';
+jest.mock('./util', () => ({
+ getMinValue: jest.fn(),
+ getMaxValue: jest.fn(),
+ selectedStyleFunction: jest.fn(),
+}));
+
+jest.mock('../palettes/selectors', () => ({
+ isActive: jest.fn(),
+ getLookup: jest.fn(),
+}));
+
+jest.mock('ol-mapbox-style', () => ({
+ stylefunction: jest.fn(),
+}));
+
+jest.mock('ol/extent', () => ({
+ containsCoordinate: jest.fn(),
+}));
+
+jest.mock('../../util/util', () => ({
+ __esModule: true,
+ default: {
+ hexToRGBA: jest.fn(),
+ },
+}));
+
+jest.mock('immutability-helper', () => jest.fn((obj) => obj));
+
+const makeLayer = (overrides = {}) => ({
+ isWMS: false,
+ getLayers: null,
+ setStyle: jest.fn(),
+ getExtent: jest.fn().mockReturnValue([0, -90, 180, 90]),
+ ...overrides,
+});
+
+const makeBaseOpts = (overrides = {}) => ({
+ def: {
+ id: 'layer-1',
+ vectorStyle: { id: 'style-1' },
+ custom: null,
+ disabled: null,
+ vectorData: { id: 'data-1' },
+ },
+ vectorStyleId: 'style-1',
+ vectorStyles: {
+ 'style-1': {
+ layers: [{ paint: { 'circle-color': [] } }],
+ },
+ },
+ options: { group: 'active' },
+ state: {
+ map: { ui: { selected: {} } },
+ proj: { id: 'geographic', selected: { resolutions: [1, 2, 4] } },
+ vectorStyles: {
+ selected: {},
+ customDefault: { 'style-1': undefined },
+ },
+ palettes: {},
+ config: { vectorData: { 'data-1': { mvt_properties: [] } } },
+ },
+ layer: makeLayer(),
+ ...overrides,
+});
+
+describe('selectors.js', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('getVectorLayers', () => {
+ it('should return only vector type layer groups flattened via getLayersArray', () => {
+ const vectorLayer = { isVector: true };
+ const vectorLayerGroup = {
+ wv: { def: { type: 'vector' } },
+ getLayersArray: jest.fn().mockReturnValue([vectorLayer]),
+ };
+ const nonVectorLayerGroup = { wv: { def: { type: 'wms' } } };
+ const state = {
+ map: {
+ ui: {
+ selected: {
+ getLayers: jest.fn().mockReturnValue({
+ getArray: jest.fn().mockReturnValue([vectorLayerGroup, nonVectorLayerGroup]),
+ }),
+ },
+ },
+ },
+ };
+ expect(getVectorLayers(state)).toEqual([vectorLayer]);
+ });
+
+ it('should return an empty array when no vector layers exist', () => {
+ const state = {
+ map: {
+ ui: {
+ selected: {
+ getLayers: jest.fn().mockReturnValue({
+ getArray: jest.fn().mockReturnValue([{ wv: { def: { type: 'wms' } } }]),
+ }),
+ },
+ },
+ },
+ };
+ expect(getVectorLayers(state)).toEqual([]);
+ });
+
+ it('should accumulate layers from multiple vector layer groups', () => {
+ const layerA = { isVector: true, id: 'a' };
+ const layerB = { isVector: true, id: 'b' };
+ const groupA = { wv: { def: { type: 'vector' } }, getLayersArray: () => [layerA] };
+ const groupB = { wv: { def: { type: 'vector' } }, getLayersArray: () => [layerB] };
+ const state = {
+ map: {
+ ui: {
+ selected: {
+ getLayers: jest.fn().mockReturnValue({
+ getArray: jest.fn().mockReturnValue([groupA, groupB]),
+ }),
+ },
+ },
+ },
+ };
+ expect(getVectorLayers(state)).toEqual([layerA, layerB]);
+ });
+ });
+
+ describe('getAllVectorStyles', () => {
+ it('should return the vectorStyle matching the layerId', () => {
+ const style = { color: 'red' };
+ const state = {
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ vectorStyles: { custom: { 'style-1': style } },
+ };
+ expect(getAllVectorStyles('layer-1', undefined, state)).toBe(style);
+ });
+
+ it('should throw when the vectorStyle name is not found in custom', () => {
+ const state = {
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'missing' } } } },
+ vectorStyles: { custom: {} },
+ };
+ expect(() => getAllVectorStyles('layer-1', undefined, state)).toThrow(
+ 'missing Is not a rendered vectorStyle',
+ );
+ });
+
+ it('should return a sub-layer by index when vectorStyle has a layers array', () => {
+ const subLayer = { id: 'sub-0' };
+ const style = { layers: [subLayer] };
+ const state = {
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ vectorStyles: { custom: { 'style-1': style } },
+ };
+ expect(getAllVectorStyles('layer-1', 0, state)).toBe(subLayer);
+ });
+
+ it('should return the top-level style when index is undefined and no layers array exists', () => {
+ const style = { color: 'blue' };
+ const state = {
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ vectorStyles: { custom: { 'style-1': style } },
+ };
+ expect(getAllVectorStyles('layer-1', undefined, state)).toBe(style);
+ });
+
+ it('should return the top-level style without descending when layers array is absent for a given index', () => {
+ const style = { color: 'green' };
+ const state = {
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ vectorStyles: { custom: { 'style-1': style } },
+ };
+ expect(getAllVectorStyles('layer-1', 0, state)).toBe(style);
+ });
+ });
+
+ describe('getVectorStyle', () => {
+ it('should return the rendered vectorStyle from state when present', () => {
+ const renderedStyle = { rendered: true };
+ const state = {
+ vectorStyles: { 'layer-1': { layers: [renderedStyle] }, custom: {} },
+ config: { layers: {} },
+ };
+ expect(getVectorStyle('layer-1', 0, state)).toBe(renderedStyle);
+ });
+
+ it('should fall back to getAllVectorStyles when no rendered style is found', () => {
+ const style = { color: 'green' };
+ const state = {
+ vectorStyles: { custom: { 'style-1': style } },
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ };
+ expect(getVectorStyle('layer-1', 0, state)).toBe(style);
+ });
+
+ it('should default index to 0 when indexInt is undefined', () => {
+ const renderedStyle = { rendered: true };
+ const state = {
+ vectorStyles: { 'layer-1': { layers: [renderedStyle] }, custom: {} },
+ config: { layers: {} },
+ };
+ expect(getVectorStyle('layer-1', undefined, state)).toBe(renderedStyle);
+ });
+
+ it('should use the provided index to select the correct rendered layer', () => {
+ const style0 = { idx: 0 };
+ const style1 = { idx: 1 };
+ const state = {
+ vectorStyles: { 'layer-1': { layers: [style0, style1] }, custom: {} },
+ config: { layers: {} },
+ };
+ expect(getVectorStyle('layer-1', 1, state)).toBe(style1);
+ });
+ });
+
+ describe('findIndex', () => {
+ const buildState = (values) => ({
+ vectorStyles: {
+ 'layer-1': { layers: [{ entries: { values } }] },
+ custom: {},
+ },
+ config: { layers: {} },
+ });
+
+ beforeEach(() => {
+ getMinValue.mockImplementation((v) => v.min);
+ getMaxValue.mockImplementation((v) => v.max);
+ });
+
+ it('should find the index for a matching min value', () => {
+ const state = buildState([{ min: 1, max: 10 }, { min: 20, max: 30 }]);
+ expect(findIndex('layer-1', 'min', 20, 0, state)).toBe(1);
+ });
+
+ it('should find the index for a matching max value', () => {
+ const state = buildState([{ min: 0, max: 10 }, { min: 20, max: 30 }]);
+ expect(findIndex('layer-1', 'max', 10, 0, state)).toBe(0);
+ });
+
+ it('should return undefined when no match is found', () => {
+ const state = buildState([{ min: 1, max: 10 }]);
+ expect(findIndex('layer-1', 'min', 99, 0, state)).toBeUndefined();
+ });
+
+ it('should default index to 0 when indexInt is not provided', () => {
+ const state = buildState([{ min: 5, max: 15 }]);
+ expect(findIndex('layer-1', 'min', 5, undefined, state)).toBe(0);
+ });
+
+ it('should return the first matching index and stop iterating', () => {
+ const state = buildState([{ min: 5, max: 10 }, { min: 5, max: 20 }]);
+ expect(findIndex('layer-1', 'min', 5, 0, state)).toBe(0);
+ });
+ });
+
+ describe('setRange', () => {
+ it('should return an object with all provided arguments', () => {
+ const layerId = 'layer-1';
+ const props = { min: 0, max: 100 };
+ const index = 0;
+ const palettes = { some: 'palette' };
+ const state = { some: 'state' };
+ expect(setRange(layerId, props, index, palettes, state)).toEqual({
+ layerId, props, index, palettes, state,
+ });
+ });
+
+ it('should handle undefined index and palettes', () => {
+ const result = setRange('layer-1', {}, undefined, undefined, {});
+ expect(result.index).toBeUndefined();
+ expect(result.palettes).toBeUndefined();
+ });
+ });
+
+ describe('isActive', () => {
+ it('should return the vectorStyle for the layer when custom entry exists', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: {
+ custom: { 'layer-1': true },
+ active: { 'layer-1': { styleId: 'style-1' } },
+ },
+ };
+ expect(isActive('layer-1', 'active', state)).toEqual({ styleId: 'style-1' });
+ });
+
+ it('should return undefined when layer is not in custom', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: { custom: {}, active: {} },
+ };
+ expect(isActive('layer-1', 'active', state)).toBeUndefined();
+ });
+
+ it('should fall back to compare.activeString when groupObj is falsy', () => {
+ const state = {
+ compare: { activeString: 'activeB' },
+ vectorStyles: {
+ custom: { 'layer-1': true },
+ activeB: { 'layer-1': { styleId: 'style-B' } },
+ },
+ };
+ expect(isActive('layer-1', null, state)).toEqual({ styleId: 'style-B' });
+ });
+
+ it('should return undefined when group entry for layer does not exist', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: {
+ custom: { 'layer-1': true },
+ active: {},
+ },
+ };
+ expect(isActive('layer-1', 'active', state)).toBeUndefined();
+ });
+ });
+
+ describe('getKey', () => {
+ it('should return an empty string when isActive returns falsy', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: { custom: {}, active: {} },
+ };
+ expect(getKey('layer-1', 'active', state)).toBe('');
+ });
+
+ it('should return a style key when def.custom is set', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: {
+ 'layer-1': { layers: [{ custom: 'palette-1', entries: {} }] },
+ custom: { 'layer-1': true },
+ active: { 'layer-1': {} },
+ },
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ };
+ expect(getKey('layer-1', 'active', state)).toContain('style=palette-1');
+ });
+
+ it('should return a min key when def.min is a non-zero truthy value', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: {
+ 'layer-1': { layers: [{ min: 5, entries: {} }] },
+ custom: { 'layer-1': true },
+ active: { 'layer-1': {} },
+ },
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ };
+ expect(getKey('layer-1', 'active', state)).toContain('min=5');
+ });
+
+ it('should return a max key when def.max is set', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: {
+ 'layer-1': { layers: [{ max: 100, entries: {} }] },
+ custom: { 'layer-1': true },
+ active: { 'layer-1': {} },
+ },
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ };
+ expect(getKey('layer-1', 'active', state)).toContain('max=100');
+ });
+
+ it('should return comma-joined keys for all matching fields', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: {
+ 'layer-1': { layers: [{ custom: 'palette-1', min: 5, max: 50, entries: {} }] },
+ custom: { 'layer-1': true },
+ active: { 'layer-1': {} },
+ },
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ };
+ expect(getKey('layer-1', 'active', state)).toBe('style=palette-1,min=5,max=50');
+ });
+
+ it('should use compare.activeString when group is not provided', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: { custom: {}, active: {} },
+ };
+ expect(getKey('layer-1', null, state)).toBe('');
+ });
+
+ it('should return an empty string when no key fields are present on def', () => {
+ const state = {
+ compare: { activeString: 'active' },
+ vectorStyles: {
+ 'layer-1': { layers: [{ entries: {} }] },
+ custom: { 'layer-1': true },
+ active: { 'layer-1': {} },
+ },
+ config: { layers: { 'layer-1': { vectorStyle: { id: 'style-1' } } } },
+ };
+ expect(getKey('layer-1', 'active', state)).toBe('');
+ });
+ });
+
+ describe('setStyleFunction', () => {
+ beforeEach(() => {
+ stylefunction.mockReturnValue(jest.fn());
+ isPaletteActive.mockReturnValue(false);
+ });
+
+ it('should return undefined when map is not present in state', () => {
+ const opts = makeBaseOpts();
+ opts.state.map.ui.selected = null;
+ expect(setStyleFunction(opts)).toBeUndefined();
+ });
+
+ it('should return undefined when layer is null', () => {
+ expect(setStyleFunction(makeBaseOpts({ layer: null }))).toBeUndefined();
+ });
+
+ it('should return undefined when layer.isWMS is true', () => {
+ const opts = makeBaseOpts({ layer: makeLayer({ isWMS: true }) });
+ expect(setStyleFunction(opts)).toBeUndefined();
+ });
+
+ it('should return undefined when glStyle is undefined for the resolved styleId', () => {
+ const opts = makeBaseOpts({ vectorStyles: {} });
+ expect(setStyleFunction(opts)).toBeUndefined();
+ });
+
+ it('should call stylefunction and return vectorStyleId on a successful run', () => {
+ const opts = makeBaseOpts();
+ expect(setStyleFunction(opts)).toBe('style-1');
+ expect(stylefunction).toHaveBeenCalled();
+ });
+
+ it('should use resolutions from opts when provided', () => {
+ const opts = makeBaseOpts({ resolutions: [8, 16, 32] });
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ [8, 16, 32],
+ );
+ });
+
+ it('should fall back to proj.selected.resolutions when opts.resolutions is absent', () => {
+ const opts = makeBaseOpts();
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ [1, 2, 4],
+ );
+ });
+
+ it('should use vectorStyleSource as source when provided', () => {
+ const opts = makeBaseOpts({ vectorStyleSource: 'custom-source' });
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ 'custom-source',
+ expect.anything(),
+ );
+ });
+
+ it('should use layerId as source when vectorStyleSource is not provided', () => {
+ const opts = makeBaseOpts();
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ 'layer-1',
+ expect.anything(),
+ );
+ });
+
+ it('should use a proj-specific vectorStyle id when available on def', () => {
+ const opts = makeBaseOpts();
+ opts.def.vectorStyle = { id: 'fallback', geographic: { id: 'geo-style' } };
+ opts.vectorStyles['geo-style'] = { layers: [{ paint: {} }] };
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalled();
+ });
+
+ it('should apply customDefault style when no customPalette and styleSelection is false', () => {
+ const customDefaultStyle = { layers: [{ paint: {} }] };
+ const opts = makeBaseOpts();
+ opts.state.vectorStyles.customDefault = { 'style-1': customDefaultStyle };
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalled();
+ });
+
+ it('should not replace glStyle with customDefault when styleSelection is true', () => {
+ const customDefaultStyle = { layers: [{ paint: { replaced: true } }] };
+ const opts = makeBaseOpts({ styleSelection: true });
+ opts.state.vectorStyles.customDefault = { 'style-1': customDefaultStyle };
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalled();
+ });
+
+ it('should apply a custom palette when customPalette is set and palettes state exists', () => {
+ const opts = makeBaseOpts();
+ opts.def.custom = 'custom-palette';
+ opts.state.palettes = { custom: { 'custom-palette': { colors: ['#ff0000'] } } };
+ util.hexToRGBA.mockReturnValue([255, 0, 0, 1]);
+ setStyleFunction(opts);
+ expect(util.hexToRGBA).toHaveBeenCalledWith('#ff0000');
+ });
+
+ it('should resolve the inner isVector layer when layer has getLayers', () => {
+ const innerLayer = { isVector: true };
+ const opts = makeBaseOpts({
+ layer: makeLayer({
+ getLayers: jest.fn().mockReturnValue({
+ getArray: jest.fn().mockReturnValue([innerLayer]),
+ }),
+ }),
+ });
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalledWith(
+ innerLayer,
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('should call layer.setStyle when selectedFeatures exist and glStyle name is not Orbit Tracks', () => {
+ const opts = makeBaseOpts();
+ opts.state.vectorStyles.selected = { 'layer-1': ['feature-1'] };
+ setStyleFunction(opts);
+ expect(opts.layer.setStyle).toHaveBeenCalled();
+ });
+
+ it('should not call layer.setStyle when selectedFeatures is empty', () => {
+ const opts = makeBaseOpts();
+ opts.state.vectorStyles.selected = {};
+ setStyleFunction(opts);
+ expect(opts.layer.setStyle).not.toHaveBeenCalled();
+ });
+
+ it('should not call layer.setStyle when glStyle name is Orbit Tracks even with selected features', () => {
+ const opts = makeBaseOpts();
+ opts.vectorStyles['style-1'] = { name: 'Orbit Tracks', layers: [{ paint: {} }] };
+ opts.state.vectorStyles.selected = { 'layer-1': ['feature-1'] };
+ setStyleFunction(opts);
+ expect(opts.layer.setStyle).not.toHaveBeenCalled();
+ });
+
+ it('should delete glStyle.id before calling stylefunction', () => {
+ const opts = makeBaseOpts();
+ opts.vectorStyles['style-1'] = { id: 'should-be-deleted', layers: [{ paint: {} }] };
+ setStyleFunction(opts);
+ expect(stylefunction).toHaveBeenCalled();
+ });
+
+ it('should apply lookup via getPaletteLookup when isPaletteActive returns true', () => {
+ const opts = makeBaseOpts();
+ opts.def.disabled = true;
+ opts.vectorStyles['style-1'] = {
+ layers: [{ paint: { 'circle-color': [] } }],
+ };
+ isPaletteActive.mockReturnValue(true);
+ getPaletteLookup.mockReturnValue({});
+ setStyleFunction(opts);
+ expect(getPaletteLookup).toHaveBeenCalled();
+ });
+
+ it('should handle extentStartX === 180 producing the western acceptable extent', () => {
+ const opts = makeBaseOpts({
+ layer: makeLayer({ getExtent: jest.fn().mockReturnValue([180, -90, 360, 90]) }),
+ });
+ opts.state.vectorStyles.selected = { 'layer-1': ['feature-1'] };
+ setStyleFunction(opts);
+ expect(opts.layer.setStyle).toHaveBeenCalled();
+ });
+
+ it('should handle extentStartX === -250 producing the eastern acceptable extent', () => {
+ const opts = makeBaseOpts({
+ layer: makeLayer({ getExtent: jest.fn().mockReturnValue([-250, -90, -110, 90]) }),
+ });
+ opts.state.vectorStyles.selected = { 'layer-1': ['feature-1'] };
+ setStyleFunction(opts);
+ expect(opts.layer.setStyle).toHaveBeenCalled();
+ });
+ });
+
+ describe('clearStyleFunction', () => {
+ beforeEach(() => {
+ stylefunction.mockReturnValue(jest.fn());
+ });
+
+ const makeClearArgs = () => {
+ const mockLayer = { setStyle: jest.fn() };
+ const def = { id: 'layer-1' };
+ const vectorStyleId = 'style-1';
+ const vectorStyles = { 'layer-1': { name: 'Some Style', layers: [] } };
+ const state = {};
+ return {
+ def, vectorStyleId, vectorStyles, mockLayer, state,
+ };
+ };
+
+ it('should call stylefunction with layer, glStyle, and vectorStyleId', () => {
+ const {
+ def, vectorStyleId, vectorStyles, mockLayer, state,
+ } = makeClearArgs();
+ clearStyleFunction(def, vectorStyleId, vectorStyles, mockLayer, state);
+ expect(stylefunction).toHaveBeenCalledWith(
+ mockLayer,
+ vectorStyles['layer-1'],
+ vectorStyleId,
+ );
+ });
+
+ it('should not call layer.setStyle for non-Orbit-Tracks layers', () => {
+ const {
+ def, vectorStyleId, vectorStyles, mockLayer, state,
+ } = makeClearArgs();
+ clearStyleFunction(def, vectorStyleId, vectorStyles, mockLayer, state);
+ expect(mockLayer.setStyle).not.toHaveBeenCalled();
+ });
+
+ it('should call layer.setStyle for Orbit Tracks layers', () => {
+ const { def, vectorStyleId, mockLayer, state } = makeClearArgs();
+ const orbitVectorStyles = { 'layer-1': { name: 'Orbit Tracks' } };
+ clearStyleFunction(def, vectorStyleId, orbitVectorStyles, mockLayer, state);
+ expect(mockLayer.setStyle).toHaveBeenCalled();
+ });
+
+ it('should find and reassign layer from olMap when a matching subLayer exists', () => {
+ const { def, vectorStyleId, vectorStyles } = makeClearArgs();
+ const matchingSubLayer = { wv: { id: 'layer-1' }, setStyle: jest.fn() };
+ const state = {
+ legacy: {
+ map: {
+ ui: {
+ selected: {
+ getLayers: jest.fn().mockReturnValue({
+ getArray: jest.fn().mockReturnValue([matchingSubLayer]),
+ }),
+ },
+ },
+ },
+ },
+ };
+ clearStyleFunction(def, vectorStyleId, vectorStyles, null, state);
+ expect(stylefunction).toHaveBeenCalledWith(
+ matchingSubLayer,
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('should not reassign layer when no subLayer id matches', () => {
+ const { def, vectorStyleId, vectorStyles, mockLayer } = makeClearArgs();
+ const nonMatchingSubLayer = { wv: { id: 'other-layer' } };
+ const state = {
+ legacy: {
+ map: {
+ ui: {
+ selected: {
+ getLayers: jest.fn().mockReturnValue({
+ getArray: jest.fn().mockReturnValue([nonMatchingSubLayer]),
+ }),
+ },
+ },
+ },
+ },
+ };
+ clearStyleFunction(def, vectorStyleId, vectorStyles, mockLayer, state);
+ expect(stylefunction).toHaveBeenCalledWith(
+ mockLayer,
+ expect.anything(),
+ expect.anything(),
+ );
+ });
+
+ it('should return an updated vectorStyles object', () => {
+ const {
+ def, vectorStyleId, vectorStyles, mockLayer, state,
+ } = makeClearArgs();
+ const result = clearStyleFunction(def, vectorStyleId, vectorStyles, mockLayer, state);
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('applyStyle', () => {
+ beforeEach(() => {
+ stylefunction.mockReturnValue(jest.fn());
+ isPaletteActive.mockReturnValue(false);
+ });
+
+ const makeApplyState = (vectorStyles = { 'style-1': { layers: [{ paint: {} }] } }) => ({
+ map: { ui: { selected: {} } },
+ proj: { id: 'geographic', selected: { resolutions: [1, 2, 4] } },
+ vectorStyles: {
+ selected: {},
+ customDefault: { 'style-1': undefined },
+ },
+ palettes: {},
+ config: {
+ vectorStyles,
+ vectorData: {},
+ },
+ });
+
+ it('should call setStyleFunction when vectorStyles and vectorStyleId are present', () => {
+ const def = { id: 'layer-1', vectorStyle: { id: 'style-1', source: 'src-1' }, custom: null, disabled: null };
+ const olVectorLayer = makeLayer();
+ const state = makeApplyState();
+ const options = { group: 'active' };
+ applyStyle(def, olVectorLayer, state, options);
+ expect(stylefunction).toHaveBeenCalled();
+ });
+
+ it('should return early when config.vectorStyles is falsy', () => {
+ const def = { id: 'layer-1', vectorStyle: { id: 'style-1', source: 'src-1' } };
+ const olVectorLayer = makeLayer();
+ const state = makeApplyState(null);
+ state.config.vectorStyles = null;
+ applyStyle(def, olVectorLayer, state, {});
+ expect(stylefunction).not.toHaveBeenCalled();
+ });
+
+ it('should return early when vectorStyleId is falsy', () => {
+ const def = { id: 'layer-1', vectorStyle: { id: '', source: 'src-1' } };
+ const olVectorLayer = makeLayer();
+ const state = makeApplyState();
+ applyStyle(def, olVectorLayer, state, {});
+ expect(stylefunction).not.toHaveBeenCalled();
+ });
+
+ it('should forward resolutions to setStyleFunction when provided', () => {
+ const def = { id: 'layer-1', vectorStyle: { id: 'style-1', source: 'src-1' }, custom: null, disabled: null };
+ const olVectorLayer = makeLayer();
+ const state = makeApplyState();
+ applyStyle(def, olVectorLayer, state, { group: 'active' }, [2, 4, 8]);
+ expect(stylefunction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ [2, 4, 8],
+ );
+ });
+
+ it('should not spread resolutions into opts when resolutions is falsy', () => {
+ const def = { id: 'layer-1', vectorStyle: { id: 'style-1', source: 'src-1' }, custom: null, disabled: null };
+ const olVectorLayer = makeLayer();
+ const state = makeApplyState();
+ applyStyle(def, olVectorLayer, state, { group: 'active' }, null);
+ expect(stylefunction).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ [1, 2, 4],
+ );
+ });
+ });
});
diff --git a/web/js/modules/vector-styles/util.test.js b/web/js/modules/vector-styles/util.test.js
index 4072f4f95..937693eef 100644
--- a/web/js/modules/vector-styles/util.test.js
+++ b/web/js/modules/vector-styles/util.test.js
@@ -1,3 +1,542 @@
-test('util module test', () => {
+/* eslint-disable new-cap */
+import {
+ getVectorStyleAttributeArray,
+ getMinValue,
+ getMaxValue,
+ isConditional,
+ adjustCircleRadius,
+ selectedCircleStyle,
+ selectedPolygonStyle,
+ offsetLineStringStyle,
+ selectedStyleFunction,
+ getConditionalColors,
+ getPaletteForStyle,
+ isFeatureInRenderableArea,
+ onMapClickGetVectorFeatures,
+ updateVectorSelection,
+} from './util';
+import { getVectorLayers, setStyleFunction } from './selectors';
+import { isFromActiveCompareRegion } from '../compare/util';
+import { Style, Circle } from 'ol/style';
+jest.mock('./selectors', () => ({
+ getVectorLayers: jest.fn(),
+ setStyleFunction: jest.fn(),
+}));
+
+jest.mock('../compare/util', () => ({
+ isFromActiveCompareRegion: jest.fn(),
+}));
+
+jest.mock('ol/style', () => {
+ const mockStroke = jest.fn().mockImplementation(function () {
+ this.setColor = jest.fn(); this.setWidth = jest.fn();
+ });
+ const mockFill = jest.fn().mockImplementation(function () {
+ this.getColor = jest.fn().mockReturnValue('rgba(255,0,0,1)'); this.setColor = jest.fn();
+ });
+ const mockCircle = jest.fn().mockImplementation(function () {
+ this.getRadius = jest.fn().mockReturnValue(5);
+ this.getFill = jest.fn().mockReturnValue(new mockFill());
+ });
+ const mockStyle = jest.fn().mockImplementation(function (opts) {
+ this.opts = opts;
+ this.getImage = jest.fn().mockReturnValue(new mockCircle());
+ this.getFill = jest.fn().mockReturnValue(new mockFill());
+ this.getStroke = jest.fn().mockReturnValue(new mockStroke());
+ this.getText = jest.fn().mockReturnValue(null);
+ });
+ return {
+ Stroke: mockStroke,
+ Fill: mockFill,
+ Circle: mockCircle,
+ Style: mockStyle,
+ };
+});
+
+describe('util.js', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('getVectorStyleAttributeArray', () => {
+ it('should return an empty array when no attributes are set', () => {
+ expect(getVectorStyleAttributeArray({})).toEqual([]);
+ });
+
+ it('should include a style entry when custom is set', () => {
+ const result = getVectorStyleAttributeArray({ custom: 'my-palette' });
+ expect(result).toContainEqual({ id: 'style', value: 'my-palette' });
+ });
+
+ it('should include a min entry when min is set to a truthy value', () => {
+ const result = getVectorStyleAttributeArray({ min: 5 });
+ expect(result).toContainEqual({ id: 'min', value: 5 });
+ });
+
+ it('should include a max entry when max is set', () => {
+ const result = getVectorStyleAttributeArray({ max: 100 });
+ expect(result).toContainEqual({ id: 'max', value: 100 });
+ });
+
+ it('should include all three entries when all attributes are set', () => {
+ const result = getVectorStyleAttributeArray({ custom: 'pal', min: 1, max: 99 });
+ expect(result).toHaveLength(3);
+ expect(result).toContainEqual({ id: 'style', value: 'pal' });
+ expect(result).toContainEqual({ id: 'min', value: 1 });
+ expect(result).toContainEqual({ id: 'max', value: 99 });
+ });
+
+ it('should not include min when min is 0 (falsy)', () => {
+ const result = getVectorStyleAttributeArray({ min: 0 });
+ expect(result.find((e) => e.id === 'min')).toBeUndefined();
+ });
+
+ it('should use id "style" for the custom key entry', () => {
+ const result = getVectorStyleAttributeArray({ custom: 'x' });
+ expect(result[0].id).toBe('style');
+ });
+ });
+
+ describe('getMinValue', () => {
+ it('should return the first element of an array', () => {
+ expect(getMinValue([10, 20, 30])).toBe(10);
+ });
+
+ it('should return the value directly when not an array', () => {
+ expect(getMinValue(42)).toBe(42);
+ });
+
+ it('should return the first element of a single-element array', () => {
+ expect(getMinValue([7])).toBe(7);
+ });
+
+ it('should return the value when it is 0', () => {
+ expect(getMinValue(0)).toBe(0);
+ });
+ });
+
+ describe('getMaxValue', () => {
+ it('should return the last element of an array', () => {
+ expect(getMaxValue([10, 20, 30])).toBe(30);
+ });
+
+ it('should return the value directly when not an array', () => {
+ expect(getMaxValue(99)).toBe(99);
+ });
+
+ it('should return the only element of a single-element array', () => {
+ expect(getMaxValue([5])).toBe(5);
+ });
+
+ it('should return the value when it is 0', () => {
+ expect(getMaxValue(0)).toBe(0);
+ });
+ });
+
+ describe('isConditional', () => {
+ it('should return true when the first element is "case"', () => {
+ expect(isConditional(['case', 'a', 'b'])).toBe(true);
+ });
+
+ it('should return false when the first element is not "case"', () => {
+ expect(isConditional(['match', 'a', 'b'])).toBe(false);
+ });
+
+ it('should return false when the item is not an array', () => {
+ expect(isConditional('case')).toBe(false);
+ });
+
+ it('should return false for an empty array', () => {
+ expect(isConditional([])).toBe(false);
+ });
+
+ it('should return false for null', () => {
+ expect(isConditional(null)).toBe(false);
+ });
+ });
+
+ describe('adjustCircleRadius', () => {
+ it('should return a new Style with radius scaled by 0.6', () => {
+ const mockImage = { getRadius: jest.fn().mockReturnValue(10), getFill: jest.fn().mockReturnValue('fill') };
+ const style = { getImage: jest.fn().mockReturnValue(mockImage) };
+ const result = adjustCircleRadius(style);
+ expect(Circle).toHaveBeenCalledWith(expect.objectContaining({ radius: 6 }));
+ expect(Style).toHaveBeenCalled();
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('selectedCircleStyle', () => {
+ it('should return a new Style when fill is present', () => {
+ const mockFillInstance = { getColor: jest.fn().mockReturnValue('rgba(255,0,0,1)') };
+ const mockImage = {
+ getRadius: jest.fn().mockReturnValue(5),
+ getFill: jest.fn().mockReturnValue(mockFillInstance),
+ };
+ const style = { getImage: jest.fn().mockReturnValue(mockImage) };
+ const result = selectedCircleStyle(style, 3);
+ expect(Circle).toHaveBeenCalledWith(expect.objectContaining({ radius: 15 }));
+ expect(result).toBeDefined();
+ });
+
+ it('should return the original style when fill is null', () => {
+ const mockImage = {
+ getRadius: jest.fn().mockReturnValue(5),
+ getFill: jest.fn().mockReturnValue(null),
+ };
+ const style = { getImage: jest.fn().mockReturnValue(mockImage) };
+ const result = selectedCircleStyle(style);
+ expect(result).toBe(style);
+ });
+
+ it('should use default size of 2 when size is not provided', () => {
+ const mockFillInstance = { getColor: jest.fn().mockReturnValue('rgba(0,0,255,1)') };
+ const mockImage = {
+ getRadius: jest.fn().mockReturnValue(4),
+ getFill: jest.fn().mockReturnValue(mockFillInstance),
+ };
+ const style = { getImage: jest.fn().mockReturnValue(mockImage) };
+ selectedCircleStyle(style);
+ expect(Circle).toHaveBeenCalledWith(expect.objectContaining({ radius: 8 }));
+ });
+ });
+
+ describe('selectedPolygonStyle', () => {
+ it('should set stroke color to white and width to 0.5 and return the style', () => {
+ const mockStrokeInstance = { setColor: jest.fn(), setWidth: jest.fn() };
+ const mockFillInstance = { getColor: jest.fn().mockReturnValue('rgba(0,0,0,1)'), setColor: jest.fn() };
+ const style = {
+ getFill: jest.fn().mockReturnValue(mockFillInstance),
+ getStroke: jest.fn().mockReturnValue(mockStrokeInstance),
+ };
+ const result = selectedPolygonStyle(style);
+ expect(mockStrokeInstance.setColor).toHaveBeenCalledWith('white');
+ expect(mockStrokeInstance.setWidth).toHaveBeenCalledWith(0.5);
+ expect(result).toBe(style);
+ });
+
+ it('should update the fill color with 0.5 opacity', () => {
+ const mockStrokeInstance = { setColor: jest.fn(), setWidth: jest.fn() };
+ const mockFillInstance = { getColor: jest.fn().mockReturnValue('rgba(10,20,30,1)'), setColor: jest.fn() };
+ const style = {
+ getFill: jest.fn().mockReturnValue(mockFillInstance),
+ getStroke: jest.fn().mockReturnValue(mockStrokeInstance),
+ };
+ selectedPolygonStyle(style);
+ expect(mockFillInstance.setColor).toHaveBeenCalledWith('rgba(10,20,30,0.5)');
+ });
+ });
+
+ describe('offsetLineStringStyle', () => {
+ it('should call setOffsetX(25) on text when present', () => {
+ const mockText = { setOffsetX: jest.fn() };
+ const style = { getText: jest.fn().mockReturnValue(mockText) };
+ offsetLineStringStyle({}, [style]);
+ expect(mockText.setOffsetX).toHaveBeenCalledWith(25);
+ });
+
+ it('should not throw when style has no text', () => {
+ const style = { getText: jest.fn().mockReturnValue(null) };
+ expect(() => offsetLineStringStyle({}, [style])).not.toThrow();
+ });
+
+ it('should return the mapped array of styles', () => {
+ const style = { getText: jest.fn().mockReturnValue(null) };
+ const result = offsetLineStringStyle({}, [style]);
+ expect(result).toEqual([style]);
+ });
+
+ it('should process multiple styles', () => {
+ const mockText = { setOffsetX: jest.fn() };
+ const styleA = { getText: jest.fn().mockReturnValue(mockText) };
+ const styleB = { getText: jest.fn().mockReturnValue(null) };
+ offsetLineStringStyle({}, [styleA, styleB]);
+ expect(mockText.setOffsetX).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('selectedStyleFunction', () => {
+ it('should return the styleArray unchanged when its length is not 1', () => {
+ const styleArray = ['a', 'b'];
+ expect(selectedStyleFunction({}, styleArray)).toBe(styleArray);
+ });
+
+ it('should call selectedCircleStyle path for Point geometry', () => {
+ const mockFillInstance = { getColor: jest.fn().mockReturnValue('rgba(0,0,0,1)') };
+ const mockImage = {
+ getRadius: jest.fn().mockReturnValue(5),
+ getFill: jest.fn().mockReturnValue(mockFillInstance),
+ };
+ const style = { getImage: jest.fn().mockReturnValue(mockImage) };
+ const feature = { getGeometry: jest.fn().mockReturnValue({ getType: jest.fn().mockReturnValue('Point') }) };
+ const result = selectedStyleFunction(feature, [style], 2);
+ expect(result).toHaveLength(1);
+ });
+
+ it('should call selectedPolygonStyle path for Polygon geometry', () => {
+ const mockStrokeInstance = { setColor: jest.fn(), setWidth: jest.fn() };
+ const mockFillInstance = { getColor: jest.fn().mockReturnValue('rgba(0,0,0,1)'), setColor: jest.fn() };
+ const style = {
+ getFill: jest.fn().mockReturnValue(mockFillInstance),
+ getStroke: jest.fn().mockReturnValue(mockStrokeInstance),
+ getImage: jest.fn().mockReturnValue(null),
+ };
+ const feature = { getGeometry: jest.fn().mockReturnValue({ getType: jest.fn().mockReturnValue('Polygon') }) };
+ const result = selectedStyleFunction(feature, [style]);
+ expect(result).toHaveLength(1);
+ });
+
+ it('should return the style unchanged for unsupported geometry types', () => {
+ const style = { getImage: jest.fn() };
+ const feature = { getGeometry: jest.fn().mockReturnValue({ getType: jest.fn().mockReturnValue('LineString') }) };
+ const result = selectedStyleFunction(feature, [style]);
+ expect(result[0]).toBe(style);
+ });
+ });
+
+ describe('getConditionalColors', () => {
+ it('should extract colors and labels from a valid conditional expression', () => {
+ const properColor = ['case', [null, null, 'Label A'], '#ff0000'];
+ const result = getConditionalColors(properColor);
+ expect(result.colors).toContain('#ff0000');
+ expect(result.labels).toContain('Label A');
+ });
+
+ it('should add a Default label for an odd trailing element', () => {
+ const input = ['case', [null, null, 'Cat'], '#aabbcc', '#ffffff'];
+ const result = getConditionalColors(input);
+ expect(result.labels).toContain('Default');
+ expect(result.colors).toContain('#ffffff');
+ });
+
+ it('should warn for an irregular pair (non-string second)', () => {
+ const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ const input = ['case', 42, 43];
+ getConditionalColors(input);
+ expect(consoleSpy).toHaveBeenCalledWith('Irregular conditional');
+ consoleSpy.mockRestore();
+ });
+
+ it('should return empty arrays for an input with only the case keyword removed', () => {
+ const input = ['case'];
+ const result = getConditionalColors(input);
+ expect(result.colors).toEqual([]);
+ expect(result.labels).toEqual([]);
+ });
+ });
+
+ describe('getPaletteForStyle', () => {
+ it('should return a classification palette for a non-conditional line-color', () => {
+ const layer = { id: 'layer-1', title: 'My Layer' };
+ const styleObj = { layers: [{ paint: { 'line-color': '#ff0000' } }] };
+ const result = getPaletteForStyle(layer, styleObj);
+ expect(result).toHaveLength(1);
+ expect(result[0].type).toBe('classification');
+ expect(result[0].colors).toContain('#ff0000');
+ expect(result[0].tooltips).toContain('My Layer');
+ expect(result[0].id).toBe('layer-10_legend');
+ });
+
+ it('should use circle-color when line-color is absent', () => {
+ const layer = { id: 'layer-2', title: 'Circle Layer' };
+ const styleObj = { layers: [{ paint: { 'circle-color': '#00ff00' } }] };
+ const result = getPaletteForStyle(layer, styleObj);
+ expect(result[0].colors).toContain('#00ff00');
+ });
+
+ it('should use fill-color when line-color and circle-color are absent', () => {
+ const layer = { id: 'layer-3', title: 'Fill Layer' };
+ const styleObj = { layers: [{ paint: { 'fill-color': '#0000ff' } }] };
+ const result = getPaletteForStyle(layer, styleObj);
+ expect(result[0].colors).toContain('#0000ff');
+ });
+
+ it('should extract conditional colors when the color is a conditional expression', () => {
+ const layer = { id: 'layer-4', title: 'Cond Layer' };
+ const color = ['case', [null, null, 'Cat A'], '#aabbcc', '#ffffff'];
+ const styleObj = { layers: [{ paint: { 'line-color': color } }] };
+ const result = getPaletteForStyle(layer, styleObj);
+ expect(result[0].colors.length).toBeGreaterThan(0);
+ });
+
+ it('should include the layer title and id in the result', () => {
+ const layer = { id: 'abc', title: 'ABC Layer' };
+ const styleObj = { layers: [{ paint: { 'line-color': '#123456' } }] };
+ const result = getPaletteForStyle(layer, styleObj);
+ expect(result[0].title).toBe('ABC Layer');
+ expect(result[0].id).toBe('abc0_legend');
+ });
+ });
+
+ describe('isFeatureInRenderableArea', () => {
+ it('should use acceptableExtent bounds when provided', () => {
+ expect(isFeatureInRenderableArea(10, 0, [-180, -90, 180, 90])).toBe(true);
+ });
+
+ it('should return false when lon is outside acceptableExtent', () => {
+ expect(isFeatureInRenderableArea(200, 0, [-180, -90, 180, 90])).toBe(false);
+ });
+
+ it('should return true for wrap=-1 when lon is between 180 and 250', () => {
+ expect(isFeatureInRenderableArea(200, -1, null)).toBe(true);
+ });
+
+ it('should return false for wrap=-1 when lon is not in range', () => {
+ expect(isFeatureInRenderableArea(100, -1, null)).toBe(false);
+ });
+
+ it('should return true for wrap=1 when lon is between -250 and -180', () => {
+ expect(isFeatureInRenderableArea(-200, 1, null)).toBe(true);
+ });
+
+ it('should return false for wrap=1 when lon is not in range', () => {
+ expect(isFeatureInRenderableArea(-100, 1, null)).toBe(false);
+ });
+
+ it('should return false when wrap is 0 and no acceptableExtent', () => {
+ expect(isFeatureInRenderableArea(10, 0, null)).toBe(false);
+ });
+ });
+
+ describe('onMapClickGetVectorFeatures', () => {
+ const makeState = (overrides = {}) => ({
+ config: {},
+ compare: { activeString: 'active' },
+ screenSize: { screenWidth: 1200, screenHeight: 800, isMobileDevice: false },
+ ...overrides,
+ });
+
+ const makeMap = (features = []) => ({
+ forEachFeatureAtPixel: jest.fn((pixels, cb) => {
+ features.forEach((pair) => cb(pair[0], pair[1]));
+ }),
+ });
+
+ it('should return all required keys in the result object', () => {
+ const map = makeMap();
+ const result = onMapClickGetVectorFeatures([100, 200], map, makeState(), 0, 445);
+ expect(result).toHaveProperty('selected');
+ expect(result).toHaveProperty('metaArray');
+ expect(result).toHaveProperty('offsetLeft');
+ expect(result).toHaveProperty('offsetTop');
+ expect(result).toHaveProperty('isCoordinatesMarker');
+ expect(result).toHaveProperty('modalShouldFollowClicks');
+ expect(result).toHaveProperty('exceededLengthLimit');
+ });
+
+ it('should return isCoordinatesMarker true when the coordinates marker feature is clicked', () => {
+ const markerFeature = { getId: jest.fn().mockReturnValue('coordinates-map-marker') };
+ const map = makeMap([[markerFeature, {}]]);
+ const result = onMapClickGetVectorFeatures([100, 200], map, makeState(), 0, 445);
+ expect(result.isCoordinatesMarker).toBe(true);
+ });
+
+ it('should set exceededLengthLimit when more than desktop limit features are at pixel', () => {
+ const makeFeat = () => ({
+ getId: jest.fn().mockReturnValue(null),
+ getGeometry: jest.fn().mockReturnValue({ getType: jest.fn().mockReturnValue('Point') }),
+ getProperties: jest.fn().mockReturnValue({}),
+ });
+ const makeLayerWv = (id) => ({
+ wv: {
+ def: {
+ id,
+ title: `Layer ${id}`,
+ vectorData: { id: 'vd1' },
+ clickDisabledFeatures: [],
+ modalShouldFollowClicks: false,
+ },
+ group: 'active',
+ },
+ });
+ isFromActiveCompareRegion.mockReturnValue(true);
+ const featurePairs = Array.from({ length: 13 }, (_, i) => {
+ const f = makeFeat();
+ f.getId.mockReturnValue(`feature-${i}`);
+ return [f, makeLayerWv(`layer-${i}`)];
+ });
+ const map = makeMap(featurePairs);
+ const state = makeState({
+ config: {
+ vectorData: { vd1: { mvt_properties: [] } },
+ },
+ });
+ const result = onMapClickGetVectorFeatures([100, 200], map, state, 0, 445);
+ expect(result.exceededLengthLimit).toBe(true);
+ });
+
+ it('should compute offsetLeft and offsetTop from pixel position', () => {
+ const map = makeMap();
+ const result = onMapClickGetVectorFeatures([600, 400], map, makeState(), 0, 445);
+ expect(typeof result.offsetLeft).toBe('number');
+ expect(typeof result.offsetTop).toBe('number');
+ });
+
+ it('should use mobile limits when isMobileDevice is true', () => {
+ const map = makeMap();
+ const result = onMapClickGetVectorFeatures(
+ [100, 200],
+ map,
+ makeState({ screenSize: { screenWidth: 400, screenHeight: 700, isMobileDevice: true } }),
+ 0,
+ 250,
+ );
+ expect(result).toHaveProperty('exceededLengthLimit');
+ });
+ });
+
+ describe('updateVectorSelection', () => {
+ const makeState = (layers = []) => ({
+ config: {
+ vectorStyles: {},
+ layers: layers.reduce((acc, l) => ({ ...acc, [l.id]: l }), {}),
+ },
+ map: {
+ ui: {
+ selected: {
+ getLayers: jest.fn().mockReturnValue({ getArray: jest.fn().mockReturnValue([]) }),
+ },
+ },
+ },
+ });
+
+ beforeEach(() => {
+ getVectorLayers.mockReturnValue([]);
+ });
+
+ it('should call setStyleFunction for each key in selectionObj', () => {
+ const layerDef = { id: 'layer-1', vectorStyle: { id: 'style-1' } };
+ const state = makeState([layerDef]);
+ const olLayer = { wv: { id: 'layer-1' } };
+ getVectorLayers.mockReturnValue([olLayer]);
+ updateVectorSelection({ 'layer-1': ['f1'] }, {}, [layerDef], 'select', state);
+ expect(setStyleFunction).toHaveBeenCalled();
+ });
+
+ it('should call setStyleFunction for each key in lastSelectionObj', () => {
+ const layerDef = { id: 'layer-1', vectorStyle: { id: 'style-1' } };
+ const state = makeState([layerDef]);
+ const olLayer = { wv: { id: 'layer-1' } };
+ getVectorLayers.mockReturnValue([olLayer]);
+ updateVectorSelection({}, { 'layer-1': ['f1'] }, [layerDef], 'deselect', state);
+ expect(setStyleFunction).toHaveBeenCalled();
+ });
+
+ it('should not call setStyleFunction when def is not found in layers', () => {
+ const state = makeState([]);
+ updateVectorSelection({ 'missing-layer': ['f1'] }, {}, [], 'select', state);
+ expect(setStyleFunction).not.toHaveBeenCalled();
+ });
+
+ it('should delete matching keys from lastSelection when they appear in selectionObj', () => {
+ const layerDef = { id: 'layer-1', vectorStyle: { id: 'style-1' } };
+ const state = makeState([layerDef]);
+ const olLayer = { wv: { id: 'layer-1' } };
+ getVectorLayers.mockReturnValue([olLayer]);
+ const lastSelection = { 'layer-1': ['f1'] };
+ updateVectorSelection({ 'layer-1': ['f2'] }, lastSelection, [layerDef], 'select', state);
+ expect(lastSelection['layer-1']).toBeUndefined();
+ });
+ });
});