Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

First pass of modules/ unit tests

Jason Hurley744ebc03580b
diff --git a/web/js/modules/alerts/reducer.test.js b/web/js/modules/alerts/reducer.test.js
index eebd906dc..05a10a817 100644
--- a/web/js/modules/alerts/reducer.test.js
+++ b/web/js/modules/alerts/reducer.test.js
@@ -4,22 +4,35 @@ import {
ACTIVATE_VECTOR_ZOOM_ALERT,
DISABLE_VECTOR_EXCEEDED_ALERT,
ACTIVATE_VECTOR_EXCEEDED_ALERT,
+ ACTIVATE_DDV_ZOOM_ALERT,
+ ACTIVATE_DDV_LOCATION_ALERT,
+ DEACTIVATE_DDV_ZOOM_ALERT,
+ DEACTIVATE_DDV_LOCATION_ALERT,
} from './constants';
+import { REMOVE_LAYER, REMOVE_GROUP } from '../layers/constants';
+import { UPDATE_MAP_EXTENT } from '../map/constants';
+
+jest.mock('../layers/util', () => ({
+ hasVectorLayers: jest.fn(),
+}));
+import { hasVectorLayers } from '../layers/util';
describe('alertReducer', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
test('Should return the initial state [alert-initial-state]', () => {
- expect(alertReducer(undefined, {})).toEqual(
- defaultAlertState,
- );
+ expect(alertReducer(undefined, {})).toEqual(defaultAlertState);
});
+
test('DISABLE_VECTOR_ZOOM_ALERT should disable vector zoom alert state [alert-disable-vector-zoom]', () => {
expect(alertReducer(
{ ...defaultAlertState, isVectorZoomAlertPresent: true },
{ type: DISABLE_VECTOR_ZOOM_ALERT },
- )).toEqual(
- defaultAlertState,
- );
+ )).toEqual(defaultAlertState);
});
+
test('ACTIVATE_VECTOR_ZOOM_ALERT should enable vector zoom alert state [alert-activate-vector-zoom]', () => {
const vectorZoomEnabledState = { ...defaultAlertState, isVectorZoomAlertPresent: true };
expect(alertReducer(
@@ -27,14 +40,14 @@ describe('alertReducer', () => {
{ type: ACTIVATE_VECTOR_ZOOM_ALERT },
)).toEqual(vectorZoomEnabledState);
});
+
test('DISABLE_VECTOR_EXCEEDED_ALERT should disable vector exceeded results alert state [alert-disable-vector-exceed]', () => {
expect(alertReducer(
{ ...defaultAlertState, isVectorExceededAlertPresent: true },
{ type: DISABLE_VECTOR_EXCEEDED_ALERT },
- )).toEqual(
- defaultAlertState,
- );
+ )).toEqual(defaultAlertState);
});
+
test('ACTIVATE_VECTOR_EXCEEDED_ALERT should enable vector exceeded results alert state [alert-activate-vector-exceed]', () => {
const vectorExceededEnabledState = { ...defaultAlertState, isVectorExceededAlertPresent: true };
expect(alertReducer(
@@ -42,4 +55,95 @@ describe('alertReducer', () => {
{ type: ACTIVATE_VECTOR_EXCEEDED_ALERT },
)).toEqual(vectorExceededEnabledState);
});
+
+ test('ACTIVATE_VECTOR_EXCEEDED_ALERT should also disable vector zoom alert [alert-activate-vector-exceed-clears-zoom]', () => {
+ const result = alertReducer(
+ { ...defaultAlertState, isVectorZoomAlertPresent: true },
+ { type: ACTIVATE_VECTOR_EXCEEDED_ALERT },
+ );
+ expect(result.isVectorExceededAlertPresent).toBe(true);
+ expect(result.isVectorZoomAlertPresent).toBe(false);
+ });
+
+ test('UPDATE_MAP_EXTENT should disable vector exceeded alert [alert-update-map-extent]', () => {
+ expect(alertReducer(
+ { ...defaultAlertState, isVectorExceededAlertPresent: true },
+ { type: UPDATE_MAP_EXTENT },
+ )).toEqual(defaultAlertState);
+ });
+
+ test('REMOVE_LAYER should return state unchanged when no vector alerts are present [alert-remove-layer-no-alerts]', () => {
+ const state = { ...defaultAlertState };
+ const result = alertReducer(state, { type: REMOVE_LAYER, layers: [] });
+ expect(result).toBe(state);
+ });
+
+ test('REMOVE_LAYER should clear vector alerts when no vector layers remain [alert-remove-layer-clears-alerts]', () => {
+ hasVectorLayers.mockReturnValue(false);
+ const state = { ...defaultAlertState, isVectorZoomAlertPresent: true };
+ const result = alertReducer(state, { type: REMOVE_LAYER, layers: [] });
+ expect(result.isVectorZoomAlertPresent).toBe(false);
+ expect(result.isVectorExceededAlertPresent).toBe(false);
+ });
+
+ test('REMOVE_LAYER should keep alerts when vector layers still exist [alert-remove-layer-keeps-alerts]', () => {
+ hasVectorLayers.mockReturnValue(true);
+ const state = { ...defaultAlertState, isVectorZoomAlertPresent: true };
+ const result = alertReducer(state, { type: REMOVE_LAYER, layers: [{}] });
+ expect(result).toBe(state);
+ });
+
+ test('REMOVE_GROUP should return state unchanged when no vector alerts are present [alert-remove-group-no-alerts]', () => {
+ const state = { ...defaultAlertState };
+ const result = alertReducer(state, { type: REMOVE_GROUP, layers: [] });
+ expect(result).toBe(state);
+ });
+
+ test('REMOVE_GROUP should clear vector alerts when no vector layers remain [alert-remove-group-clears-alerts]', () => {
+ hasVectorLayers.mockReturnValue(false);
+ const state = { ...defaultAlertState, isVectorExceededAlertPresent: true };
+ const result = alertReducer(state, { type: REMOVE_GROUP, layers: [] });
+ expect(result.isVectorZoomAlertPresent).toBe(false);
+ expect(result.isVectorExceededAlertPresent).toBe(false);
+ });
+
+ test('ACTIVATE_DDV_ZOOM_ALERT should set isDDVZoomAlertPresent and append title [alert-activate-ddv-zoom]', () => {
+ const result = alertReducer(undefined, { type: ACTIVATE_DDV_ZOOM_ALERT, title: 'Layer A' });
+ expect(result.isDDVZoomAlertPresent).toBe(true);
+ expect(result.ddvZoomAlerts).toEqual(['Layer A']);
+ });
+
+ test('ACTIVATE_DDV_LOCATION_ALERT should set isDDVLocationAlertPresent and append title [alert-activate-ddv-location]', () => {
+ const result = alertReducer(undefined, { type: ACTIVATE_DDV_LOCATION_ALERT, title: 'Layer B' });
+ expect(result.isDDVLocationAlertPresent).toBe(true);
+ expect(result.ddvLocationAlerts).toEqual(['Layer B']);
+ });
+
+ test('DEACTIVATE_DDV_ZOOM_ALERT should remove title and set isDDVZoomAlertPresent false when one alert remains [alert-deactivate-ddv-zoom-last]', () => {
+ const state = { ...defaultAlertState, isDDVZoomAlertPresent: true, ddvZoomAlerts: ['Layer A'] };
+ const result = alertReducer(state, { type: DEACTIVATE_DDV_ZOOM_ALERT, title: 'Layer A' });
+ expect(result.isDDVZoomAlertPresent).toBe(false);
+ expect(result.ddvZoomAlerts).toEqual([]);
+ });
+
+ test('DEACTIVATE_DDV_ZOOM_ALERT should keep isDDVZoomAlertPresent true when multiple alerts remain [alert-deactivate-ddv-zoom-multiple]', () => {
+ const state = { ...defaultAlertState, isDDVZoomAlertPresent: true, ddvZoomAlerts: ['Layer A', 'Layer B'] };
+ const result = alertReducer(state, { type: DEACTIVATE_DDV_ZOOM_ALERT, title: 'Layer A' });
+ expect(result.isDDVZoomAlertPresent).toBe(true);
+ expect(result.ddvZoomAlerts).toEqual(['Layer B']);
+ });
+
+ test('DEACTIVATE_DDV_LOCATION_ALERT should remove title and set isDDVLocationAlertPresent false when one alert remains [alert-deactivate-ddv-location-last]', () => {
+ const state = { ...defaultAlertState, isDDVLocationAlertPresent: true, ddvLocationAlerts: ['Layer C'] };
+ const result = alertReducer(state, { type: DEACTIVATE_DDV_LOCATION_ALERT, title: 'Layer C' });
+ expect(result.isDDVLocationAlertPresent).toBe(false);
+ expect(result.ddvLocationAlerts).toEqual([]);
+ });
+
+ test('DEACTIVATE_DDV_LOCATION_ALERT should keep isDDVLocationAlertPresent true when multiple alerts remain [alert-deactivate-ddv-location-multiple]', () => {
+ const state = { ...defaultAlertState, isDDVLocationAlertPresent: true, ddvLocationAlerts: ['Layer C', 'Layer D'] };
+ const result = alertReducer(state, { type: DEACTIVATE_DDV_LOCATION_ALERT, title: 'Layer C' });
+ expect(result.isDDVLocationAlertPresent).toBe(true);
+ expect(result.ddvLocationAlerts).toEqual(['Layer D']);
+ });
});
diff --git a/web/js/modules/animation/actions.test.js b/web/js/modules/animation/actions.test.js
index 73e2b5511..805f6086f 100644
--- a/web/js/modules/animation/actions.test.js
+++ b/web/js/modules/animation/actions.test.js
@@ -8,98 +8,143 @@ import {
stop,
toggleLooping,
toggleComponentGifActive,
+ toggleAnimationCollapse,
+ toggleAnimationAutoplay,
changeStartDate,
changeEndDate,
changeStartAndEndDate,
changeFrameRate,
changeCropBounds,
onActivate,
+ playKioskAnimation,
} from './actions';
import fixtures from '../../fixtures';
const middlewares = [thunk];
const state = fixtures.getState();
+test(
+ `changeFrameRate action returns ${constants.UPDATE_FRAME_RATE} action type and number value [animation-action-speed]`,
+ () => {
+ const response = changeFrameRate(2);
+ expect(response.type).toEqual(constants.UPDATE_FRAME_RATE);
+ expect(response.value).toEqual(2);
+ },
+);
+
+test(
+ `onActivate action returns ${constants.OPEN_ANIMATION} action type and current dateValue [animation-action-activate]`,
+ () => {
+ const mockStore = configureMockStore(middlewares);
+ const store = mockStore(state);
+ store.dispatch(onActivate());
+ const response1 = store.getActions()[0];
+ const response2 = store.getActions()[1];
+ expect(response1.type).toEqual(constants.UPDATE_START_AND_END_DATE);
+ expect(response1.endDate).toEqual(state.date.selected);
+ expect(response1.startDate).toEqual(
+ util.dateAdd(state.date.selected, 'day', -10),
+ );
+ expect(response2.type).toEqual(constants.OPEN_ANIMATION);
+ },
+);
+
+test(
+ `changeBoundary action returns ${constants.UPDATE_CROP_BOUNDS} action type and current bounds value [animation-action-boundary]`,
+ () => {
+ const mockStore = configureMockStore(middlewares);
+ const store = mockStore(state);
+ const mockBounds = {
+ x: 1, y: 1, x2: 2, y2: 2,
+ };
+ store.dispatch(changeCropBounds(mockBounds));
+ const response = store.getActions()[0];
+ expect(response.type).toEqual(constants.UPDATE_CROP_BOUNDS);
+ expect(response.value).toEqual(mockBounds);
+ },
+);
+
describe('Open, play, stop, close and toggle actions', () => {
test(
`onClose action returns ${constants.EXIT_ANIMATION} action type [animation-action-exit]`,
() => {
- const expectedAction = {
- type: constants.EXIT_ANIMATION,
- };
+ const expectedAction = { type: constants.EXIT_ANIMATION };
expect(onClose().type).toEqual(expectedAction.type);
},
);
+
test(
`play action returns ${constants.PLAY_ANIMATION} action type [animation-action-play]`,
() => {
- const expectedAction = {
- type: constants.PLAY_ANIMATION,
- };
+ const expectedAction = { type: constants.PLAY_ANIMATION };
expect(play().type).toEqual(expectedAction.type);
},
);
+
test(
`stop action returns ${constants.STOP_ANIMATION} action type [animation-action-stop]`,
() => {
- const expectedAction = {
- type: constants.STOP_ANIMATION,
- };
+ const expectedAction = { type: constants.STOP_ANIMATION };
expect(stop().type).toEqual(expectedAction.type);
},
);
+
test(
`toggleLooping action returns ${constants.TOGGLE_LOOPING} action type [animation-action-loop]`,
() => {
- const expectedAction = {
- type: constants.TOGGLE_LOOPING,
- };
+ const expectedAction = { type: constants.TOGGLE_LOOPING };
expect(toggleLooping().type).toEqual(expectedAction.type);
},
);
+
test(
- `toggleComponentGifActive action returns ${
- constants.TOGGLE_GIF
- } action type [animation-action-gif]`,
+ `toggleComponentGifActive action returns ${constants.TOGGLE_GIF} action type [animation-action-gif]`,
() => {
- const expectedAction = {
- type: constants.TOGGLE_GIF,
- };
+ const expectedAction = { type: constants.TOGGLE_GIF };
expect(toggleComponentGifActive().type).toEqual(expectedAction.type);
},
);
+
+ test(
+ `toggleAnimationCollapse action returns ${constants.COLLAPSE_ANIMATION} action type [animation-action-collapse]`,
+ () => {
+ expect(toggleAnimationCollapse().type).toEqual(constants.COLLAPSE_ANIMATION);
+ },
+ );
+
+ test(
+ `toggleAnimationAutoplay action returns ${constants.TOGGLE_AUTOPLAY} action type [animation-action-autoplay]`,
+ () => {
+ expect(toggleAnimationAutoplay().type).toEqual(constants.TOGGLE_AUTOPLAY);
+ },
+ );
});
+
describe('Animation Datechange actions', () => {
const now = util.now();
const then = util.dateAdd(now, 'day', -7);
+
test(
- `changeStartDate action returns ${
- constants.UPDATE_START_DATE
- } action type and current date as value [animation-action-start-date]`,
+ `changeStartDate action returns ${constants.UPDATE_START_DATE} action type and current date as value [animation-action-start-date]`,
() => {
- const expectedAction = {
- type: constants.UPDATE_START_DATE,
- value: now,
- };
+ const expectedAction = { type: constants.UPDATE_START_DATE, value: now };
const response = changeStartDate(now);
expect(response.type).toEqual(expectedAction.type);
expect(response.value).toEqual(now);
},
);
+
test(
- `changeEndDate action returns ${
- constants.UPDATE_END_DATE
- } action type and current date as value [animation-action-end-date]`,
+ `changeEndDate action returns ${constants.UPDATE_END_DATE} action type and current date as value [animation-action-end-date]`,
() => {
const response = changeEndDate(now);
expect(response.type).toEqual(constants.UPDATE_END_DATE);
expect(response.value).toEqual(now);
},
);
+
test(
- `changeStartAndEndDate action returns ${
- constants.UPDATE_START_AND_END_DATE
- } action type and current date as value [animation-action-start-and-end-date]`,
+ `changeStartAndEndDate action returns ${constants.UPDATE_START_AND_END_DATE} action type and current date as value [animation-action-start-and-end-date]`,
() => {
const response = changeStartAndEndDate(then, now);
expect(response.type).toEqual(constants.UPDATE_START_AND_END_DATE);
@@ -109,46 +154,123 @@ describe('Animation Datechange actions', () => {
);
});
-test(
- `changeFrameRate action returns ${
- constants.UPDATE_FRAME_RATE
- } action type and number value [animation-action-speed]`,
- () => {
- const response = changeFrameRate(2);
- expect(response.type).toEqual(constants.UPDATE_FRAME_RATE);
- expect(response.value).toEqual(2);
- },
-);
-test(
- `onActivate action returns ${
- constants.OPEN_ANIMATION
- } action type and current dateValue [animation-action-activate]`,
- () => {
- const mockStore = configureMockStore(middlewares);
- const store = mockStore(state);
- store.dispatch(onActivate());
- const response1 = store.getActions()[0];
- const response2 = store.getActions()[1];
- expect(response1.type).toEqual(constants.UPDATE_START_AND_END_DATE);
- expect(response1.endDate).toEqual(state.date.selected);
- expect(response1.startDate).toEqual(
- util.dateAdd(state.date.selected, 'day', -10),
- );
- expect(response2.type).toEqual(constants.OPEN_ANIMATION);
- },
-);
+describe('playKioskAnimation action', () => {
+ const now = util.now();
+ const then = util.dateAdd(now, 'day', -7);
-test(
- `changeBoundary action returns ${constants.UPDATE_CROP_BOUNDS} action type and current bounds value [animation-action-boundary]`,
- () => {
- const mockStore = configureMockStore(middlewares);
- const store = mockStore(state);
- const mockBounds = {
- x: 1, y: 1, x2: 2, y2: 2,
- };
- store.dispatch(changeCropBounds(mockBounds));
- const response = store.getActions()[0];
- expect(response.type).toEqual(constants.UPDATE_CROP_BOUNDS);
- expect(response.value).toEqual(mockBounds);
- },
-);
+ test(
+ `playKioskAnimation action returns ${constants.PLAY_KIOSK_ANIMATIONS} action type with startDate and endDate [animation-action-kiosk]`,
+ () => {
+ const response = playKioskAnimation(then, now);
+ expect(response.type).toEqual(constants.PLAY_KIOSK_ANIMATIONS);
+ expect(response.startDate).toEqual(then);
+ expect(response.endDate).toEqual(now);
+ },
+ );
+});
+
+describe('onActivate with existing startDate and endDate', () => {
+ test(
+ 'onActivate skips UPDATE_START_AND_END_DATE when startDate and endDate already exist [animation-action-activate-existing-dates]',
+ () => {
+ const mockStore = configureMockStore(middlewares);
+ const stateWithDates = {
+ ...state,
+ animation: {
+ ...state.animation,
+ startDate: util.dateAdd(state.date.selected, 'day', -5),
+ endDate: state.date.selected,
+ },
+ };
+ const store = mockStore(stateWithDates);
+ store.dispatch(onActivate());
+ const actions = store.getActions();
+ expect(actions.length).toEqual(1);
+ expect(actions[0].type).toEqual(constants.OPEN_ANIMATION);
+ },
+ );
+});
+
+describe('onActivate with customSelected interval', () => {
+ test(
+ 'onActivate uses customInterval and customDelta when customSelected is true [animation-action-activate-custom]',
+ () => {
+ const mockStore = configureMockStore(middlewares);
+ const customState = {
+ ...state,
+ animation: {
+ ...state.animation,
+ startDate: null,
+ endDate: null,
+ },
+ date: {
+ ...state.date,
+ customSelected: true,
+ customDelta: 1,
+ customInterval: 3,
+ autoSelected: false,
+ },
+ };
+ const store = mockStore(customState);
+ store.dispatch(onActivate());
+ const actions = store.getActions();
+ expect(actions[0].type).toEqual(constants.UPDATE_START_AND_END_DATE);
+ expect(actions[1].type).toEqual(constants.OPEN_ANIMATION);
+ },
+ );
+});
+
+describe('onActivate with autoSelected', () => {
+ test(
+ 'onActivate uses autoSelected imagery delta frames [animation-action-activate-auto]',
+ () => {
+ const mockStore = configureMockStore(middlewares);
+ const autoState = {
+ ...state,
+ animation: {
+ ...state.animation,
+ startDate: null,
+ endDate: null,
+ },
+ date: {
+ ...state.date,
+ autoSelected: true,
+ customSelected: false,
+ },
+ };
+ const store = mockStore(autoState);
+ store.dispatch(onActivate());
+ const actions = store.getActions();
+ expect(actions[0].type).toEqual(constants.UPDATE_START_AND_END_DATE);
+ expect(actions[1].type).toEqual(constants.OPEN_ANIMATION);
+ },
+ );
+});
+
+describe('onActivate appNow past tenFramesAfter branch', () => {
+ test(
+ 'onActivate uses activeDate as startDate when appNow is past tenFramesAfter [animation-action-activate-past]',
+ () => {
+ const mockStore = configureMockStore(middlewares);
+ const pastState = {
+ ...state,
+ animation: {
+ ...state.animation,
+ startDate: null,
+ endDate: null,
+ },
+ date: {
+ ...state.date,
+ autoSelected: false,
+ customSelected: false,
+ appNow: new Date('2099-01-01'),
+ },
+ };
+ const store = mockStore(pastState);
+ store.dispatch(onActivate());
+ const actions = store.getActions();
+ expect(actions[0].type).toEqual(constants.UPDATE_START_AND_END_DATE);
+ expect(actions[1].type).toEqual(constants.OPEN_ANIMATION);
+ },
+ );
+});
diff --git a/web/js/modules/animation/gifstream.test.js b/web/js/modules/animation/gifstream.test.js
index c9a87f216..681fa0935 100644
--- a/web/js/modules/animation/gifstream.test.js
+++ b/web/js/modules/animation/gifstream.test.js
@@ -1,3 +1,445 @@
-test('gifstream module test', () => {
+import GifStream from './gifstream';
+import GifWriter from '../../lib/gifwriter';
+import NeuQuant from '../../lib/neuquant';
+jest.mock('../../lib/gifwriter');
+jest.mock('../../lib/neuquant');
+
+const mockEnqueue = jest.fn();
+const mockClose = jest.fn();
+
+const mockPaletteRGB = [255, 0, 0, 0, 255, 0, 0, 0, 255];
+
+const mockNeuQuantInstance = {
+ process: jest.fn(() => mockPaletteRGB),
+ map: jest.fn(() => 0),
+};
+NeuQuant.mockImplementation(() => mockNeuQuantInstance);
+
+const mockGifWriterInstance = { getReader: jest.fn() };
+GifWriter.mockImplementation(() => mockGifWriterInstance);
+
+function makeImageData(width = 2, height = 2) {
+ const data = new Uint8ClampedArray(width * height * 4).fill(128);
+ return { data, width, height };
+}
+
+function makeCtx(width = 2, height = 2) {
+ return {
+ clearRect: jest.fn(),
+ getContext: jest.fn(),
+ drawImage: jest.fn(),
+ font: '',
+ fillStyle: '',
+ textAlign: '',
+ textBaseline: '',
+ strokeStyle: '',
+ lineWidth: 0,
+ strokeText: jest.fn(),
+ fillText: jest.fn(),
+ getImageData: jest.fn(() => makeImageData(width, height)),
+ };
+}
+
+function baseOptions(overrides = {}) {
+ return {
+ gifWidth: 2,
+ gifHeight: 2,
+ fontColor: '#fff',
+ fontSize: '12px',
+ fontFamily: 'Arial',
+ fontWeight: 'bold',
+ text: '',
+ textAlign: 'center',
+ textBaseline: 'bottom',
+ waterMark: null,
+ waterMarkHeight: 0,
+ waterMarkWidth: 0,
+ waterMarkXCoordinate: 0,
+ waterMarkYCoordinate: 0,
+ loop: 0,
+ images: [{ src: 'img1.png' }],
+ progressCallback: jest.fn(),
+ showFrameText: false,
+ ...overrides,
+ };
+}
+
+describe('GifStream', () => {
+ let gs;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ gs = new GifStream();
+ });
+
+ describe('constructor', () => {
+ it('initializes canvas and ctx to null', () => {
+ expect(gs.canvas).toBeNull();
+ expect(gs.ctx).toBeNull();
+ });
+ });
+
+ describe('cancel', () => {
+ it('sets cancelled to true when no promise exists', () => {
+ gs.cancel();
+ expect(gs.cancelled).toBe(true);
+ });
+
+ it('cancels the promise when one exists', () => {
+ gs.promise = { cancel: jest.fn() };
+ gs.cancel();
+ expect(gs.cancelled).toBe(true);
+ expect(gs.promise.cancel).toHaveBeenCalled();
+ });
+ });
+
+ describe('createGIF', () => {
+ beforeEach(() => {
+ jest.spyOn(document, 'createElement').mockReturnValue({
+ getContext: jest.fn(() => makeCtx()),
+ width: 0,
+ height: 0,
+ });
+ });
+
+ it('throws when images array is empty', () => {
+ expect(() => gs.createGIF(baseOptions({ images: [] }), jest.fn())).toThrow('No images found');
+ });
+
+ it('clears existing canvas rect when canvas already exists', () => {
+ const mockClearRect = jest.fn();
+ gs.canvas = { width: 2, height: 2 };
+ gs.ctx = { clearRect: mockClearRect };
+ jest.spyOn(gs, 'getImagePromise').mockReturnValue(Promise.resolve({}));
+ gs.createGIF(baseOptions(), jest.fn());
+ expect(mockClearRect).toHaveBeenCalledWith(0, 0, 2, 2);
+ });
+
+ it('calls getImagePromise for each image', () => {
+ const spy = jest.spyOn(gs, 'getImagePromise').mockReturnValue(Promise.resolve({}));
+ gs.createGIF(baseOptions({ images: [{ src: 'a.png' }, { src: 'b.png' }] }), jest.fn());
+ expect(spy).toHaveBeenCalledTimes(2);
+ });
+
+ it('calls progressCallback with 0 on start', async () => {
+ const progressCallback = jest.fn();
+ const mockReader = {
+ read: jest.fn().mockResolvedValue({ done: true, value: undefined }),
+ };
+ mockGifWriterInstance.getReader.mockReturnValue(mockReader);
+ jest.spyOn(gs, 'getImagePromise').mockResolvedValue({});
+ jest.spyOn(gs, 'getStream').mockReturnValue(mockGifWriterInstance);
+ await new Promise((resolve) => {
+ gs.createGIF(baseOptions({ progressCallback }), resolve);
+ });
+ expect(progressCallback).toHaveBeenCalledWith(0);
+ });
+
+ it('calls callback with blob when stream is done', async () => {
+ const mockReader = {
+ read: jest.fn()
+ .mockResolvedValueOnce({ done: false, value: new Uint8Array([1, 2]) })
+ .mockResolvedValueOnce({ done: true, value: undefined }),
+ };
+ mockGifWriterInstance.getReader.mockReturnValue(mockReader);
+ jest.spyOn(gs, 'getImagePromise').mockResolvedValue({});
+ jest.spyOn(gs, 'getStream').mockReturnValue(mockGifWriterInstance);
+
+ jest.useFakeTimers();
+ const resultPromise = new Promise((resolve) => {
+ gs.createGIF(baseOptions({ images: [{ src: 'a.png' }] }), resolve);
+ });
+ await jest.runAllTimersAsync();
+ const result = await resultPromise;
+ jest.useRealTimers();
+
+ expect(result.blob).toBeInstanceOf(Blob);
+ expect(result.error).toBe('');
+ });
+
+ it('calls returnCancel when cancelled mid-stream', async () => {
+ const mockReader = {
+ read: jest.fn().mockResolvedValue({ done: false, value: new Uint8Array([1]) }),
+ };
+ mockGifWriterInstance.getReader.mockReturnValue(mockReader);
+ jest.spyOn(gs, 'getImagePromise').mockResolvedValue({});
+ jest.spyOn(gs, 'getStream').mockReturnValue(mockGifWriterInstance);
+ jest.useFakeTimers();
+ const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ const result = await new Promise((resolve) => {
+ gs.createGIF(baseOptions(), (obj) => {
+ if (obj.cancelled) resolve(obj);
+ });
+ gs.cancelled = true;
+ jest.runAllTimers();
+ });
+ expect(result.cancelled).toBe(true);
+ consoleSpy.mockRestore();
+ jest.useRealTimers();
+ });
+
+ it('calls returnError when getImagePromise rejects', async () => {
+ jest.spyOn(gs, 'getImagePromise').mockRejectedValue(new Error('load error'));
+ const result = await new Promise((resolve) => {
+ gs.createGIF(baseOptions(), (obj) => {
+ if (obj.error) resolve(obj);
+ });
+ });
+ expect(result.blob).toBeNull();
+ expect(result.error).toBeDefined();
+ });
+ });
+
+ describe('getImagePromise', () => {
+ beforeEach(() => {
+ gs.options = baseOptions();
+ });
+
+ it('resolves with img on load', async () => {
+ const mockImg = {
+ onload: null,
+ onerror: null,
+ src: '',
+ width: 0,
+ height: 0,
+ text: '',
+ delay: 0,
+ crossOrigin: '',
+ };
+ jest.spyOn(global, 'Image').mockImplementation(() => mockImg);
+ URL.revokeObjectURL = jest.fn();
+ const promise = gs.getImagePromise({ src: 'test.png', text: 'hi', delay: 200 });
+ mockImg.onload();
+ const img = await promise;
+ expect(img).toBe(mockImg);
+ });
+
+ it('rejects on error', async () => {
+ const mockImg = {
+ onload: null,
+ onerror: null,
+ src: '',
+ width: 0,
+ height: 0,
+ text: '',
+ delay: 0,
+ crossOrigin: '',
+ };
+ jest.spyOn(global, 'Image').mockImplementation(() => mockImg);
+ const promise = gs.getImagePromise({ src: 'bad.png' });
+ mockImg.onerror(new Error('fail'));
+ await expect(promise).rejects.toBeDefined();
+ });
+ });
+
+ describe('addFrameDetails', () => {
+ it('draws image to canvas and returns ctx', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'Hello', showFrameText: true });
+ const img = { text: 'frame text', src: 'img.png' };
+ const result = gs.addFrameDetails(ctx, img);
+ expect(ctx.drawImage).toHaveBeenCalled();
+ expect(result).toBe(ctx);
+ });
+
+ it('applies text when text exists', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'test text', showFrameText: false });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalledWith('test text', expect.any(Number), expect.any(Number));
+ });
+
+ it('applies frameText when showFrameText is true and frameText exists', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'global', showFrameText: true });
+ const img = { text: 'frame text' };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalledWith('frame text', expect.any(Number), expect.any(Number));
+ });
+
+ it('applies stroke when options.stroke is set', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({
+ text: 'stroked',
+ showFrameText: true,
+ stroke: { color: 'black', pixels: 2 },
+ });
+ const img = { text: 'stroked' };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.strokeText).toHaveBeenCalled();
+ });
+
+ it('draws watermark when waterMark is set', () => {
+ const ctx = makeCtx();
+ const waterMark = {};
+ gs.options = baseOptions({
+ waterMark,
+ waterMarkXCoordinate: 0,
+ waterMarkYCoordinate: 0,
+ waterMarkWidth: 10,
+ waterMarkHeight: 10,
+ });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.drawImage).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns error string on exception', () => {
+ const ctx = makeCtx();
+ ctx.drawImage.mockImplementation(() => { throw new Error('draw error'); });
+ gs.options = baseOptions();
+ const img = { text: null };
+ const result = gs.addFrameDetails(ctx, img);
+ expect(typeof result).toBe('string');
+ expect(result).toContain('Error');
+ });
+
+ it('uses textXCoordinate from options when provided', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'hi', textXCoordinate: 99 });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalledWith('hi', 99, expect.any(Number));
+ });
+
+ it('uses textYCoordinate from options when provided', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'hi', textYCoordinate: 77 });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalledWith('hi', expect.any(Number), 77);
+ });
+
+ it('uses textAlign right branch', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'hi', textAlign: 'right' });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalled();
+ });
+
+ it('uses textAlign left branch', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'hi', textAlign: 'left' });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalled();
+ });
+
+ it('uses textBaseline center branch', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'hi', textBaseline: 'center' });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalled();
+ });
+
+ it('uses textBaseline top branch', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: 'hi', textBaseline: 'top' });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).toHaveBeenCalled();
+ });
+
+ it('does not call fillText when no text', () => {
+ const ctx = makeCtx();
+ gs.options = baseOptions({ text: '', showFrameText: false });
+ const img = { text: null };
+ gs.addFrameDetails(ctx, img);
+ expect(ctx.fillText).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('getStream', () => {
+ let ctx;
+ let pullFn;
+ let capturedController;
+
+ beforeEach(() => {
+ ctx = makeCtx();
+ gs.options = baseOptions();
+
+ global.ReadableStream = jest.fn(({ pull }) => {
+ pullFn = pull;
+ return { _pull: pull };
+ });
+
+ capturedController = { enqueue: mockEnqueue, close: mockClose };
+ });
+
+ it('returns a GifWriter instance', () => {
+ const frames = [{ delay: 500 }];
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ expect(GifWriter).toHaveBeenCalled();
+ });
+
+ it('uses loop option when provided', () => {
+ const frames = [{ delay: 100 }];
+ gs.options = baseOptions({ loop: 2 });
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ expect(GifWriter).toHaveBeenCalledWith(
+ expect.anything(), 2, 2, { loop: 2 },
+ );
+ });
+
+ it('defaults loop to 0 when not set', () => {
+ const frames = [{ delay: 100 }];
+ gs.options = baseOptions({ loop: undefined });
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ expect(GifWriter).toHaveBeenCalledWith(
+ expect.anything(), 2, 2, { loop: 0 },
+ );
+ });
+
+ it('enqueues pixel data for a frame with a delay', () => {
+ const frames = [{ delay: 200 }];
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ pullFn(capturedController);
+ expect(mockEnqueue).toHaveBeenCalled();
+ });
+
+ it('uses default delay of 100 when frame.delay is falsy', () => {
+ const frames = [{ delay: 0 }];
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ pullFn(capturedController);
+ const enqueueArgs = mockEnqueue.mock.calls[0][0];
+ expect(enqueueArgs[5].delay).toBe(100);
+ });
+
+ it('adds extraLastFrameDelay on the last frame', () => {
+ const frames = [{ delay: 100 }];
+ gs.options = baseOptions({ extraLastFrameDelay: 500 });
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ pullFn(capturedController);
+ const enqueueArgs = mockEnqueue.mock.calls[0][0];
+ expect(enqueueArgs[5].delay).toBe(10 + 50);
+ });
+
+ it('does not add extraLastFrameDelay to non-last frames', () => {
+ const frames = [{ delay: 100 }, { delay: 100 }];
+ gs.options = baseOptions({ extraLastFrameDelay: 500, images: [{ src: 'a' }, { src: 'b' }] });
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ pullFn(capturedController);
+ const enqueueArgs = mockEnqueue.mock.calls[0][0];
+ expect(enqueueArgs[5].delay).toBe(10);
+ });
+
+ it('maps pixels correctly', () => {
+ const frames = [{ delay: 100 }];
+ jest.spyOn(gs, 'addFrameDetails').mockReturnValue(ctx);
+ gs.getStream(frames, ctx);
+ pullFn(capturedController);
+ expect(mockNeuQuantInstance.map).toHaveBeenCalled();
+ });
+ });
});
diff --git a/web/js/modules/animation/reducer.test.js b/web/js/modules/animation/reducer.test.js
deleted file mode 100644
index 7cbe7e263..000000000
--- a/web/js/modules/animation/reducer.test.js
+++ /dev/null
@@ -1,101 +0,0 @@
-import update from 'immutability-helper';
-import { defaultState, animationReducer } from './reducers';
-import * as CONSTANTS from './constants';
-import util from '../../util/util';
-
-const now = util.now();
-const then = util.dateAdd(now, 'day', -7);
-
-test('OPEN_ANIMATION action updates active state [animation-reducer-open]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.OPEN_ANIMATION,
- });
-
- expect(response.isActive).toEqual(true);
-});
-
-test('EXIT_ANIMATION action toggles isPlaying and isActive values [animation-reducer-exit]', () => {
- let updatedState = update(defaultState, { isActive: { $set: true } });
- updatedState = update(updatedState, { isPlaying: { $set: true } });
- const response = animationReducer(updatedState, {
- type: CONSTANTS.EXIT_ANIMATION,
- });
- expect(updatedState.isActive).toEqual(true);
- expect(updatedState.isPlaying).toEqual(true);
- expect(response.isActive).toEqual(false);
- expect(response.isPlaying).toEqual(false);
-});
-test('PLAY_ANIMATION action makes isPlaying truthy [animation-reducer-play]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.PLAY_ANIMATION,
- });
- expect(defaultState.isPlaying).toEqual(false);
- expect(response.isPlaying).toEqual(true);
-});
-test('UPDATE_FRAME_RATE action changes speed value [animation-reducer-speed]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.UPDATE_FRAME_RATE,
- value: 5,
- });
- expect(defaultState.speed).toEqual(3);
- expect(response.speed).toEqual(5);
-});
-test('UPDATE_START_AND_END_DATE action updates dates [animation-reducer-start-and-end-date]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.UPDATE_START_AND_END_DATE,
- startDate: then,
- endDate: now,
- });
- expect(defaultState.startDate).toBeUndefined();
- expect(defaultState.endDate).toBeUndefined();
- expect(response.startDate).toEqual(then);
- expect(response.endDate).toEqual(now);
-});
-test('UPDATE_START_DATE action changes startDate value [animation-reducer-start-date]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.UPDATE_START_DATE,
- value: then,
- });
- expect(defaultState.startDate).toBeUndefined();
- expect(response.startDate).toEqual(then);
-});
-test('UPDATE_END_DATE action changes endDate value [animation-reducer-end-date]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.UPDATE_END_DATE,
- value: now,
- });
- expect(defaultState.startDate).toBeUndefined();
- expect(response.endDate).toEqual(now);
-});
-test('TOGGLE_LOOPING action toggles loop value [animation-reducer-loop]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.TOGGLE_LOOPING,
- });
- expect(defaultState.loop).toBeFalsy();
- expect(response.loop).toBeTruthy();
-});
-test('TOGGLE_GIF action toggles gifActive bool value [animation-reducer-gif]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.TOGGLE_GIF,
- });
- expect(defaultState.gifActive).toBeFalsy();
- expect(response.gifActive).toBeTruthy();
-});
-
-test('KEY_PRESS_ACTION action toggles isPlaying bool when animation is active [animation-reducer-key-press-active]', () => {
- const updatedState = update(defaultState, { isActive: { $set: true } });
- const response = animationReducer(updatedState, {
- type: CONSTANTS.KEY_PRESS_ACTION,
- keyCode: 32,
- });
- expect(updatedState.isPlaying).toBeFalsy();
- expect(response.isPlaying).toBeTruthy();
-});
-test('KEY_PRESS_ACTION action does not toggle isPlaying bool when animation is inActive [animation-reducer-key-press-disabled]', () => {
- const response = animationReducer(defaultState, {
- type: CONSTANTS.KEY_PRESS_ACTION,
- keyCode: 32,
- });
- expect(defaultState.isPlaying).toBeFalsy();
- expect(response.isPlaying).toBeFalsy();
-});
diff --git a/web/js/modules/animation/reducers.test.js b/web/js/modules/animation/reducers.test.js
new file mode 100644
index 000000000..1ee5dcf34
--- /dev/null
+++ b/web/js/modules/animation/reducers.test.js
@@ -0,0 +1,244 @@
+import update from 'immutability-helper';
+import { defaultState, animationReducer, getInitialState } from './reducers';
+import * as CONSTANTS from './constants';
+import util from '../../util/util';
+
+const now = util.now();
+const then = util.dateAdd(now, 'day', -7);
+
+test('OPEN_ANIMATION action updates active state [animation-reducer-open]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.OPEN_ANIMATION,
+ });
+
+ expect(response.isActive).toEqual(true);
+});
+
+test('EXIT_ANIMATION action toggles isPlaying and isActive values [animation-reducer-exit]', () => {
+ let updatedState = update(defaultState, { isActive: { $set: true } });
+ updatedState = update(updatedState, { isPlaying: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.EXIT_ANIMATION,
+ });
+ expect(updatedState.isActive).toEqual(true);
+ expect(updatedState.isPlaying).toEqual(true);
+ expect(response.isActive).toEqual(false);
+ expect(response.isPlaying).toEqual(false);
+});
+
+test('PLAY_ANIMATION action makes isPlaying truthy [animation-reducer-play]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.PLAY_ANIMATION,
+ });
+ expect(defaultState.isPlaying).toEqual(false);
+ expect(response.isPlaying).toEqual(true);
+});
+
+test('UPDATE_FRAME_RATE action changes speed value [animation-reducer-speed]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.UPDATE_FRAME_RATE,
+ value: 5,
+ });
+ expect(defaultState.speed).toEqual(3);
+ expect(response.speed).toEqual(5);
+});
+
+test('UPDATE_START_AND_END_DATE action updates dates [animation-reducer-start-and-end-date]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.UPDATE_START_AND_END_DATE,
+ startDate: then,
+ endDate: now,
+ });
+ expect(defaultState.startDate).toBeUndefined();
+ expect(defaultState.endDate).toBeUndefined();
+ expect(response.startDate).toEqual(then);
+ expect(response.endDate).toEqual(now);
+});
+
+test('UPDATE_START_DATE action changes startDate value [animation-reducer-start-date]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.UPDATE_START_DATE,
+ value: then,
+ });
+ expect(defaultState.startDate).toBeUndefined();
+ expect(response.startDate).toEqual(then);
+});
+
+test('UPDATE_END_DATE action changes endDate value [animation-reducer-end-date]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.UPDATE_END_DATE,
+ value: now,
+ });
+ expect(defaultState.startDate).toBeUndefined();
+ expect(response.endDate).toEqual(now);
+});
+
+test('TOGGLE_LOOPING action toggles loop value [animation-reducer-loop]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.TOGGLE_LOOPING,
+ });
+ expect(defaultState.loop).toBeFalsy();
+ expect(response.loop).toBeTruthy();
+});
+
+test('TOGGLE_GIF action toggles gifActive bool value [animation-reducer-gif]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.TOGGLE_GIF,
+ });
+ expect(defaultState.gifActive).toBeFalsy();
+ expect(response.gifActive).toBeTruthy();
+});
+
+test('KEY_PRESS_ACTION action toggles isPlaying bool when animation is active [animation-reducer-key-press-active]', () => {
+ const updatedState = update(defaultState, { isActive: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.KEY_PRESS_ACTION,
+ keyCode: 32,
+ });
+ expect(updatedState.isPlaying).toBeFalsy();
+ expect(response.isPlaying).toBeTruthy();
+});
+
+test('KEY_PRESS_ACTION action does not toggle isPlaying bool when animation is inActive [animation-reducer-key-press-disabled]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.KEY_PRESS_ACTION,
+ keyCode: 32,
+ });
+ expect(defaultState.isPlaying).toBeFalsy();
+ expect(response.isPlaying).toBeFalsy();
+});
+
+test('STOP_ANIMATION action sets isPlaying to false [animation-reducer-stop]', () => {
+ const updatedState = update(defaultState, { isPlaying: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.STOP_ANIMATION,
+ });
+ expect(updatedState.isPlaying).toEqual(true);
+ expect(response.isPlaying).toEqual(false);
+});
+
+test('UPDATE_CROP_BOUNDS action sets boundaries value [animation-reducer-crop-bounds]', () => {
+ const bounds = { x: 0, y: 0, width: 100, height: 100 };
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.UPDATE_CROP_BOUNDS,
+ value: bounds,
+ });
+ expect(defaultState.boundaries).toBeUndefined();
+ expect(response.boundaries).toEqual(bounds);
+});
+
+test('COLLAPSE_ANIMATION action toggles isCollapsed value [animation-reducer-collapse]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.COLLAPSE_ANIMATION,
+ });
+ expect(defaultState.isCollapsed).toBeFalsy();
+ expect(response.isCollapsed).toBeTruthy();
+});
+
+test('TOGGLE_AUTOPLAY action toggles autoplay value [animation-reducer-autoplay]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.TOGGLE_AUTOPLAY,
+ });
+ expect(defaultState.autoplay).toBeFalsy();
+ expect(response.autoplay).toBeTruthy();
+});
+
+test('KEY_PRESS_ACTION with keyCode 27 exits animation [animation-reducer-key-press-escape]', () => {
+ const updatedState = update(defaultState, {
+ isActive: { $set: true },
+ isPlaying: { $set: true },
+ gifActive: { $set: true },
+ });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.KEY_PRESS_ACTION,
+ keyCode: 27,
+ });
+ expect(response.isActive).toEqual(false);
+ expect(response.isPlaying).toEqual(false);
+ expect(response.gifActive).toEqual(false);
+});
+
+test('KEY_PRESS_ACTION with unrelated keyCode returns unchanged state [animation-reducer-key-press-other]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.KEY_PRESS_ACTION,
+ keyCode: 65,
+ });
+ expect(response).toEqual(defaultState);
+});
+
+test('PLAY_KIOSK_ANIMATIONS action sets loop, speed, dates, and isPlaying [animation-reducer-kiosk]', () => {
+ const response = animationReducer(defaultState, {
+ type: CONSTANTS.PLAY_KIOSK_ANIMATIONS,
+ startDate: then,
+ endDate: now,
+ });
+ expect(response.loop).toEqual(true);
+ expect(response.speed).toEqual(6);
+ expect(response.startDate).toEqual(then);
+ expect(response.endDate).toEqual(now);
+ expect(response.isPlaying).toEqual(true);
+});
+
+test('OPEN_ANIMATION action sets gifActive to false [animation-reducer-open-gif-false]', () => {
+ const updatedState = update(defaultState, { gifActive: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.OPEN_ANIMATION,
+ });
+ expect(response.gifActive).toEqual(false);
+});
+
+test('PLAY_ANIMATION action sets gifActive to false [animation-reducer-play-gif-false]', () => {
+ const updatedState = update(defaultState, { gifActive: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.PLAY_ANIMATION,
+ });
+ expect(response.gifActive).toEqual(false);
+});
+
+test('UPDATE_START_AND_END_DATE action sets isPlaying to false [animation-reducer-start-end-date-stops-play]', () => {
+ const updatedState = update(defaultState, { isPlaying: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.UPDATE_START_AND_END_DATE,
+ startDate: then,
+ endDate: now,
+ });
+ expect(response.isPlaying).toEqual(false);
+});
+
+test('UPDATE_START_DATE action sets isPlaying to false [animation-reducer-start-date-stops-play]', () => {
+ const updatedState = update(defaultState, { isPlaying: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.UPDATE_START_DATE,
+ value: then,
+ });
+ expect(response.isPlaying).toEqual(false);
+});
+
+test('UPDATE_END_DATE action sets isPlaying to false [animation-reducer-end-date-stops-play]', () => {
+ const updatedState = update(defaultState, { isPlaying: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.UPDATE_END_DATE,
+ value: now,
+ });
+ expect(response.isPlaying).toEqual(false);
+});
+
+test('TOGGLE_GIF action sets isPlaying to false [animation-reducer-gif-stops-play]', () => {
+ const updatedState = update(defaultState, { isPlaying: { $set: true } });
+ const response = animationReducer(updatedState, {
+ type: CONSTANTS.TOGGLE_GIF,
+ });
+ expect(response.isPlaying).toEqual(false);
+});
+
+test('default action returns unchanged state [animation-reducer-default]', () => {
+ const response = animationReducer(defaultState, { type: 'UNKNOWN_ACTION' });
+ expect(response).toEqual(defaultState);
+});
+
+test('getInitialState returns startDate 7 days before initialDate and endDate as initialDate [animation-reducer-get-initial-state]', () => {
+ const config = { initialDate: now };
+ const state = getInitialState(config);
+ expect(state.endDate).toEqual(now);
+ expect(state.startDate).toEqual(util.dateAdd(now, 'day', -7));
+});
diff --git a/web/js/modules/animation/selectors.test.js b/web/js/modules/animation/selectors.test.js
index c4e1cdccf..365f4c653 100644
--- a/web/js/modules/animation/selectors.test.js
+++ b/web/js/modules/animation/selectors.test.js
@@ -1,3 +1,289 @@
-test('selectors module test', () => {
+import getImageArray from './selectors';
+import util from '../../util/util';
+import { imageUtilGetCoordsFromPixelValues, getDownloadUrl } from '../image-download/util';
+import { subdailyLayersActive, getLayers } from '../layers/selectors';
+import { formatDisplayDate, getNextImageryDelta } from '../date/util';
+jest.mock('../../util/util', () => ({
+ format: jest.fn((url) => url),
+ dateAdd: jest.fn((date, increment, delta) => {
+ const next = new Date(date);
+ next.setDate(next.getDate() + 1);
+ return next;
+ }),
+}));
+
+jest.mock('../image-download/util', () => ({
+ imageUtilGetCoordsFromPixelValues: jest.fn(() => [[0, 0], [1, 1]]),
+ getDownloadUrl: jest.fn(() => 'http://example.com/image'),
+}));
+
+jest.mock('../layers/selectors', () => ({
+ subdailyLayersActive: jest.fn(() => false),
+ getLayers: jest.fn(() => []),
+}));
+
+jest.mock('../date/util', () => ({
+ formatDisplayDate: jest.fn((date) => date.toISOString()),
+ getNextImageryDelta: jest.fn(() => 1),
+}));
+
+jest.mock('../date/constants', () => ({
+ TIME_SCALE_FROM_NUMBER: {
+ 1: 'day',
+ 2: 'month',
+ },
+}));
+
+const buildState = (overrides = {}) => ({
+ animation: { speed: 10 },
+ proj: 'geographic',
+ map: { ui: { selected: {} } },
+ date: {
+ customInterval: 1,
+ interval: 1,
+ customDelta: null,
+ delta: 1,
+ customSelected: false,
+ autoSelected: false,
+ ...overrides.date,
+ },
+ locationSearch: { coordinates: [0, 0] },
+ layers: { active: { layers: [] } },
+ ...overrides,
+});
+
+const buildOptions = (overrides = {}) => ({
+ boundaries: {},
+ showDates: true,
+ startDate: '2023-01-01',
+ endDate: '2023-01-03',
+ url: 'http://example.com',
+ ...overrides,
+});
+
+const dimensions = { width: 800, height: 600 };
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ util.dateAdd.mockImplementation((date) => {
+ const next = new Date(date);
+ next.setDate(next.getDate() + 1);
+ return next;
+ });
+});
+
+describe('getImageArray', () => {
+ test('returns an array of image objects for a date range', () => {
+ const result = getImageArray(buildOptions(), dimensions, buildState());
+ expect(Array.isArray(result)).toBe(true);
+ expect(result.length).toBe(3);
+ });
+
+ test('each item has src, text, and delay properties', () => {
+ const result = getImageArray(buildOptions(), dimensions, buildState());
+ result.forEach((item) => {
+ expect(item).toHaveProperty('src');
+ expect(item).toHaveProperty('text');
+ expect(item).toHaveProperty('delay');
+ });
+ });
+
+ test('delay is calculated from animation speed', () => {
+ const result = getImageArray(buildOptions(), dimensions, buildState());
+ expect(result[0].delay).toBe(100);
+ });
+
+ test('text is set to strDate when showDates is true', () => {
+ const result = getImageArray(buildOptions({ showDates: true }), dimensions, buildState());
+ expect(result[0].text).not.toBe('');
+ });
+
+ test('text is empty string when showDates is false', () => {
+ const result = getImageArray(buildOptions({ showDates: false }), dimensions, buildState());
+ result.forEach((item) => {
+ expect(item.text).toBe('');
+ });
+ });
+
+ test('returns empty array when startDate equals endDate', () => {
+ const result = getImageArray(
+ buildOptions({ startDate: '2023-01-01', endDate: '2023-01-01' }),
+ dimensions,
+ buildState(),
+ );
+ expect(result.length).toBe(1);
+ });
+
+ test('returns false when frame count exceeds 40', () => {
+ util.dateAdd.mockImplementation((date) => {
+ const next = new Date(date);
+ next.setMinutes(next.getMinutes() + 1);
+ return next;
+ });
+ const result = getImageArray(
+ buildOptions({ startDate: '2023-01-01T00:00:00Z', endDate: '2023-01-03T00:00:00Z' }),
+ dimensions,
+ buildState(),
+ );
+ expect(result).toBe(false);
+ });
+
+ test('uses customDelta when customSelected is true and customDelta is set', () => {
+ const state = buildState({
+ date: {
+ customInterval: 1,
+ interval: 1,
+ customDelta: 5,
+ delta: 1,
+ customSelected: true,
+ autoSelected: false,
+ },
+ });
+ const result = getImageArray(buildOptions(), dimensions, state);
+ expect(util.dateAdd).toHaveBeenCalledWith(expect.any(Date), 'day', 5);
+ expect(Array.isArray(result)).toBe(true);
+ });
+
+ test('uses delta when customSelected is false', () => {
+ const state = buildState({
+ date: {
+ customInterval: 1,
+ interval: 1,
+ customDelta: null,
+ delta: 2,
+ customSelected: false,
+ autoSelected: false,
+ },
+ });
+ getImageArray(buildOptions(), dimensions, state);
+ expect(util.dateAdd).toHaveBeenCalledWith(expect.any(Date), 'day', 2);
+ });
+
+ test('uses delta when customSelected is true but customDelta is falsy', () => {
+ const state = buildState({
+ date: {
+ customInterval: 1,
+ interval: 1,
+ customDelta: null,
+ delta: 3,
+ customSelected: true,
+ autoSelected: false,
+ },
+ });
+ getImageArray(buildOptions(), dimensions, state);
+ expect(util.dateAdd).toHaveBeenCalledWith(expect.any(Date), 'day', 3);
+ });
+
+ test('uses getNextImageryDelta when autoSelected is true', () => {
+ const state = buildState({
+ date: {
+ customInterval: 1,
+ interval: 1,
+ customDelta: null,
+ delta: 1,
+ customSelected: false,
+ autoSelected: true,
+ },
+ });
+ getImageArray(buildOptions(), dimensions, state);
+ expect(getNextImageryDelta).toHaveBeenCalled();
+ expect(util.dateAdd).toHaveBeenCalledWith(expect.any(Date), 'day', 1);
+ });
+
+ test('uses customInterval for increment when customSelected is true', () => {
+ const state = buildState({
+ date: {
+ customInterval: 2,
+ interval: 1,
+ customDelta: 1,
+ delta: 1,
+ customSelected: true,
+ autoSelected: false,
+ },
+ });
+ getImageArray(buildOptions(), dimensions, state);
+ expect(util.dateAdd).toHaveBeenCalledWith(expect.any(Date), 'month', expect.any(Number));
+ });
+
+ test('calls subdailyLayersActive with state', () => {
+ getImageArray(buildOptions(), dimensions, buildState());
+ expect(subdailyLayersActive).toHaveBeenCalledWith(buildState());
+ });
+
+ test('calls imageUtilGetCoordsFromPixelValues with boundaries and map', () => {
+ const state = buildState();
+ getImageArray(buildOptions(), dimensions, state);
+ expect(imageUtilGetCoordsFromPixelValues).toHaveBeenCalledWith({}, state.map.ui.selected);
+ });
+
+ test('calls getDownloadUrl with expected arguments', () => {
+ const state = buildState();
+ const options = buildOptions();
+ getImageArray(options, dimensions, state);
+ expect(getDownloadUrl).toHaveBeenCalledWith(
+ options.url,
+ state.proj,
+ expect.any(Array),
+ [[0, 0], [1, 1]],
+ dimensions,
+ expect.any(Date),
+ false,
+ false,
+ state.locationSearch.coordinates,
+ );
+ });
+
+ test('calls formatDisplayDate for each frame', () => {
+ getImageArray(buildOptions(), dimensions, buildState());
+ expect(formatDisplayDate).toHaveBeenCalledTimes(3);
+ });
+
+ test('calls getLayers for each frame', () => {
+ getImageArray(buildOptions(), dimensions, buildState());
+ expect(getLayers).toHaveBeenCalledTimes(3);
+ });
+
+ test('getLayers called with renderable and reverse options', () => {
+ const state = buildState();
+ getImageArray(buildOptions(), dimensions, state);
+ expect(getLayers).toHaveBeenCalledWith(state, expect.objectContaining({
+ reverse: true,
+ renderable: true,
+ }));
+ });
+
+ test('src is set from util.format return value', () => {
+ util.format.mockReturnValue('http://mocked-src.com/img');
+ const result = getImageArray(buildOptions(), dimensions, buildState());
+ result.forEach((item) => {
+ expect(item.src).toBe('http://mocked-src.com/img');
+ });
+ });
+
+ test('returns empty array when endDate is before startDate', () => {
+ const result = getImageArray(
+ buildOptions({ startDate: '2023-01-05', endDate: '2023-01-01' }),
+ dimensions,
+ buildState(),
+ );
+ expect(result).toEqual([]);
+ });
+
+ test('filters out layers past their endDate in getProducts via getLayers', () => {
+ getLayers.mockReturnValue([
+ { visible: true, startDate: '2022-01-01', endDate: '2023-01-02' },
+ { visible: true, startDate: '2022-01-01', endDate: '2024-01-01' },
+ ]);
+ const result = getImageArray(buildOptions(), dimensions, buildState());
+ expect(Array.isArray(result)).toBe(true);
+ });
+
+ test('includes layer with no startDate in getProducts', () => {
+ getLayers.mockReturnValue([
+ { visible: false },
+ ]);
+ const result = getImageArray(buildOptions(), dimensions, buildState());
+ expect(Array.isArray(result)).toBe(true);
+ });
});
diff --git a/web/js/modules/animation/util.test.js b/web/js/modules/animation/util.test.js
index 473541bb8..1dfbbeab5 100644
--- a/web/js/modules/animation/util.test.js
+++ b/web/js/modules/animation/util.test.js
@@ -1,9 +1,13 @@
import {
mapLocationToAnimationState,
snapToIntervalDelta,
+ getStampProps,
+ getNumberOfSteps,
} from './util';
import { defaultState } from './reducers';
+// mapLocationToAnimationState tests
+
test('mapLocationToAnimationState updates state to have isPlaying bool true if playanim and ab keys are present [animation-location-state]', () => {
const stateFromLocation = { animation: defaultState };
const PERMALINK_STATE = { ab: true, playanim: true };
@@ -35,6 +39,69 @@ test('mapLocationToAnimationState closes animation if ab is not present [animati
expect(response.animation.isPlaying).toBeFalsy();
});
+test('mapLocationToAnimationState sets isActive true when ab is "on" [animation-ab-on-string]', () => {
+ const stateFromLocation = { animation: defaultState };
+ const PERMALINK_STATE = { ab: 'on' };
+ const response = mapLocationToAnimationState(PERMALINK_STATE, stateFromLocation);
+ expect(response.animation.isActive).toBeTruthy();
+ expect(response.animation.isPlaying).toBeFalsy();
+});
+
+test('mapLocationToAnimationState does not wipe dates when ae param is present [animation-ae-param]', () => {
+ const startDate = new Date('2020-01-01T00:00:00Z');
+ const endDate = new Date('2020-01-02T00:00:00Z');
+ const stateFromLocation = {
+ animation: {
+ ...defaultState,
+ startDate,
+ endDate,
+ },
+ };
+ const PERMALINK_STATE = { ae: '2020-01-02' };
+ const response = mapLocationToAnimationState(PERMALINK_STATE, stateFromLocation);
+ expect(response.animation.endDate).toBeUndefined();
+ expect(response.animation.startDate).toBeUndefined();
+});
+
+test('mapLocationToAnimationState preserves dates when ab is active and ae/as params are present [animation-dates-preserved]', () => {
+ const startDate = new Date('2020-01-01T00:00:00Z');
+ const endDate = new Date('2020-01-02T00:00:00Z');
+ const stateFromLocation = {
+ animation: {
+ ...defaultState,
+ startDate,
+ endDate,
+ },
+ };
+ const PERMALINK_STATE = { ab: true, as: '2020-01-01', ae: '2020-01-02' };
+ const response = mapLocationToAnimationState(PERMALINK_STATE, stateFromLocation);
+ expect(response.animation.isActive).toBeTruthy();
+});
+
+test('mapLocationToAnimationState does not set isPlaying if ab is absent but playanim is present [animation-playanim-no-ab]', () => {
+ const stateFromLocation = { animation: defaultState };
+ const PERMALINK_STATE = { playanim: true };
+ const response = mapLocationToAnimationState(PERMALINK_STATE, stateFromLocation);
+ expect(response.animation.isPlaying).toBeFalsy();
+ expect(response.animation.isActive).toBeFalsy();
+});
+
+test('mapLocationToAnimationState wipes start and end dates when ab is absent and no ae param [animation-wipe-dates]', () => {
+ const stateFromLocation = {
+ animation: {
+ ...defaultState,
+ startDate: new Date('2020-01-01T00:00:00Z'),
+ endDate: new Date('2020-01-02T00:00:00Z'),
+ },
+ };
+ const PERMALINK_STATE = {};
+ const response = mapLocationToAnimationState(PERMALINK_STATE, stateFromLocation);
+ expect(response.animation.startDate).toBeUndefined();
+ expect(response.animation.endDate).toBeUndefined();
+});
+
+// snapToIntervalDelta tests
+
test('snapToIntervalDelta snaps at the year interval [animation-year-interval]', () => {
const currentDate = new Date('2010-06-23');
const startDate = new Date(' 2000-04-15');
@@ -115,3 +182,88 @@ test('snapToIntervalDelta snaps to startDate if currentDate is before startDate
const snappedDate = snapToIntervalDelta(currentDate, startDate, endDate, 'minute', 1);
expect(snappedDate.valueOf()).toBe(expected.valueOf());
});
+
+test('snapToIntervalDelta returns startDate when currDate exactly equals startDate [animation-snap-exact-start]', () => {
+ const currentDate = new Date('2018-04-19 08:15:30Z');
+ const startDate = new Date(' 2018-04-19 08:15:30Z');
+ const endDate = new Date(' 2018-04-19 09:00:00Z');
+ const snappedDate = snapToIntervalDelta(currentDate, startDate, endDate, 'minute', 1);
+ expect(snappedDate.valueOf()).toBe(startDate.valueOf());
+});
+
+// getStampProps tests
+
+test('getStampProps returns correct stamp height and dateStamp when dimensions.w < breakPoint and stampHeight < 60 [stamp-small-width-small-height]', () => {
+ const result = getStampProps(5, 300, 100, { w: 200, h: 200 }, 100, 500);
+ expect(result).toHaveProperty('stampHeight');
+ expect(result).toHaveProperty('dateStamp');
+ expect(result.stampHeight).toBeLessThan(60);
+ expect(result.dateStamp.align).toBe('left');
+ expect(result.dateStamp.x).toBe(1);
+});
+
+test('getStampProps caps stampHeight at 60 when computed value exceeds 60 and dimensions.w < breakPoint [stamp-small-width-capped-height]', () => {
+ const result = getStampProps(1, 300, 100, { w: 200, h: 500 }, 400, 600);
+ expect(result.stampHeight).toBe(60);
+});
+
+test('getStampProps sets fontSize > 0 when dimensions.h > stampHeight * 1.5 and dimensions.w < breakPoint [stamp-small-width-fontsize]', () => {
+ const result = getStampProps(5, 300, 100, { w: 200, h: 500 }, 100, 500);
+ expect(result.dateStamp.fontSize).toBeGreaterThan(0);
+});
+
+test('getStampProps sets fontSize to 0 when dimensions.h <= stampHeight * 1.5 and dimensions.w < breakPoint [stamp-small-width-no-fontsize]', () => {
+ const result = getStampProps(5, 300, 100, { w: 200, h: 10 }, 100, 500);
+ expect(result.dateStamp.fontSize).toBe(0);
+});
+
+test('getStampProps returns correct props when dimensions.w >= breakPoint and stampHeightByImageWidth > 60 [stamp-large-width-capped]', () => {
+ const result = getStampProps(1, 300, 100, { w: 400, h: 800 }, 1000, 1000);
+ expect(result.stampHeight).toBe(60);
+ expect(result.dateStamp.align).toBe('left');
+});
+
+test('getStampProps returns stampHeight of 20 when stampHeightByImageWidth < 20 and dimensions.w >= breakPoint [stamp-large-width-min-height]', () => {
+ const result = getStampProps(200, 300, 100, { w: 400, h: 800 }, 1000, 1000);
+ expect(result.stampHeight).toBe(20);
+});
+
+test('getStampProps sets fontSize > 0 when dimensions.h > stampHeight * 1.5 and dimensions.w >= breakPoint [stamp-large-width-fontsize]', () => {
+ const result = getStampProps(5, 300, 100, { w: 400, h: 800 }, 1000, 1000);
+ expect(result.dateStamp.fontSize).toBeGreaterThan(0);
+});
+
+test('getStampProps sets fontSize to 0 when dimensions.h <= stampHeight * 1.5 and dimensions.w >= breakPoint [stamp-large-width-no-fontsize]', () => {
+ const result = getStampProps(5, 300, 100, { w: 400, h: 10 }, 1000, 1000);
+ expect(result.dateStamp.fontSize).toBe(0);
+});
+
+// getNumberOfSteps tests
+
+test('getNumberOfSteps returns 1 when nextDate is after end [animation-steps-single-frame]', () => {
+ const start = new Date('2018-01-01');
+ const end = new Date('2018-01-01');
+ const steps = getNumberOfSteps(start, end, 'day', null, false, [], 1);
+ expect(steps).toBe(1);
+});
+
+test('getNumberOfSteps returns correct count for day interval [animation-steps-day]', () => {
+ const start = new Date('2018-01-01');
+ const end = new Date('2018-01-05');
+ const steps = getNumberOfSteps(start, end, 'day', null, false, [], 1);
+ expect(steps).toBe(5);
+});
+
+test('getNumberOfSteps respects maxToCheck limit [animation-steps-max]', () => {
+ const start = new Date('2018-01-01');
+ const end = new Date('2018-12-31');
+ const steps = getNumberOfSteps(start, end, 'day', 10, false, [], 1);
+ expect(steps).toBe(10);
+});
+
+test('getNumberOfSteps returns correct count for month interval [animation-steps-month]', () => {
+ const start = new Date('2018-01-01');
+ const end = new Date('2018-06-01');
+ const steps = getNumberOfSteps(start, end, 'month', null, false, [], 1);
+ expect(steps).toBe(6);
+});
diff --git a/web/js/modules/charting/reducers.test.js b/web/js/modules/charting/reducers.test.js
index 04cce6a78..066c93f8d 100644
--- a/web/js/modules/charting/reducers.test.js
+++ b/web/js/modules/charting/reducers.test.js
@@ -1,3 +1,176 @@
-test('reducers module test', () => {
+import {
+ chartingReducer,
+ initialChartingState,
+} from './reducers';
+import {
+ TOGGLE_ON_OFF,
+ TOGGLE_AOI_ON_OFF,
+ UPDATE_AOI_COORDINATES,
+ TOGGLE_AOI_SELECTED_ON_OFF,
+ TOGGLE_REQUEST_IN_PROGRESS,
+ TOGGLE_MODAL_OPEN,
+ UPDATE_CHARTING_DATE_SELECTION,
+ UPDATE_START_DATE,
+ UPDATE_END_DATE,
+ UPDATE_ACTIVE_CHART,
+} from './constants';
+describe('initialChartingState', () => {
+ it('has the correct default shape', () => {
+ expect(initialChartingState).toEqual({
+ active: false,
+ activeLayer: undefined,
+ aoiActive: true,
+ aoiSelected: false,
+ aoiCoordinates: [],
+ chartRequestInProgress: false,
+ timeSpanSelection: 'range',
+ timeSpanStartDate: undefined,
+ timeSpanEndDate: undefined,
+ fromButton: false,
+ isChartOpen: false,
+ });
+ });
+});
+
+describe('chartingReducer', () => {
+ it('returns the default state when called with no arguments', () => {
+ const state = chartingReducer(undefined, { type: '@@INIT' });
+ expect(state).toEqual(initialChartingState);
+ });
+
+ it('returns the same state for an unknown action', () => {
+ const state = chartingReducer(initialChartingState, { type: 'UNKNOWN' });
+ expect(state).toBe(initialChartingState);
+ });
+
+ describe('TOGGLE_ON_OFF', () => {
+ it('sets active to true and fromButton to true when currently inactive', () => {
+ const state = chartingReducer(initialChartingState, { type: TOGGLE_ON_OFF });
+ expect(state.active).toBe(true);
+ expect(state.fromButton).toBe(true);
+ });
+
+ it('resets to initial-like state when currently active', () => {
+ const activeState = { ...initialChartingState, active: true };
+ const state = chartingReducer(activeState, { type: TOGGLE_ON_OFF });
+ expect(state.active).toBe(false);
+ expect(state.activeLayer).toBeUndefined();
+ expect(state.aoiActive).toBe(true);
+ expect(state.aoiCoordinates).toBeNull();
+ expect(state.aoiSelected).toBe(false);
+ expect(state.chartRequestInProgress).toBe(false);
+ expect(state.timeSpanEndDate).toBeUndefined();
+ expect(state.timeSpanSelection).toBe('range');
+ expect(state.timeSpanStartDate).toBeUndefined();
+ expect(state.fromButton).toBe(false);
+ expect(state.isChartOpen).toBe(false);
+ });
+ });
+
+ describe('TOGGLE_AOI_ON_OFF', () => {
+ it('toggles aoiActive from true to false', () => {
+ const state = chartingReducer(initialChartingState, { type: TOGGLE_AOI_ON_OFF });
+ expect(state.aoiActive).toBe(false);
+ });
+
+ it('toggles aoiActive from false to true', () => {
+ const inactiveAoi = { ...initialChartingState, aoiActive: false };
+ const state = chartingReducer(inactiveAoi, { type: TOGGLE_AOI_ON_OFF });
+ expect(state.aoiActive).toBe(true);
+ });
+ });
+
+ describe('TOGGLE_REQUEST_IN_PROGRESS', () => {
+ it('sets chartRequestInProgress to true', () => {
+ const state = chartingReducer(initialChartingState, { type: TOGGLE_REQUEST_IN_PROGRESS, status: true });
+ expect(state.chartRequestInProgress).toBe(true);
+ });
+
+ it('sets chartRequestInProgress to false', () => {
+ const inProgress = { ...initialChartingState, chartRequestInProgress: true };
+ const state = chartingReducer(inProgress, { type: TOGGLE_REQUEST_IN_PROGRESS, status: false });
+ expect(state.chartRequestInProgress).toBe(false);
+ });
+ });
+
+ describe('TOGGLE_MODAL_OPEN', () => {
+ it('sets isChartOpen to true', () => {
+ const state = chartingReducer(initialChartingState, { type: TOGGLE_MODAL_OPEN, status: true });
+ expect(state.isChartOpen).toBe(true);
+ });
+
+ it('sets isChartOpen to false', () => {
+ const openState = { ...initialChartingState, isChartOpen: true };
+ const state = chartingReducer(openState, { type: TOGGLE_MODAL_OPEN, status: false });
+ expect(state.isChartOpen).toBe(false);
+ });
+ });
+
+ describe('UPDATE_AOI_COORDINATES', () => {
+ it('updates aoiCoordinates with the provided extent', () => {
+ const extent = [10, 20, 30, 40];
+ const state = chartingReducer(initialChartingState, { type: UPDATE_AOI_COORDINATES, extent });
+ expect(state.aoiCoordinates).toEqual(extent);
+ });
+ });
+
+ describe('TOGGLE_AOI_SELECTED_ON_OFF', () => {
+ it('sets aoiSelected to the explicit action value when action.action is not null', () => {
+ const state = chartingReducer(initialChartingState, { type: TOGGLE_AOI_SELECTED_ON_OFF, action: true });
+ expect(state.aoiSelected).toBe(true);
+ });
+
+ it('sets aoiSelected to false via explicit action value', () => {
+ const selectedState = { ...initialChartingState, aoiSelected: true };
+ const state = chartingReducer(selectedState, { type: TOGGLE_AOI_SELECTED_ON_OFF, action: false });
+ expect(state.aoiSelected).toBe(false);
+ });
+
+ it('toggles aoiSelected when action.action is null', () => {
+ const state = chartingReducer(initialChartingState, { type: TOGGLE_AOI_SELECTED_ON_OFF, action: null });
+ expect(state.aoiSelected).toBe(true);
+ });
+
+ it('toggles aoiSelected from true to false when action.action is null', () => {
+ const selectedState = { ...initialChartingState, aoiSelected: true };
+ const state = chartingReducer(selectedState, { type: TOGGLE_AOI_SELECTED_ON_OFF, action: null });
+ expect(state.aoiSelected).toBe(false);
+ });
+
+ it('toggles aoiSelected when action.action is undefined', () => {
+ const state = chartingReducer(initialChartingState, { type: TOGGLE_AOI_SELECTED_ON_OFF });
+ expect(state.aoiSelected).toBe(true);
+ });
+ });
+
+ describe('UPDATE_CHARTING_DATE_SELECTION', () => {
+ it('updates timeSpanSelection with the buttonClicked value', () => {
+ const state = chartingReducer(initialChartingState, { type: UPDATE_CHARTING_DATE_SELECTION, buttonClicked: 'single' });
+ expect(state.timeSpanSelection).toBe('single');
+ });
+ });
+
+ describe('UPDATE_START_DATE', () => {
+ it('updates timeSpanStartDate with the provided date', () => {
+ const date = '2024-01-01';
+ const state = chartingReducer(initialChartingState, { type: UPDATE_START_DATE, date });
+ expect(state.timeSpanStartDate).toBe(date);
+ });
+ });
+
+ describe('UPDATE_END_DATE', () => {
+ it('updates timeSpanEndDate with the provided date', () => {
+ const date = '2024-12-31';
+ const state = chartingReducer(initialChartingState, { type: UPDATE_END_DATE, date });
+ expect(state.timeSpanEndDate).toBe(date);
+ });
+ });
+
+ describe('UPDATE_ACTIVE_CHART', () => {
+ it('updates activeLayer with the provided layerId', () => {
+ const state = chartingReducer(initialChartingState, { type: UPDATE_ACTIVE_CHART, layerId: 'layer-123' });
+ expect(state.activeLayer).toBe('layer-123');
+ });
+ });
});
diff --git a/web/js/modules/charting/util.test.js b/web/js/modules/charting/util.test.js
index 4072f4f95..176f59bef 100644
--- a/web/js/modules/charting/util.test.js
+++ b/web/js/modules/charting/util.test.js
@@ -1,3 +1,140 @@
-test('util module test', () => {
+import { mapLocationToChartingState, getFormattedMonthAbbrevDates } from './util';
+import { initialChartingState } from './reducers';
+import { formatDisplayDate } from '../date/util';
+jest.mock('./reducers', () => ({
+ initialChartingState: {
+ active: false,
+ activeLayer: undefined,
+ aoiActive: true,
+ aoiSelected: false,
+ aoiCoordinates: [],
+ chartRequestInProgress: false,
+ timeSpanSelection: 'range',
+ timeSpanStartDate: undefined,
+ timeSpanEndDate: undefined,
+ fromButton: false,
+ isChartOpen: false,
+ },
+}));
+
+jest.mock('../date/util', () => ({
+ formatDisplayDate: jest.fn((date) => `formatted-${date}`),
+}));
+
+const baseState = {
+ charting: {
+ active: false,
+ aoiActive: false,
+ aoiSelected: false,
+ timeSpanSelection: 'range',
+ },
+};
+
+describe('mapLocationToChartingState', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('resets charting to initialChartingState when cha is not "true"', () => {
+ const result = mapLocationToChartingState({}, baseState);
+ expect(result.charting).toEqual(initialChartingState);
+ });
+
+ it('resets charting to initialChartingState when cha is a non-"true" string', () => {
+ const result = mapLocationToChartingState({ cha: 'false' }, baseState);
+ expect(result.charting).toEqual(initialChartingState);
+ });
+
+ it('sets charting.active to true when cha is "true"', () => {
+ const result = mapLocationToChartingState({ cha: 'true' }, baseState);
+ expect(result.charting.active).toBe(true);
+ });
+
+ it('sets timeSpanSelection to "date" when cha is "true" and cht2 is absent', () => {
+ const result = mapLocationToChartingState({ cha: 'true' }, baseState);
+ expect(result.charting.timeSpanSelection).toBe('date');
+ });
+
+ it('does not override timeSpanSelection when cht2 is present', () => {
+ const result = mapLocationToChartingState({ cha: 'true', cht2: '2024-12-31' }, baseState);
+ expect(result.charting.timeSpanSelection).not.toBe('date');
+ });
+
+ it('sets aoiActive and aoiSelected to true when cha is "true" and chc is present', () => {
+ const result = mapLocationToChartingState({ cha: 'true', chc: 'someCoords' }, baseState);
+ expect(result.charting.aoiActive).toBe(true);
+ expect(result.charting.aoiSelected).toBe(true);
+ });
+
+ it('does not set aoiSelected when chc is absent', () => {
+ const result = mapLocationToChartingState({ cha: 'true' }, baseState);
+ expect(result.charting.aoiSelected).toBe(false);
+ });
+
+ it('sets active, aoiActive, aoiSelected, and timeSpanSelection to "date" when cha is "true" and chc present and cht2 absent', () => {
+ const result = mapLocationToChartingState({ cha: 'true', chc: 'coords' }, baseState);
+ expect(result.charting.active).toBe(true);
+ expect(result.charting.aoiActive).toBe(true);
+ expect(result.charting.aoiSelected).toBe(true);
+ expect(result.charting.timeSpanSelection).toBe('date');
+ });
+
+ it('sets active and aoiActive/aoiSelected but preserves timeSpanSelection when cha "true", chc present, cht2 present', () => {
+ const result = mapLocationToChartingState({ cha: 'true', chc: 'coords', cht2: '2024-01-01' }, baseState);
+ expect(result.charting.active).toBe(true);
+ expect(result.charting.aoiActive).toBe(true);
+ expect(result.charting.aoiSelected).toBe(true);
+ expect(result.charting.timeSpanSelection).toBe('range');
+ });
+
+ it('returns the original state object structure with charting nested', () => {
+ const result = mapLocationToChartingState({ cha: 'true' }, baseState);
+ expect(result).toHaveProperty('charting');
+ });
+
+ it('does not mutate the original stateFromLocationObj', () => {
+ const original = { ...baseState, charting: { ...baseState.charting } };
+ mapLocationToChartingState({ cha: 'true', chc: 'x', cht2: 'y' }, baseState);
+ expect(baseState).toEqual(original);
+ });
+});
+
+describe('getFormattedMonthAbbrevDates', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('returns formatted dateA and dateB', () => {
+ const result = getFormattedMonthAbbrevDates('2024-01-01', '2024-06-30');
+ expect(result).toEqual({
+ dateA: 'formatted-2024-01-01',
+ dateB: 'formatted-2024-06-30',
+ });
+ });
+
+ it('calls formatDisplayDate with the selected date', () => {
+ getFormattedMonthAbbrevDates('2024-01-01', '2024-06-30');
+ expect(formatDisplayDate).toHaveBeenCalledWith('2024-01-01');
+ });
+
+ it('calls formatDisplayDate with the selectedB date', () => {
+ getFormattedMonthAbbrevDates('2024-01-01', '2024-06-30');
+ expect(formatDisplayDate).toHaveBeenCalledWith('2024-06-30');
+ });
+
+ it('calls formatDisplayDate exactly twice', () => {
+ getFormattedMonthAbbrevDates('2024-01-01', '2024-06-30');
+ expect(formatDisplayDate).toHaveBeenCalledTimes(2);
+ });
+
+ it('handles undefined arguments without throwing', () => {
+ expect(() => getFormattedMonthAbbrevDates(undefined, undefined)).not.toThrow();
+ });
+
+ it('returns dateA as formatted-undefined when selected is undefined', () => {
+ const result = getFormattedMonthAbbrevDates(undefined, undefined);
+ expect(result.dateA).toBe('formatted-undefined');
+ expect(result.dateB).toBe('formatted-undefined');
+ });
});
diff --git a/web/js/modules/compare/actions.test.js b/web/js/modules/compare/actions.test.js
index 792e54a99..69b393ae5 100644
--- a/web/js/modules/compare/actions.test.js
+++ b/web/js/modules/compare/actions.test.js
@@ -7,7 +7,7 @@ import {
setValue,
changeMode,
} from './actions';
-import { INIT_SECOND_LAYER_GROUP } from '../layers/constants';
+import { INIT_SECOND_LAYER_GROUP, SYNC_SECOND_LAYER_GROUP } from '../layers/constants';
import fixtures from '../../fixtures';
import { INIT_SECOND_DATE, CLEAR_PRELOAD } from '../date/constants';
@@ -27,6 +27,62 @@ test('toggleCompareOnOff dispatches two actions [compare-action-toggle-return-ac
expect(thirdResponse.type).toEqual(CONSTANTS.TOGGLE_ON_OFF);
});
+test('toggleCompareOnOff with active=true exits compare mode and snapshots layer IDs [compare-action-toggle-exit]', () => {
+ const mockStore = configureMockStore(middlewares);
+ const activeState = {
+ ...state,
+ compare: {
+ ...state.compare,
+ active: true,
+ bStatesInitiated: true,
+ },
+ };
+ const store = mockStore(activeState);
+ store.dispatch(toggleCompareOnOff());
+ const actions = store.getActions();
+ const toggleAction = actions.find((a) => a.type === CONSTANTS.TOGGLE_ON_OFF);
+
+ expect(actions.length).toBe(1);
+ expect(toggleAction).toBeDefined();
+ expect(toggleAction).toHaveProperty('lastExitALayerIds');
+ expect(Array.isArray(toggleAction.lastExitALayerIds)).toBe(true);
+});
+
+test('toggleCompareOnOff with bStatesInitiated=true dispatches syncSecondLayerGroup [compare-action-toggle-reentry]', () => {
+ const mockStore = configureMockStore(middlewares);
+ const lastExitALayerIds = ['layer1', 'layer2'];
+ const reentryState = {
+ ...state,
+ compare: {
+ ...state.compare,
+ active: false,
+ bStatesInitiated: true,
+ lastExitALayerIds,
+ },
+ };
+ const store = mockStore(reentryState);
+ store.dispatch(toggleCompareOnOff());
+ const actions = store.getActions();
+ const syncAction = actions.find((a) => a.type === SYNC_SECOND_LAYER_GROUP);
+ const toggleAction = actions.find((a) => a.type === CONSTANTS.TOGGLE_ON_OFF);
+
+ expect(syncAction).toBeDefined();
+ expect(toggleAction).toBeDefined();
+ expect(actions.find((a) => a.type === INIT_SECOND_LAYER_GROUP)).toBeUndefined();
+ expect(actions.find((a) => a.type === INIT_SECOND_DATE)).toBeUndefined();
+});
+
+test('toggleCompareOnOff with active=false and bStatesInitiated=false does not include lastExitALayerIds in TOGGLE_ON_OFF [compare-action-toggle-no-exit-payload]', () => {
+ const mockStore = configureMockStore(middlewares);
+ const store = mockStore(state);
+ store.dispatch(toggleCompareOnOff());
+ const actions = store.getActions();
+ const toggleAction = actions.find((a) => a.type === CONSTANTS.TOGGLE_ON_OFF);
+
+ expect(toggleAction).toBeDefined();
+ expect(toggleAction).not.toHaveProperty('lastExitALayerIds');
+});
+
test(
`toggleActiveCompareState returns ${CONSTANTS.CHANGE_STATE} action type [compare-action-toggle]`,
() => {
@@ -41,6 +97,7 @@ test(
expect(secondResponse).toEqual(expectedSecond);
},
);
+
test(
`setValue returns ${CONSTANTS.CHANGE_VALUE} action type and value [compare-action-set-value]`,
() => {
@@ -52,6 +109,10 @@ test(
},
);
+test('setValue handles zero [compare-action-set-value-zero]', () => {
+ expect(setValue(0)).toEqual({ type: CONSTANTS.CHANGE_VALUE, value: 0 });
+});
+
test(
`changeMode returns ${CONSTANTS.CHANGE_MODE} action type and mode value [compare-action-change-mode]`,
() => {
@@ -62,3 +123,7 @@ test(
expect(changeMode('some-mode')).toEqual(expectedAction);
},
);
+
+test('changeMode handles different mode strings [compare-action-change-mode-opacity]', () => {
+ expect(changeMode('opacity')).toEqual({ type: CONSTANTS.CHANGE_MODE, mode: 'opacity' });
+});
diff --git a/web/js/modules/compare/reducers.test.js b/web/js/modules/compare/reducers.test.js
index 1c1ac7487..b11f680ee 100644
--- a/web/js/modules/compare/reducers.test.js
+++ b/web/js/modules/compare/reducers.test.js
@@ -11,6 +11,13 @@ test('CHANGE_STATE update active state and activeString [compare-reducer-change-
expect(response.isCompareA).toBeFalsy();
});
+test('CHANGE_STATE toggles back to isCompareA=true and activeString=active [compare-reducer-change-state-back]', () => {
+ const stateB = { ...initialCompareState, isCompareA: false, activeString: 'activeB' };
+ const response = compareReducer(stateB, { type: CONSTANTS.CHANGE_STATE });
+ expect(response.isCompareA).toBeTruthy();
+ expect(response.activeString).toEqual('active');
+});
+
test('TOGGLE_ON_OFF toggles compare feature on and off [compare-reducer-toggle]', () => {
const response = compareReducer(initialCompareState, {
type: CONSTANTS.TOGGLE_ON_OFF,
@@ -19,6 +26,30 @@ test('TOGGLE_ON_OFF toggles compare feature on and off [compare-reducer-toggle]'
expect(response.active).toBeTruthy();
});
+test('TOGGLE_ON_OFF sets bStatesInitiated to true [compare-reducer-toggle-bstates]', () => {
+ const response = compareReducer(initialCompareState, { type: CONSTANTS.TOGGLE_ON_OFF });
+ expect(response.bStatesInitiated).toBe(true);
+});
+
+test('TOGGLE_ON_OFF when active=true stores lastExitALayerIds from action [compare-reducer-toggle-exit-layers]', () => {
+ const activeState = { ...initialCompareState, active: true };
+ const layerIds = ['layer1', 'layer2'];
+ const response = compareReducer(activeState, {
+ type: CONSTANTS.TOGGLE_ON_OFF,
+ lastExitALayerIds: layerIds,
+ });
+ expect(response.active).toBe(false);
+ expect(response.lastExitALayerIds).toEqual(layerIds);
+});
+
+test('TOGGLE_ON_OFF when active=false does not set lastExitALayerIds [compare-reducer-toggle-no-exit-layers]', () => {
+ const response = compareReducer(initialCompareState, {
+ type: CONSTANTS.TOGGLE_ON_OFF,
+ lastExitALayerIds: ['layer1'],
+ });
+ expect(response.lastExitALayerIds).toBeUndefined();
+});
+
test('CHANGE_MODE updates mode [compare-reducer-change-mode]', () => {
const response = compareReducer(initialCompareState, {
type: CONSTANTS.CHANGE_MODE,
@@ -27,3 +58,38 @@ test('CHANGE_MODE updates mode [compare-reducer-change-mode]', () => {
expect(initialCompareState.mode).toEqual('swipe');
expect(response.mode).toEqual('new-mode');
});
+
+test('CHANGE_MODE resets value to 50 [compare-reducer-change-mode-resets-value]', () => {
+ const stateWithValue = { ...initialCompareState, value: 75 };
+ const response = compareReducer(stateWithValue, {
+ type: CONSTANTS.CHANGE_MODE,
+ mode: 'opacity',
+ });
+ expect(response.value).toEqual(50);
+});
+
+test('CHANGE_VALUE updates value [compare-reducer-change-value]', () => {
+ const response = compareReducer(initialCompareState, {
+ type: CONSTANTS.CHANGE_VALUE,
+ value: 80,
+ });
+ expect(response.value).toEqual(80);
+});
+
+test('CHANGE_VALUE updates value to 0 [compare-reducer-change-value-zero]', () => {
+ const response = compareReducer(initialCompareState, {
+ type: CONSTANTS.CHANGE_VALUE,
+ value: 0,
+ });
+ expect(response.value).toEqual(0);
+});
+
+test('default case returns existing state unchanged [compare-reducer-default]', () => {
+ const response = compareReducer(initialCompareState, { type: 'UNKNOWN_ACTION' });
+ expect(response).toEqual(initialCompareState);
+});
+
+test('compareReducer uses initialCompareState when no state is provided [compare-reducer-default-state]', () => {
+ const response = compareReducer(undefined, { type: 'UNKNOWN_ACTION' });
+ expect(response).toEqual(initialCompareState);
+});
diff --git a/web/js/modules/compare/selectors.test.js b/web/js/modules/compare/selectors.test.js
new file mode 100644
index 000000000..21bf3e553
--- /dev/null
+++ b/web/js/modules/compare/selectors.test.js
@@ -0,0 +1,93 @@
+import { getCompareDates } from './selectors';
+
+const selectedDate = new Date(Date.UTC(2022, 0, 15));
+const selectedBDate = new Date(Date.UTC(2021, 5, 20));
+
+const baseState = {
+ date: {
+ selected: selectedDate,
+ selectedB: selectedBDate,
+ },
+};
+
+describe('getCompareDates', () => {
+ test('returns an object with dateA and dateB keys [compare-selector-keys]', () => {
+ const result = getCompareDates(baseState);
+ expect(result).toHaveProperty('dateA');
+ expect(result).toHaveProperty('dateB');
+ });
+
+ test('returns string values for dateA and dateB [compare-selector-string-values]', () => {
+ const result = getCompareDates(baseState);
+ expect(typeof result.dateA).toBe('string');
+ expect(typeof result.dateB).toBe('string');
+ });
+
+ test('dateA reflects the selected date [compare-selector-date-a]', () => {
+ const result = getCompareDates(baseState);
+ expect(result.dateA).toBe('2022 JAN 15');
+ });
+
+ test('dateB reflects the selectedB date [compare-selector-date-b]', () => {
+ const result = getCompareDates(baseState);
+ expect(result.dateB).toBe('2021 JUN 20');
+ });
+
+ test('returns updated dateA when selected changes [compare-selector-date-a-updated]', () => {
+ const newState = {
+ date: {
+ selected: new Date(Date.UTC(2020, 2, 10)),
+ selectedB: selectedBDate,
+ },
+ };
+ const result = getCompareDates(newState);
+ expect(result.dateA).toBe('2020 MAR 10');
+ });
+
+ test('returns updated dateB when selectedB changes [compare-selector-date-b-updated]', () => {
+ const newState = {
+ date: {
+ selected: selectedDate,
+ selectedB: new Date(Date.UTC(2019, 11, 25)),
+ },
+ };
+ const result = getCompareDates(newState);
+ expect(result.dateB).toBe('2019 DEC 25');
+ });
+
+ test('memoizes result when state has not changed [compare-selector-memoized]', () => {
+ const result1 = getCompareDates(baseState);
+ const result2 = getCompareDates(baseState);
+ expect(result1).toBe(result2);
+ });
+
+ test('returns new result when state changes [compare-selector-not-memoized-on-change]', () => {
+ const result1 = getCompareDates(baseState);
+ const changedState = {
+ date: {
+ selected: new Date(Date.UTC(2023, 6, 4)),
+ selectedB: selectedBDate,
+ },
+ };
+ const result2 = getCompareDates(changedState);
+ expect(result1).not.toBe(result2);
+ expect(result2.dateA).toBe('2023 JUL 04');
+ });
+
+ test('handles same date for both selected and selectedB [compare-selector-same-dates]', () => {
+ const sameDate = new Date(Date.UTC(2022, 3, 1));
+ const sameState = {
+ date: {
+ selected: sameDate,
+ selectedB: sameDate,
+ },
+ };
+ const result = getCompareDates(sameState);
+ expect(result.dateA).toBe(result.dateB);
+ });
+
+ test('result contains only dateA and dateB keys [compare-selector-shape]', () => {
+ const result = getCompareDates(baseState);
+ expect(Object.keys(result)).toEqual(['dateA', 'dateB']);
+ });
+});
diff --git a/web/js/modules/compare/util.test.js b/web/js/modules/compare/util.test.js
index f2d53e0c5..76b2fbd29 100644
--- a/web/js/modules/compare/util.test.js
+++ b/web/js/modules/compare/util.test.js
@@ -1,14 +1,123 @@
-import { mapLocationToCompareState } from './util';
+import { mapLocationToCompareState, isFromActiveCompareRegion, getFormattedMonthAbbrevDates } from './util';
import { initialCompareState } from './reducers';
const stateFromLocation = { compare: initialCompareState };
const PERMALINK_STATE = { ca: '' };
test('mapLocationToCompareState sets compare as active is ca is defined permalink [compare-permalink]', () => {
- const response = mapLocationToCompareState(
- PERMALINK_STATE,
- stateFromLocation,
- );
+ const response = mapLocationToCompareState(PERMALINK_STATE, stateFromLocation);
expect(stateFromLocation.compare.active).toBeFalsy();
expect(response.compare.active).toBeTruthy();
});
+
+test('mapLocationToCompareState sets bStatesInitiated to true when ca is defined [compare-permalink-bstates]', () => {
+ const response = mapLocationToCompareState(PERMALINK_STATE, stateFromLocation);
+ expect(response.compare.bStatesInitiated).toBe(true);
+});
+
+test('mapLocationToCompareState sets activeString to activeB when ca is "false" [compare-permalink-false]', () => {
+ const response = mapLocationToCompareState({ ca: 'false' }, stateFromLocation);
+ expect(response.compare.activeString).toEqual('activeB');
+});
+
+test('mapLocationToCompareState does not set activeString to activeB when ca is not "false" [compare-permalink-not-false]', () => {
+ const response = mapLocationToCompareState({ ca: 'true' }, stateFromLocation);
+ expect(response.compare.activeString).not.toEqual('activeB');
+});
+
+test('mapLocationToCompareState resets compare to initialCompareState when ca is undefined [compare-permalink-reset]', () => {
+ const modifiedState = {
+ compare: { ...initialCompareState, active: true, bStatesInitiated: true },
+ };
+ const response = mapLocationToCompareState({}, modifiedState);
+ expect(response.compare).toEqual(initialCompareState);
+});
+
+test('isFromActiveCompareRegion returns true when compare is not active [compare-util-inactive]', () => {
+ const result = isFromActiveCompareRegion([100, 100], 'active', 50, { active: false });
+ expect(result).toBe(true);
+});
+
+test('isFromActiveCompareRegion returns true when compare is not provided [compare-util-no-compare]', () => {
+ const result = isFromActiveCompareRegion([100, 100], 'active', 50);
+ expect(result).toBe(true);
+});
+
+test('isFromActiveCompareRegion returns false when mode is not swipe [compare-util-not-swipe]', () => {
+ const result = isFromActiveCompareRegion([100, 100], 'active', 50, {
+ active: true,
+ mode: 'opacity',
+ isCompareA: true,
+ });
+ expect(result).toBe(false);
+});
+
+test('isFromActiveCompareRegion returns false when isCompareA and coords exceed swipeOffset [compare-util-swipe-a-over]', () => {
+ const result = isFromActiveCompareRegion([60, 0], 'active', 50, {
+ active: true,
+ mode: 'swipe',
+ isCompareA: true,
+ });
+ expect(result).toBe(false);
+});
+
+test('isFromActiveCompareRegion returns false when isCompareA and group is not active [compare-util-swipe-a-wrong-group]', () => {
+ const result = isFromActiveCompareRegion([40, 0], 'activeB', 50, {
+ active: true,
+ mode: 'swipe',
+ isCompareA: true,
+ });
+ expect(result).toBe(false);
+});
+
+test('isFromActiveCompareRegion returns true when isCompareA, coords within swipeOffset and group is active [compare-util-swipe-a-valid]', () => {
+ const result = isFromActiveCompareRegion([40, 0], 'active', 50, {
+ active: true,
+ mode: 'swipe',
+ isCompareA: true,
+ });
+ expect(result).toBe(true);
+});
+
+test('isFromActiveCompareRegion returns false when not isCompareA and coords are less than swipeOffset [compare-util-swipe-b-under]', () => {
+ const result = isFromActiveCompareRegion([40, 0], 'activeB', 50, {
+ active: true,
+ mode: 'swipe',
+ isCompareA: false,
+ });
+ expect(result).toBe(false);
+});
+
+test('isFromActiveCompareRegion returns false when not isCompareA and group is not activeB [compare-util-swipe-b-wrong-group]', () => {
+ const result = isFromActiveCompareRegion([60, 0], 'active', 50, {
+ active: true,
+ mode: 'swipe',
+ isCompareA: false,
+ });
+ expect(result).toBe(false);
+});
+
+test('isFromActiveCompareRegion returns true when not isCompareA, coords exceed swipeOffset and group is activeB [compare-util-swipe-b-valid]', () => {
+ const result = isFromActiveCompareRegion([60, 0], 'activeB', 50, {
+ active: true,
+ mode: 'swipe',
+ isCompareA: false,
+ });
+ expect(result).toBe(true);
+});
+
+test('getFormattedMonthAbbrevDates returns dateA and dateB keys [compare-util-formatted-dates]', () => {
+ const dateA = new Date('2021-01-15');
+ const dateB = new Date('2021-06-20');
+ const result = getFormattedMonthAbbrevDates(dateA, dateB);
+ expect(result).toHaveProperty('dateA');
+ expect(result).toHaveProperty('dateB');
+});
+
+test('getFormattedMonthAbbrevDates returns formatted string values [compare-util-formatted-dates-values]', () => {
+ const dateA = new Date('2021-01-15');
+ const dateB = new Date('2021-06-20');
+ const result = getFormattedMonthAbbrevDates(dateA, dateB);
+ expect(typeof result.dateA).toBe('string');
+ expect(typeof result.dateB).toBe('string');
+});
diff --git a/web/js/modules/core/actions.test.js b/web/js/modules/core/actions.test.js
index 22bc698b0..c2720a4ae 100644
--- a/web/js/modules/core/actions.test.js
+++ b/web/js/modules/core/actions.test.js
@@ -1,3 +1,121 @@
-test('actions module test', () => {
+import {
+ startRequest,
+ fetchSuccess,
+ fetchFailure,
+ requestAction,
+} from './actions';
+beforeEach(() => {
+ jest.resetAllMocks();
+});
+
+test('startRequest returns correct type without id [actions-start-no-id]', () => {
+ const result = startRequest('FETCH_DATA');
+ expect(result).toEqual({ type: 'FETCH_DATA_START' });
+ expect(result.id).toBeUndefined();
+});
+
+test('startRequest returns correct type with id [actions-start-with-id]', () => {
+ const result = startRequest('FETCH_DATA', 'abc123');
+ expect(result).toEqual({ type: 'FETCH_DATA_START', id: 'abc123' });
+});
+
+test('startRequest does not include id when id is falsy [actions-start-falsy-id]', () => {
+ const result = startRequest('FETCH_DATA', 0);
+ expect(result.id).toBeUndefined();
+});
+
+test('fetchSuccess returns correct type and response without id [actions-success-no-id]', () => {
+ const result = fetchSuccess('FETCH_DATA', { key: 'value' });
+ expect(result).toEqual({ type: 'FETCH_DATA_SUCCESS', response: { key: 'value' } });
+ expect(result.id).toBeUndefined();
+});
+
+test('fetchSuccess returns correct type, response, and id [actions-success-with-id]', () => {
+ const result = fetchSuccess('FETCH_DATA', { key: 'value' }, 'abc123');
+ expect(result).toEqual({ type: 'FETCH_DATA_SUCCESS', response: { key: 'value' }, id: 'abc123' });
+});
+
+test('fetchFailure returns correct type and error without id [actions-failure-no-id]', () => {
+ const error = new Error('something went wrong');
+ const result = fetchFailure('FETCH_DATA', error);
+ expect(result).toEqual({ type: 'FETCH_DATA_FAILURE', error });
+ expect(result.id).toBeUndefined();
+});
+
+test('fetchFailure returns correct type, error, and id [actions-failure-with-id]', () => {
+ const error = new Error('something went wrong');
+ const result = fetchFailure('FETCH_DATA', error, 'abc123');
+ expect(result).toEqual({ type: 'FETCH_DATA_FAILURE', error, id: 'abc123' });
+});
+
+test('requestAction dispatches start and success, returns json data [actions-request-json]', async () => {
+ const mockData = { result: 'ok' };
+ global.fetch = jest.fn().mockResolvedValue({
+ json: jest.fn().mockResolvedValue(mockData),
+ text: jest.fn(),
+ });
+ const dispatch = jest.fn();
+
+ const result = await requestAction(dispatch, 'FETCH_DATA', '/api/data', 'application/json', undefined, {});
+
+ expect(dispatch).toHaveBeenNthCalledWith(1, { type: 'FETCH_DATA_START' });
+ expect(dispatch).toHaveBeenNthCalledWith(2, { type: 'FETCH_DATA_SUCCESS', response: mockData });
+ expect(result).toEqual(mockData);
+});
+
+test('requestAction dispatches start and success, returns text data [actions-request-text]', async () => {
+ const mockText = '<xml>data</xml>';
+ global.fetch = jest.fn().mockResolvedValue({
+ json: jest.fn(),
+ text: jest.fn().mockResolvedValue(mockText),
+ });
+ const dispatch = jest.fn();
+
+ const result = await requestAction(dispatch, 'FETCH_DATA', '/api/data', 'text/xml', undefined, {});
+
+ expect(dispatch).toHaveBeenNthCalledWith(1, { type: 'FETCH_DATA_START' });
+ expect(dispatch).toHaveBeenNthCalledWith(2, { type: 'FETCH_DATA_SUCCESS', response: mockText });
+ expect(result).toEqual(mockText);
+});
+
+test('requestAction includes id in dispatched actions when provided [actions-request-with-id]', async () => {
+ const mockData = { result: 'ok' };
+ global.fetch = jest.fn().mockResolvedValue({
+ json: jest.fn().mockResolvedValue(mockData),
+ text: jest.fn(),
+ });
+ const dispatch = jest.fn();
+
+ await requestAction(dispatch, 'FETCH_DATA', '/api/data', 'application/json', 'myId', {});
+
+ expect(dispatch).toHaveBeenNthCalledWith(1, { type: 'FETCH_DATA_START', id: 'myId' });
+ expect(dispatch).toHaveBeenNthCalledWith(2, { type: 'FETCH_DATA_SUCCESS', response: mockData, id: 'myId' });
+});
+
+test('requestAction dispatches failure and calls console.error on fetch error [actions-request-failure]', async () => {
+ const mockError = new Error('network failure');
+ global.fetch = jest.fn().mockRejectedValue(mockError);
+ const dispatch = jest.fn();
+ const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
+
+ await requestAction(dispatch, 'FETCH_DATA', '/api/data', 'application/json', undefined, {});
+
+ expect(dispatch).toHaveBeenNthCalledWith(1, { type: 'FETCH_DATA_START' });
+ expect(dispatch).toHaveBeenNthCalledWith(2, { type: 'FETCH_DATA_FAILURE', error: mockError });
+ expect(consoleSpy).toHaveBeenCalledWith(mockError);
+
+ consoleSpy.mockRestore();
+});
+
+test('requestAction dispatches failure with id on fetch error [actions-request-failure-with-id]', async () => {
+ const mockError = new Error('network failure');
+ global.fetch = jest.fn().mockRejectedValue(mockError);
+ const dispatch = jest.fn();
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+
+ await requestAction(dispatch, 'FETCH_DATA', '/api/data', 'application/json', 'errId', {});
+
+ expect(dispatch).toHaveBeenNthCalledWith(1, { type: 'FETCH_DATA_START', id: 'errId' });
+ expect(dispatch).toHaveBeenNthCalledWith(2, { type: 'FETCH_DATA_FAILURE', error: mockError, id: 'errId' });
});
diff --git a/web/js/modules/core/reducers.test.js b/web/js/modules/core/reducers.test.js
index 04cce6a78..6b818d8ac 100644
--- a/web/js/modules/core/reducers.test.js
+++ b/web/js/modules/core/reducers.test.js
@@ -1,3 +1,85 @@
-test('reducers module test', () => {
+import {
+ defaultRequestState,
+ requestResponse,
+ requestReducer,
+} from './reducers';
+test('defaultRequestState has correct initial shape [reducers-default-state]', () => {
+ expect(defaultRequestState).toEqual({
+ isLoading: false,
+ error: null,
+ response: null,
+ type: null,
+ });
+});
+
+test('requestResponse returns defaultRequestState when called with no args [reducers-response-no-args]', () => {
+ const result = requestResponse();
+ expect(result).toEqual(defaultRequestState);
+});
+
+test('requestResponse merges provided props over defaultRequestState [reducers-response-with-props]', () => {
+ const result = requestResponse({ isLoading: true, response: { data: 1 } });
+ expect(result.isLoading).toBe(true);
+ expect(result.response).toEqual({ data: 1 });
+ expect(result.error).toBeNull();
+ expect(result.type).toBeNull();
+});
+
+test('requestResponse does not mutate defaultRequestState [reducers-response-no-mutation]', () => {
+ requestResponse({ isLoading: true });
+ expect(defaultRequestState.isLoading).toBe(false);
+});
+
+test('requestReducer handles START action [reducers-reducer-start]', () => {
+ const result = requestReducer('FETCH_DATA', {}, { type: 'FETCH_DATA_START' });
+ expect(result.isLoading).toBe(true);
+ expect(result.response).toBeNull();
+ expect(result.error).toBeNull();
+});
+
+test('requestReducer handles SUCCESS action with response [reducers-reducer-success]', () => {
+ const mockResponse = { items: [1, 2, 3] };
+ const result = requestReducer('FETCH_DATA', {}, { type: 'FETCH_DATA_SUCCESS', response: mockResponse });
+ expect(result.isLoading).toBe(false);
+ expect(result.response).toEqual(mockResponse);
+ expect(result.error).toBeNull();
+});
+
+test('requestReducer handles FAILURE action with error [reducers-reducer-failure]', () => {
+ const mockError = new Error('failed');
+ const result = requestReducer('FETCH_DATA', {}, { type: 'FETCH_DATA_FAILURE', error: mockError });
+ expect(result.isLoading).toBe(false);
+ expect(result.response).toBeNull();
+ expect(result.error).toEqual(mockError);
+});
+
+test('requestReducer returns current state on unknown action type [reducers-reducer-default]', () => {
+ const currentState = { isLoading: false, error: null, response: { data: 'cached' }, type: null };
+ const result = requestReducer('FETCH_DATA', currentState, { type: 'UNRELATED_ACTION' });
+ expect(result.response).toEqual({ data: 'cached' });
+ expect(result.isLoading).toBe(false);
+});
+
+test('requestReducer does not match START of a different actionName [reducers-reducer-no-cross-match]', () => {
+ const currentState = { isLoading: false, error: null, response: { data: 'cached' }, type: null };
+ const result = requestReducer('FETCH_DATA', currentState, { type: 'OTHER_ACTION_START' });
+ expect(result.isLoading).toBe(false);
+ expect(result.response).toEqual({ data: 'cached' });
+});
+
+test('requestReducer SUCCESS sets isLoading to false [reducers-reducer-success-not-loading]', () => {
+ const loadingState = { isLoading: true, error: null, response: null, type: null };
+ const result = requestReducer('MY_ACTION', loadingState, { type: 'MY_ACTION_SUCCESS', response: 'ok' });
+ expect(result.isLoading).toBe(false);
+ expect(result.response).toBe('ok');
+});
+
+test('requestReducer FAILURE sets isLoading to false [reducers-reducer-failure-not-loading]', () => {
+ const loadingState = { isLoading: true, error: null, response: null, type: null };
+ const mockError = new Error('oops');
+ const result = requestReducer('MY_ACTION', loadingState, { type: 'MY_ACTION_FAILURE', error: mockError });
+ expect(result.isLoading).toBe(false);
+ expect(result.error).toEqual(mockError);
+ expect(result.response).toBeNull();
});
diff --git a/web/js/modules/date/actions.test.js b/web/js/modules/date/actions.test.js
index 533e0ba18..ff73b4257 100644
--- a/web/js/modules/date/actions.test.js
+++ b/web/js/modules/date/actions.test.js
@@ -7,6 +7,13 @@ import {
changeCustomInterval,
changeAutoInterval,
selectInterval,
+ toggleCustomModal,
+ setArrowDown,
+ setArrowUp,
+ setPreload,
+ clearPreload,
+ initSecondDate,
+ triggerTodayButton,
} from './actions';
import {
CHANGE_TIME_SCALE,
@@ -15,6 +22,11 @@ import {
CHANGE_INTERVAL,
SELECT_DATE,
UPDATE_APP_NOW,
+ TOGGLE_CUSTOM_MODAL,
+ INIT_SECOND_DATE,
+ ARROW_DOWN,
+ ARROW_UP,
+ SET_PRELOAD,
CLEAR_PRELOAD,
} from './constants';
import fixtures from '../../fixtures';
@@ -44,15 +56,13 @@ function addMockLayer(layerId, layerArray) {
layerArray,
config.layers,
{},
- getLayers(getState(layerArray), { group: 'all' }).overlays
- .length,
+ getLayers(getState(layerArray), { group: 'all' }).overlays.length,
);
}
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
-// test variables
const mockDate = new Date('2022-01-01');
const customInterval = 3;
const delta = 5;
@@ -84,9 +94,7 @@ describe('Date timescale changes', () => {
test(
`selectDate action returns ${SELECT_DATE} as type, 'selected' as activeString, and ${mockDate} as value [date-action-select-date]`,
() => {
- const expectedFirst = {
- type: CLEAR_PRELOAD,
- };
+ const expectedFirst = { type: CLEAR_PRELOAD };
const expectedSecond = {
type: SELECT_DATE,
activeString: 'selected',
@@ -109,13 +117,9 @@ describe('Date timescale changes', () => {
activeString: 'active',
},
layers: {
- active: {
- layers,
- },
- },
- proj: {
- id: 'geographic',
+ active: { layers },
},
+ proj: { id: 'geographic' },
});
store.dispatch(selectDate(mockDate));
expect(store.getActions()[0]).toEqual(expectedFirst);
@@ -127,9 +131,7 @@ describe('Date timescale changes', () => {
`selectDate action returns ${SELECT_DATE} as type and selectedB as activeString and ${mockDate} as value [date-action-select-date-b]`,
() => {
const prevDate = new Date('2021-01-01');
- const expectedFirst = {
- type: CLEAR_PRELOAD,
- };
+ const expectedFirst = { type: CLEAR_PRELOAD };
const expectedSecond = {
type: SELECT_DATE,
activeString: 'selectedB',
@@ -152,13 +154,9 @@ describe('Date timescale changes', () => {
activeString: 'activeB',
},
layers: {
- activeB: {
- layers,
- },
- },
- proj: {
- id: 'geographic',
+ activeB: { layers },
},
+ proj: { id: 'geographic' },
});
store.dispatch(selectDate(mockDate));
expect(store.getActions()[0]).toEqual(expectedFirst);
@@ -167,21 +165,45 @@ describe('Date timescale changes', () => {
);
test(
- `changeCustomInterval action returns ${CHANGE_CUSTOM_INTERVAL} as type and ${customInterval} as value and ${delta} as delta [date-action-custom-interval]`,
+ 'selectDate does not dispatch CLEAR_PRELOAD when preloaded is false [date-action-select-date-no-preload]',
() => {
+ let layers = addLayer('terra-cr', [], config.layers, {}, 0);
+ layers = addMockLayer('aqua-cr', layers);
+ const prevDate = new Date('2021-01-01');
const store = mockStore({
- date: {},
+ date: {
+ preloaded: false,
+ selected: prevDate,
+ lastArrowDirection: 'right',
+ delta: 1,
+ interval: 1,
+ unit: 'year',
+ },
compare: {
- isCompareA: false,
- activeString: 'activeB',
+ isCompareA: true,
+ activeString: 'active',
},
- proj: {
- id: 'geographic',
+ layers: {
+ active: { layers },
},
+ proj: { id: 'geographic' },
});
- const expectedFirst = {
- type: CLEAR_PRELOAD,
- };
+ store.dispatch(selectDate(mockDate));
+ const actions = store.getActions();
+ expect(actions.length).toBe(1);
+ expect(actions[0].type).toEqual(SELECT_DATE);
+ },
+ );
+
+ test(
+ `changeCustomInterval action returns ${CHANGE_CUSTOM_INTERVAL} as type and ${customInterval} as value and ${delta} as delta [date-action-custom-interval]`,
+ () => {
+ const store = mockStore({
+ date: {},
+ compare: { isCompareA: false, activeString: 'activeB' },
+ proj: { id: 'geographic' },
+ });
+ const expectedFirst = { type: CLEAR_PRELOAD };
const expectedSecond = {
type: CHANGE_CUSTOM_INTERVAL,
interval: customInterval,
@@ -198,17 +220,10 @@ describe('Date timescale changes', () => {
() => {
const store = mockStore({
date: {},
- compare: {
- isCompareA: false,
- activeString: 'activeB',
- },
- proj: {
- id: 'geographic',
- },
+ compare: { isCompareA: false, activeString: 'activeB' },
+ proj: { id: 'geographic' },
});
- const expectedFirst = {
- type: CLEAR_PRELOAD,
- };
+ const expectedFirst = { type: CLEAR_PRELOAD };
const expectedSecond = {
type: CHANGE_AUTO_INTERVAL,
autoSelected: true,
@@ -224,17 +239,10 @@ describe('Date timescale changes', () => {
() => {
const store = mockStore({
date: {},
- compare: {
- isCompareA: false,
- activeString: 'activeB',
- },
- proj: {
- id: 'geographic',
- },
+ compare: { isCompareA: false, activeString: 'activeB' },
+ proj: { id: 'geographic' },
});
- const expectedFirst = {
- type: CLEAR_PRELOAD,
- };
+ const expectedFirst = { type: CLEAR_PRELOAD };
const expectedSecond = {
type: CHANGE_INTERVAL,
interval,
@@ -246,4 +254,154 @@ describe('Date timescale changes', () => {
expect(store.getActions()[1]).toEqual(expectedSecond);
},
);
+
+ test(
+ 'selectInterval passes autoSelected when provided [date-action-interval-auto]',
+ () => {
+ const store = mockStore({
+ date: {},
+ compare: { isCompareA: false, activeString: 'activeB' },
+ proj: { id: 'geographic' },
+ });
+ store.dispatch(selectInterval(delta, interval, false, true));
+ const second = store.getActions()[1];
+ expect(second.autoSelected).toBe(true);
+ expect(second.customSelected).toBe(false);
+ },
+ );
+});
+
+test('initSecondDate returns INIT_SECOND_DATE action [date-action-init-second-date]', () => {
+ expect(initSecondDate()).toEqual({ type: INIT_SECOND_DATE });
+});
+
+test('clearPreload returns CLEAR_PRELOAD action [date-action-clear-preload]', () => {
+ expect(clearPreload()).toEqual({ type: CLEAR_PRELOAD });
+});
+
+test('setArrowUp returns ARROW_UP action [date-action-arrow-up]', () => {
+ expect(setArrowUp()).toEqual({ type: ARROW_UP });
+});
+
+test('setPreload returns SET_PRELOAD action with preloaded and lastPreloadDate [date-action-set-preload]', () => {
+ const lastPreloadDate = new Date('2022-06-01');
+ expect(setPreload(true, lastPreloadDate)).toEqual({
+ type: SET_PRELOAD,
+ preloaded: true,
+ lastPreloadDate,
+ });
+});
+
+test('toggleCustomModal returns TOGGLE_CUSTOM_MODAL with open and toggleBy [date-action-toggle-modal]', () => {
+ expect(toggleCustomModal(true, 'button')).toEqual({
+ type: TOGGLE_CUSTOM_MODAL,
+ value: true,
+ toggleBy: 'button',
+ });
+});
+
+test('toggleCustomModal returns TOGGLE_CUSTOM_MODAL with false [date-action-toggle-modal-false]', () => {
+ expect(toggleCustomModal(false, 'outside')).toEqual({
+ type: TOGGLE_CUSTOM_MODAL,
+ value: false,
+ toggleBy: 'outside',
+ });
+});
+
+test('setArrowDown dispatches CLEAR_PRELOAD and ARROW_DOWN when direction changes [date-action-arrow-down-change]', () => {
+ const store = mockStore({
+ date: { lastArrowDirection: 'left' },
+ });
+ store.dispatch(setArrowDown('right'));
+ const actions = store.getActions();
+ expect(actions[0]).toEqual({ type: CLEAR_PRELOAD });
+ expect(actions[1]).toEqual({ type: ARROW_DOWN, value: 'right' });
+});
+
+test('setArrowDown dispatches only ARROW_DOWN when direction is unchanged [date-action-arrow-down-same]', () => {
+ const store = mockStore({
+ date: { lastArrowDirection: 'right' },
+ });
+ store.dispatch(setArrowDown('right'));
+ const actions = store.getActions();
+ expect(actions.length).toBe(1);
+ expect(actions[0]).toEqual({ type: ARROW_DOWN, value: 'right' });
+});
+
+test('setArrowDown dispatches only ARROW_DOWN when direction is null [date-action-arrow-down-null]', () => {
+ const store = mockStore({
+ date: { lastArrowDirection: 'right' },
+ });
+ store.dispatch(setArrowDown(null));
+ const actions = store.getActions();
+ expect(actions.length).toBe(1);
+ expect(actions[0]).toEqual({ type: ARROW_DOWN, value: null });
+});
+
+test('triggerTodayButton dispatches SELECT_DATE when selectedDate differs from appNow [date-action-today-button]', () => {
+ const appNow = new Date('2022-06-01');
+ const selected = new Date('2022-01-01');
+ const store = mockStore({
+ date: {
+ selected,
+ appNow,
+ },
+ compare: {
+ isCompareA: true,
+ },
+ proj: { id: 'geographic' },
+ config,
+ layers: { active: { layers: [] } },
+ });
+ store.dispatch(triggerTodayButton());
+ const actions = store.getActions();
+ expect(actions.length).toBe(1);
+ expect(actions[0]).toEqual({
+ type: SELECT_DATE,
+ activeString: 'selected',
+ value: appNow,
+ });
+});
+
+test('triggerTodayButton does not dispatch when selectedDate equals appNow [date-action-today-button-no-op]', () => {
+ const appNow = new Date('2022-06-01');
+ const store = mockStore({
+ date: {
+ selected: appNow,
+ appNow,
+ },
+ compare: {
+ isCompareA: true,
+ },
+ proj: { id: 'geographic' },
+ config,
+ layers: { active: { layers: [] } },
+ });
+ store.dispatch(triggerTodayButton());
+ expect(store.getActions().length).toBe(0);
+});
+
+test('triggerTodayButton uses selectedB when isCompareA is false [date-action-today-button-b]', () => {
+ const appNow = new Date('2022-06-01');
+ const selectedB = new Date('2022-01-01');
+ const store = mockStore({
+ date: {
+ selectedB,
+ appNow,
+ },
+ compare: {
+ isCompareA: false,
+ },
+ proj: { id: 'geographic' },
+ config,
+ layers: { activeB: { layers: [] } },
+ });
+ store.dispatch(triggerTodayButton());
+ const actions = store.getActions();
+ expect(actions.length).toBe(1);
+ expect(actions[0]).toEqual({
+ type: SELECT_DATE,
+ activeString: 'selectedB',
+ value: appNow,
+ });
});
diff --git a/web/js/modules/date/reducers.test.js b/web/js/modules/date/reducers.test.js
index 369418ad3..048e6b38f 100644
--- a/web/js/modules/date/reducers.test.js
+++ b/web/js/modules/date/reducers.test.js
@@ -1,6 +1,7 @@
import {
dateReducer,
dateReducerState,
+ getInitialState,
} from './reducers';
import {
CHANGE_TIME_SCALE,
@@ -9,46 +10,38 @@ import {
CHANGE_INTERVAL,
SELECT_DATE,
UPDATE_APP_NOW,
+ TOGGLE_CUSTOM_MODAL,
+ INIT_SECOND_DATE,
+ ARROW_DOWN,
+ ARROW_UP,
+ SET_PRELOAD,
+ CLEAR_PRELOAD,
+ customModalType,
} from './constants';
import util from '../../util/util';
-// test variables
const mockDate = util.now();
const selectedZoom = 2;
describe('dateReducer', () => {
test('should return the initial state [date-reducer-initial-state]', () => {
- expect(dateReducer(undefined, {})).toEqual(
- dateReducerState,
- );
+ expect(dateReducer(undefined, {})).toEqual(dateReducerState);
});
+
test(
- `${CHANGE_TIME_SCALE
- }action type and ${selectedZoom} as selectedZoom ` +
- 'should return new state [date-reducer-time-scale]',
+ `${CHANGE_TIME_SCALE} action type and ${selectedZoom} as selectedZoom should return new state [date-reducer-time-scale]`,
() => {
expect(
- dateReducer(dateReducerState, {
- type: CHANGE_TIME_SCALE,
- value: selectedZoom,
- }),
- ).toEqual({
- ...dateReducerState,
- selectedZoom,
- });
+ dateReducer(dateReducerState, { type: CHANGE_TIME_SCALE, value: selectedZoom }),
+ ).toEqual({ ...dateReducerState, selectedZoom });
},
);
+
test(
- `${CHANGE_CUSTOM_INTERVAL
- }action type and 4 as customInterval and 10 as customDelta ` +
- 'should return new state [date-reducer-custom-interval]',
+ `${CHANGE_CUSTOM_INTERVAL} action type and 4 as customInterval and 10 as customDelta should return new state [date-reducer-custom-interval]`,
() => {
expect(
- dateReducer(dateReducerState, {
- type: CHANGE_CUSTOM_INTERVAL,
- interval: 4,
- delta: 10,
- }),
+ dateReducer(dateReducerState, { type: CHANGE_CUSTOM_INTERVAL, interval: 4, delta: 10 }),
).toEqual({
...dateReducerState,
customInterval: 4,
@@ -57,10 +50,22 @@ describe('dateReducer', () => {
});
},
);
+
+ test(
+ 'CHANGE_CUSTOM_INTERVAL with null interval and null delta sets customSelected to false [date-reducer-custom-interval-false]',
+ () => {
+ const result = dateReducer(dateReducerState, {
+ type: CHANGE_CUSTOM_INTERVAL,
+ interval: null,
+ delta: null,
+ });
+ expect(result.customSelected).toBe(false);
+ expect(result.autoSelected).toBe(false);
+ },
+ );
+
test(
- `${CHANGE_AUTO_INTERVAL
- }action type and true as autoSelected ` +
- 'should return new state [date-reducer-auto-interval]',
+ `${CHANGE_AUTO_INTERVAL} action type and true as autoSelected should return new state [date-reducer-auto-interval]`,
() => {
expect(
dateReducer(dateReducerState, {
@@ -69,16 +74,25 @@ describe('dateReducer', () => {
delta: 1,
autoSelected: true,
}),
- ).toEqual({
- ...dateReducerState,
+ ).toEqual({ ...dateReducerState, autoSelected: true });
+ },
+ );
+
+ test(
+ 'CHANGE_AUTO_INTERVAL sets customSelected to false [date-reducer-auto-interval-clears-custom]',
+ () => {
+ const stateWithCustom = { ...dateReducerState, customSelected: true };
+ const result = dateReducer(stateWithCustom, {
+ type: CHANGE_AUTO_INTERVAL,
autoSelected: true,
});
+ expect(result.customSelected).toBe(false);
+ expect(result.autoSelected).toBe(true);
},
);
+
test(
- `${CHANGE_INTERVAL
- }action type and 1 as delta and 2 as interval ` +
- 'should return new state [date-reducer-interval]',
+ `${CHANGE_INTERVAL} action type and 1 as delta and 2 as interval should return new state [date-reducer-interval]`,
() => {
expect(
dateReducer(dateReducerState, {
@@ -97,9 +111,9 @@ describe('dateReducer', () => {
});
},
);
+
test(
- `${SELECT_DATE} action type and ${mockDate} as value and selected ` +
- 'as activeString should return new state [date-reducer-selected]',
+ `${SELECT_DATE} action type and ${mockDate} as value and selected as activeString should return new state [date-reducer-selected]`,
() => {
expect(
dateReducer(dateReducerState, {
@@ -107,16 +121,12 @@ describe('dateReducer', () => {
value: mockDate,
activeString: 'selected',
}),
- ).toEqual({
- ...dateReducerState,
- selected: mockDate,
- });
+ ).toEqual({ ...dateReducerState, selected: mockDate });
},
);
+
test(
- `${SELECT_DATE
- }action type and ${mockDate} as value and selectedB ` +
- 'as activeString should return new state [date-reducer-selectedB]',
+ `${SELECT_DATE} action type and ${mockDate} as value and selectedB as activeString should return new state [date-reducer-selectedB]`,
() => {
expect(
dateReducer(dateReducerState, {
@@ -124,25 +134,153 @@ describe('dateReducer', () => {
value: mockDate,
activeString: 'selectedB',
}),
- ).toEqual({
- ...dateReducerState,
- selectedB: mockDate,
+ ).toEqual({ ...dateReducerState, selectedB: mockDate });
+ },
+ );
+
+ test(
+ 'SELECT_DATE stores lastArrowDirection from action [date-reducer-selected-arrow-direction]',
+ () => {
+ const result = dateReducer(dateReducerState, {
+ type: SELECT_DATE,
+ value: mockDate,
+ activeString: 'selected',
+ lastArrowDirection: 'right',
});
+ expect(result.lastArrowDirection).toBe('right');
},
);
+
test(
- `${UPDATE_APP_NOW
- }action type and ${mockDate} as value should return new state [date-reducer-update-app-now]`,
+ `${UPDATE_APP_NOW} action type and ${mockDate} as value should return new state [date-reducer-update-app-now]`,
() => {
expect(
- dateReducer(dateReducerState, {
- type: UPDATE_APP_NOW,
- value: mockDate,
- }),
- ).toEqual({
- ...dateReducerState,
- appNow: mockDate,
+ dateReducer(dateReducerState, { type: UPDATE_APP_NOW, value: mockDate }),
+ ).toEqual({ ...dateReducerState, appNow: mockDate });
+ },
+ );
+
+ test(
+ 'INIT_SECOND_DATE sets selectedB to 7 days before selected [date-reducer-init-second-date]',
+ () => {
+ const selected = new Date('2022-01-08');
+ const stateWithSelected = { ...dateReducerState, selected };
+ const result = dateReducer(stateWithSelected, { type: INIT_SECOND_DATE });
+ const expected = util.dateAdd(selected, 'day', -7);
+ expect(result.selectedB).toEqual(expected);
+ },
+ );
+
+ test(
+ 'ARROW_DOWN sets arrowDown and lastArrowDirection to the given value [date-reducer-arrow-down]',
+ () => {
+ const result = dateReducer(dateReducerState, { type: ARROW_DOWN, value: 'right' });
+ expect(result.arrowDown).toBe('right');
+ expect(result.lastArrowDirection).toBe('right');
+ },
+ );
+
+ test(
+ 'ARROW_UP clears arrowDown to empty string [date-reducer-arrow-up]',
+ () => {
+ const stateWithArrow = { ...dateReducerState, arrowDown: 'left' };
+ const result = dateReducer(stateWithArrow, { type: ARROW_UP });
+ expect(result.arrowDown).toBe('');
+ },
+ );
+
+ test(
+ 'SET_PRELOAD sets preloaded and lastPreloadDate [date-reducer-set-preload]',
+ () => {
+ const lastPreloadDate = new Date('2022-06-01');
+ const result = dateReducer(dateReducerState, {
+ type: SET_PRELOAD,
+ preloaded: true,
+ lastPreloadDate,
});
+ expect(result.preloaded).toBe(true);
+ expect(result.lastPreloadDate).toEqual(lastPreloadDate);
+ },
+ );
+
+ test(
+ 'CLEAR_PRELOAD sets preloaded and lastPreloadDate to null [date-reducer-clear-preload]',
+ () => {
+ const loadedState = { ...dateReducerState, preloaded: true, lastPreloadDate: new Date() };
+ const result = dateReducer(loadedState, { type: CLEAR_PRELOAD });
+ expect(result.preloaded).toBeNull();
+ expect(result.lastPreloadDate).toBeNull();
},
);
+
+ test(
+ 'TOGGLE_CUSTOM_MODAL with TIMELINE toggleBy sets timelineCustomModalOpen and closes animation [date-reducer-toggle-modal-timeline]',
+ () => {
+ const result = dateReducer(dateReducerState, {
+ type: TOGGLE_CUSTOM_MODAL,
+ value: true,
+ toggleBy: customModalType.TIMELINE,
+ });
+ expect(result.timelineCustomModalOpen).toBe(true);
+ expect(result.animationCustomModalOpen).toBe(false);
+ },
+ );
+
+ test(
+ 'TOGGLE_CUSTOM_MODAL with ANIMATION toggleBy sets animationCustomModalOpen and closes timeline [date-reducer-toggle-modal-animation]',
+ () => {
+ const result = dateReducer(dateReducerState, {
+ type: TOGGLE_CUSTOM_MODAL,
+ value: true,
+ toggleBy: customModalType.ANIMATION,
+ });
+ expect(result.animationCustomModalOpen).toBe(true);
+ expect(result.timelineCustomModalOpen).toBe(false);
+ },
+ );
+
+ test(
+ 'TOGGLE_CUSTOM_MODAL with unknown toggleBy sets both modals with action value [date-reducer-toggle-modal-other]',
+ () => {
+ const result = dateReducer(dateReducerState, {
+ type: TOGGLE_CUSTOM_MODAL,
+ value: true,
+ toggleBy: 'other',
+ });
+ expect(result.timelineCustomModalOpen).toBe(true);
+ expect(result.animationCustomModalOpen).toBe(true);
+ },
+ );
+
+ test(
+ 'default case returns unchanged state [date-reducer-default]',
+ () => {
+ const result = dateReducer(dateReducerState, { type: 'UNKNOWN_ACTION' });
+ expect(result).toEqual(dateReducerState);
+ },
+ );
+});
+
+describe('getInitialState', () => {
+ test('returns state with selected, selectedB, and appNow from config [date-reducer-get-initial-state]', () => {
+ const initialDate = new Date('2022-01-01');
+ const pageLoadTime = new Date('2022-01-01T12:00:00Z');
+ const config = { initialDate, pageLoadTime };
+ const result = getInitialState(config);
+ expect(result.selected).toEqual(initialDate);
+ expect(result.selectedB).toEqual(util.dateAdd(initialDate, 'day', -7));
+ expect(result.appNow).toEqual(pageLoadTime);
+ });
+
+ test('getInitialState spreads all dateReducerState properties [date-reducer-get-initial-state-spread]', () => {
+ const initialDate = new Date('2022-03-15');
+ const pageLoadTime = new Date('2022-03-15T08:00:00Z');
+ const config = { initialDate, pageLoadTime };
+ const result = getInitialState(config);
+ expect(result.selectedZoom).toBe(dateReducerState.selectedZoom);
+ expect(result.interval).toBe(dateReducerState.interval);
+ expect(result.delta).toBe(dateReducerState.delta);
+ expect(result.customSelected).toBe(dateReducerState.customSelected);
+ expect(result.autoSelected).toBe(dateReducerState.autoSelected);
+ });
});
diff --git a/web/js/modules/date/selectors.test.js b/web/js/modules/date/selectors.test.js
index c4e1cdccf..ec2659c31 100644
--- a/web/js/modules/date/selectors.test.js
+++ b/web/js/modules/date/selectors.test.js
@@ -1,3 +1,122 @@
-test('selectors module test', () => {
+import { getDates, getSelectedDate, getDeltaIntervalUnit } from './selectors';
+import { TIME_SCALE_FROM_NUMBER } from './constants';
+const selectedDate = new Date('2022-01-01');
+const selectedBDate = new Date('2021-06-15');
+
+const baseState = {
+ date: {
+ selected: selectedDate,
+ selectedB: selectedBDate,
+ interval: 3,
+ delta: 1,
+ customSelected: false,
+ customInterval: 5,
+ customDelta: 10,
+ },
+ compare: {
+ isCompareA: true,
+ },
+};
+
+describe('getDates', () => {
+ test('returns the date object from state [selector-get-dates]', () => {
+ const result = getDates(baseState);
+ expect(result).toBe(baseState.date);
+ });
+
+ test('returns the full date object with all properties [selector-get-dates-full]', () => {
+ const result = getDates(baseState);
+ expect(result.selected).toEqual(selectedDate);
+ expect(result.selectedB).toEqual(selectedBDate);
+ });
+});
+
+describe('getSelectedDate', () => {
+ test('returns date[compareDateString] when compareDateString is provided [selector-get-selected-date-string]', () => {
+ const result = getSelectedDate(baseState, 'selected');
+ expect(result).toEqual(selectedDate);
+ });
+
+ test('returns date[selectedB] when compareDateString is "selectedB" [selector-get-selected-date-string-b]', () => {
+ const result = getSelectedDate(baseState, 'selectedB');
+ expect(result).toEqual(selectedBDate);
+ });
+
+ test('returns date.selected when no compareDateString and isCompareA is true [selector-get-selected-date-compare-a]', () => {
+ const result = getSelectedDate(baseState);
+ expect(result).toEqual(selectedDate);
+ });
+
+ test('returns date.selectedB when no compareDateString and isCompareA is false [selector-get-selected-date-compare-b]', () => {
+ const stateB = {
+ ...baseState,
+ compare: { isCompareA: false },
+ };
+ const result = getSelectedDate(stateB);
+ expect(result).toEqual(selectedBDate);
+ });
+
+ test('returns undefined when compareDateString key does not exist in date [selector-get-selected-date-missing-key]', () => {
+ const result = getSelectedDate(baseState, 'nonExistentKey');
+ expect(result).toBeUndefined();
+ });
+});
+
+describe('getDeltaIntervalUnit', () => {
+ test('returns delta, interval, and unit from standard (non-custom) state [selector-get-delta-interval-unit-standard]', () => {
+ const result = getDeltaIntervalUnit(baseState);
+ expect(result.delta).toBe(baseState.date.delta);
+ expect(result.interval).toBe(baseState.date.interval);
+ expect(result.unit).toBe(TIME_SCALE_FROM_NUMBER[baseState.date.interval]);
+ });
+
+ test('returns customDelta and customInterval when customSelected is true [selector-get-delta-interval-unit-custom]', () => {
+ const customState = {
+ ...baseState,
+ date: {
+ ...baseState.date,
+ customSelected: true,
+ },
+ };
+ const result = getDeltaIntervalUnit(customState);
+ expect(result.delta).toBe(customState.date.customDelta);
+ expect(result.interval).toBe(customState.date.customInterval);
+ expect(result.unit).toBe(TIME_SCALE_FROM_NUMBER[customState.date.customInterval]);
+ });
+
+ test('returns correct unit mapped from TIME_SCALE_FROM_NUMBER for standard interval [selector-get-delta-interval-unit-mapping]', () => {
+ const result = getDeltaIntervalUnit(baseState);
+ expect(result.unit).toBe(TIME_SCALE_FROM_NUMBER[3]);
+ });
+
+ test('returns correct unit mapped from TIME_SCALE_FROM_NUMBER for custom interval [selector-get-delta-interval-unit-custom-mapping]', () => {
+ const customState = {
+ ...baseState,
+ date: {
+ ...baseState.date,
+ customSelected: true,
+ customInterval: 5,
+ },
+ };
+ const result = getDeltaIntervalUnit(customState);
+ expect(result.unit).toBe(TIME_SCALE_FROM_NUMBER[5]);
+ });
+
+ test('returns undefined unit when interval has no mapping in TIME_SCALE_FROM_NUMBER [selector-get-delta-interval-unit-no-mapping]', () => {
+ const stateWithUnknownInterval = {
+ ...baseState,
+ date: {
+ ...baseState.date,
+ interval: 999,
+ },
+ };
+ const result = getDeltaIntervalUnit(stateWithUnknownInterval);
+ expect(result.unit).toBeUndefined();
+ });
+
+ test('returned object has exactly delta, interval, and unit keys [selector-get-delta-interval-unit-shape]', () => {
+ const result = getDeltaIntervalUnit(baseState);
+ expect(Object.keys(result)).toEqual(['delta', 'interval', 'unit']);
+ });
});
diff --git a/web/js/modules/date/util.test.js b/web/js/modules/date/util.test.js
index 3400252b5..d601c97f4 100644
--- a/web/js/modules/date/util.test.js
+++ b/web/js/modules/date/util.test.js
@@ -1,39 +1,52 @@
import {
- mapLocationToDateState, tryCatchDate, rollDate, roll, getDaysInMonth,
+ mapLocationToDateState,
+ tryCatchDate,
+ rollDate,
+ roll,
+ getDaysInMonth,
+ getNextTimeSelection,
+ formatDisplayDate,
+ parseDate,
+ serializeDate,
+ serializeDateWrapper,
+ serializeDateBWrapper,
+ serializeDateChartingWrapper,
+ filterProjLayersWithStartDate,
+ getMaxLayerEndDates,
+ getLayersActiveAtDate,
+ outOfStepChange,
+ getNextDateTime,
+ getNumberStepsBetween,
+ coverageDateFormatter,
+ formatISODate,
+ parsePermalinkDate,
+ getNextImageryDelta,
+ checkHasFutureLayers,
} from './util';
import fixtures from '../../fixtures';
const state = fixtures.getState();
+const config = fixtures.config();
test('parses date 1.1 [date-parse-1.1]', () => {
const d = new Date(Date.UTC(2013, 0, 5));
- const param = {
- time: '2013-01-05',
- };
- let stateFromLocation = {
- date: {},
- };
-
+ const param = { time: '2013-01-05' };
+ let stateFromLocation = { date: {} };
stateFromLocation = mapLocationToDateState(param, stateFromLocation, state);
expect(stateFromLocation.date.selected).toMatchObject(d);
});
+
test('parses valid date: 1.2 [date-parse-1.2]', () => {
const d = new Date(Date.UTC(2013, 0, 5));
- const param = {
- t: '2013-01-05',
- };
+ const param = { t: '2013-01-05' };
const date = tryCatchDate(param.t, state.date.appNow);
expect(date).toEqual(d);
});
+
test('If date is invalid, uses Initial Time [date-invalid]', () => {
- const param = {
- time: 'X',
- };
- let stateFromLocation = {
- date: state.date,
- };
+ const param = { time: 'X' };
+ let stateFromLocation = { date: state.date };
stateFromLocation = mapLocationToDateState(param, stateFromLocation, state);
-
expect(stateFromLocation.date.selected).toBe(state.date.selected);
});
@@ -169,42 +182,631 @@ describe('rollDate', () => {
answer: new Date(Date.UTC(2015, 6, 16)),
}];
- tests.forEach((t) => {
- test(t.name, () => {
- const result = rollDate(t.d, t.period.unit, t.period.value, t.minDate, t.maxDate);
- expect(result).toEqual(t.answer);
+ tests.forEach(({ name, d, period, answer, minDate, maxDate }) => {
+ test(name, () => {
+ expect(rollDate(d, period.unit, period.value, minDate, maxDate)).toEqual(answer);
});
});
+
+ test('rollDate minute up [date-minute-up]', () => {
+ const d = new Date(Date.UTC(2014, 0, 1, 12, 30, 0));
+ expect(rollDate(d, 'minute', 1)).toEqual(new Date(Date.UTC(2014, 0, 1, 12, 31, 0)));
+ });
+
+ test('rollDate minute down [date-minute-down]', () => {
+ const d = new Date(Date.UTC(2014, 0, 1, 12, 30, 0));
+ expect(rollDate(d, 'minute', -1)).toEqual(new Date(Date.UTC(2014, 0, 1, 12, 29, 0)));
+ });
+
+ test('rollDate minute roll over max [date-minute-roll-max]', () => {
+ const d = new Date(Date.UTC(2014, 0, 1, 12, 59, 0));
+ expect(rollDate(d, 'minute', 1)).toEqual(new Date(Date.UTC(2014, 0, 1, 12, 0, 0)));
+ });
+
+ test('rollDate minute roll over min [date-minute-roll-min]', () => {
+ const d = new Date(Date.UTC(2014, 0, 1, 12, 0, 0));
+ expect(rollDate(d, 'minute', -1)).toEqual(new Date(Date.UTC(2014, 0, 1, 12, 59, 0)));
+ });
+
+ test('rollDate hour up [date-hour-up]', () => {
+ const d = new Date(Date.UTC(2014, 0, 1, 12, 0, 0));
+ expect(rollDate(d, 'hour', 1)).toEqual(new Date(Date.UTC(2014, 0, 1, 13, 0, 0)));
+ });
+
+ test('rollDate hour roll over max [date-hour-roll-max]', () => {
+ const d = new Date(Date.UTC(2014, 0, 1, 23, 0, 0));
+ expect(rollDate(d, 'hour', 1)).toEqual(new Date(Date.UTC(2014, 0, 1, 0, 0, 0)));
+ });
+
+ test('rollDate throws on invalid interval [date-invalid-interval]', () => {
+ const d = new Date(Date.UTC(2014, 0, 1));
+ expect(() => rollDate(d, 'invalid', 1)).toThrow('[rollDate] Invalid interval: invalid');
+ });
});
describe('roll', () => {
- const tests = [
- {
- v: 15, min: 10, max: 20, answer: 15, name: 'middle',
- },
- {
- v: 8, min: 10, max: 20, answer: 19, name: 'min',
- },
- {
- v: 22, min: 10, max: 20, answer: 11, name: 'max',
- },
- ];
-
- tests.forEach((t) => {
- test(t.name, () => {
- expect(roll(t.v, t.min, t.max)).toBe(t.answer);
- });
+ test('returns value when within range [roll-in-range]', () => {
+ expect(roll(5, 1, 10)).toBe(5);
+ });
+
+ test('wraps from below min [roll-below-min]', () => {
+ expect(roll(0, 1, 10)).toBe(10);
+ });
+
+ test('wraps from above max [roll-above-max]', () => {
+ expect(roll(11, 1, 10)).toBe(1);
+ });
+
+ test('returns min when equal to min [roll-at-min]', () => {
+ expect(roll(1, 1, 10)).toBe(1);
+ });
+
+ test('returns max when equal to max [roll-at-max]', () => {
+ expect(roll(10, 1, 10)).toBe(10);
+ });
+});
+
+describe('getDaysInMonth', () => {
+ test('returns 28 for February in a non-leap year [days-in-month-feb]', () => {
+ expect(getDaysInMonth(new Date(Date.UTC(2014, 1, 1)))).toBe(28);
+ });
+
+ test('returns 29 for February in a leap year [days-in-month-feb-leap]', () => {
+ expect(getDaysInMonth(new Date(Date.UTC(2016, 1, 1)))).toBe(29);
+ });
+
+ test('returns 31 for January [days-in-month-jan]', () => {
+ expect(getDaysInMonth(new Date(Date.UTC(2014, 0, 1)))).toBe(31);
+ });
+
+ test('returns 30 for April [days-in-month-apr]', () => {
+ expect(getDaysInMonth(new Date(Date.UTC(2014, 3, 1)))).toBe(30);
+ });
+
+ test('accepts plain object with year and month [days-in-month-object]', () => {
+ expect(getDaysInMonth({ year: 2014, month: 1 })).toBe(28);
+ });
+});
+
+describe('getNextTimeSelection', () => {
+ const minDate = new Date(Date.UTC(2000, 0, 1));
+ const maxDate = new Date(Date.UTC(2030, 11, 31));
+
+ test('increments year [next-time-year]', () => {
+ const d = new Date(Date.UTC(2014, 5, 15));
+ expect(getNextTimeSelection(1, 'year', d, minDate, maxDate))
+ .toEqual(new Date(Date.UTC(2015, 5, 15)));
+ });
+
+ test('decrements year [next-time-year-down]', () => {
+ const d = new Date(Date.UTC(2014, 5, 15));
+ expect(getNextTimeSelection(-1, 'year', d, minDate, maxDate))
+ .toEqual(new Date(Date.UTC(2013, 5, 15)));
+ });
+
+ test('increments month [next-time-month]', () => {
+ const d = new Date(Date.UTC(2014, 5, 15));
+ expect(getNextTimeSelection(1, 'month', d, minDate, maxDate))
+ .toEqual(new Date(Date.UTC(2014, 6, 15)));
+ });
+
+ test('increments day [next-time-day]', () => {
+ const d = new Date(Date.UTC(2014, 5, 15));
+ expect(getNextTimeSelection(1, 'day', d, minDate, maxDate))
+ .toEqual(new Date(Date.UTC(2014, 5, 16)));
+ });
+
+ test('increments hour [next-time-hour]', () => {
+ const d = new Date(Date.UTC(2014, 5, 15, 10, 0));
+ expect(getNextTimeSelection(1, 'hour', d, minDate, maxDate))
+ .toEqual(new Date(Date.UTC(2014, 5, 15, 11, 0)));
+ });
+
+ test('increments minute [next-time-minute]', () => {
+ const d = new Date(Date.UTC(2014, 5, 15, 10, 30));
+ expect(getNextTimeSelection(1, 'minute', d, minDate, maxDate))
+ .toEqual(new Date(Date.UTC(2014, 5, 15, 10, 31)));
+ });
+
+ test('clamps to minDate when result is before min [next-time-clamp-min]', () => {
+ const d = new Date(Date.UTC(2000, 0, 2));
+ expect(getNextTimeSelection(-10, 'day', d, minDate, maxDate)).toEqual(minDate);
+ });
+
+ test('clamps to maxDate when result is after max [next-time-clamp-max]', () => {
+ const d = new Date(Date.UTC(2030, 11, 30));
+ expect(getNextTimeSelection(10, 'day', d, minDate, maxDate)).toEqual(maxDate);
});
});
-describe('daysInMonth', () => {
- test('feb, non-leap [date-non-leap]', () => {
- const d = new Date(Date.UTC(2015, 1, 15));
- expect(getDaysInMonth(d)).toBe(28);
+describe('tryCatchDate', () => {
+ test('returns parsed date for valid string [trycatch-valid]', () => {
+ const result = tryCatchDate('2022-01-15', new Date());
+ expect(result).toEqual(new Date(Date.UTC(2022, 0, 15)));
+ });
+
+ test('returns initialState for invalid string [trycatch-invalid]', () => {
+ const fallback = new Date('2020-01-01');
+ const result = tryCatchDate('not-a-date', fallback);
+ expect(result).toEqual(fallback);
+ });
+});
+
+describe('formatDisplayDate', () => {
+ test('formats daily date as YYYY MMM DD [format-display-date-daily]', () => {
+ const d = new Date(Date.UTC(2022, 0, 15));
+ expect(formatDisplayDate(d, false)).toBe('2022 JAN 15');
+ });
+
+ test('formats subdaily date with time and Z suffix [format-display-date-subdaily]', () => {
+ const d = new Date(Date.UTC(2022, 0, 15, 13, 45));
+ expect(formatDisplayDate(d, true)).toBe('2022 JAN 15 13:45Z');
+ });
+
+ test('returns undefined when date is null [format-display-date-null]', () => {
+ expect(formatDisplayDate(null)).toBeUndefined();
+ });
+
+ test('returns undefined when date is undefined [format-display-date-undefined]', () => {
+ expect(formatDisplayDate(undefined)).toBeUndefined();
+ });
+});
+
+describe('parseDate', () => {
+ test('parses a full ISO date+time string [parse-date-full]', () => {
+ const result = parseDate('2022-01-15T13:45:30Z');
+ expect(result.getFullYear()).toBe(2022);
+ expect(result.getMonth()).toBe(0);
+ expect(result.getDate()).toBe(15);
+ expect(result.getHours()).toBe(13);
+ expect(result.getMinutes()).toBe(45);
+ expect(result.getSeconds()).toBe(30);
+ });
+
+ test('parses date string without time component [parse-date-no-time]', () => {
+ const result = parseDate('2022-06-20T00:00:00Z');
+ expect(result.getFullYear()).toBe(2022);
+ expect(result.getMonth()).toBe(5);
+ expect(result.getDate()).toBe(20);
+ });
+
+ test('throws on completely invalid date string [parse-date-invalid]', () => {
+ expect(() => parseDate('not-a-date')).toThrow();
+ });
+
+ test('parses date with milliseconds [parse-date-milliseconds]', () => {
+ const result = parseDate('2022-01-15T10:30:00.500Z');
+ expect(result.getFullYear()).toBe(2022);
+ });
+});
+
+describe('serializeDate', () => {
+ test('serializes a UTC date to the expected format [serialize-date]', () => {
+ const d = new Date(Date.UTC(2022, 0, 15, 13, 45, 0));
+ const result = serializeDate(d);
+ expect(result).toBe('2022-01-15-T13:45:00Z');
+ });
+
+ test('serializes midnight correctly [serialize-date-midnight]', () => {
+ const d = new Date(Date.UTC(2020, 5, 1, 0, 0, 0));
+ expect(serializeDate(d)).toBe('2020-06-01-T00:00:00Z');
+ });
+});
+
+describe('filterProjLayersWithStartDate', () => {
+ test('filters layers with startDate and matching projection [filter-proj-layers]', () => {
+ const layers = [
+ { startDate: '2020-01-01', projections: { geographic: {} } },
+ { startDate: '2020-01-01', projections: { arctic: {} } },
+ { projections: { geographic: {} } },
+ ];
+ expect(filterProjLayersWithStartDate(layers, 'geographic')).toHaveLength(1);
+ });
+
+ test('returns empty array when no layers match [filter-proj-layers-empty]', () => {
+ expect(filterProjLayersWithStartDate([], 'geographic')).toEqual([]);
+ });
+
+ test('excludes layers without startDate [filter-proj-layers-no-startdate]', () => {
+ const layers = [{ projections: { geographic: {} } }];
+ expect(filterProjLayersWithStartDate(layers, 'geographic')).toHaveLength(0);
+ });
+
+ test('excludes layers without matching projection [filter-proj-layers-no-proj]', () => {
+ const layers = [{ startDate: '2020-01-01', projections: { arctic: {} } }];
+ expect(filterProjLayersWithStartDate(layers, 'geographic')).toHaveLength(0);
+ });
+});
+
+describe('getMaxLayerEndDates', () => {
+ test('returns end dates for layers with endDate [max-layer-end-dates]', () => {
+ const appNow = new Date('2022-01-01');
+ const layers = [{ endDate: '2021-06-01' }, { endDate: '2021-12-01' }];
+ const result = getMaxLayerEndDates(layers, appNow);
+ expect(result).toHaveLength(2);
+ expect(result[0]).toEqual(new Date('2021-06-01'));
+ });
+
+ test('uses appNow when layer has no endDate [max-layer-end-dates-fallback]', () => {
+ const appNow = new Date('2022-01-01');
+ const result = getMaxLayerEndDates([{ endDate: null }], appNow);
+ expect(result[0]).toEqual(appNow);
+ });
+
+ test('returns empty array for no layers [max-layer-end-dates-empty]', () => {
+ expect(getMaxLayerEndDates([], new Date())).toEqual([]);
+ });
+});
+
+describe('getLayersActiveAtDate', () => {
+ test('returns empty array when no layers are visible [layers-active-empty]', () => {
+ const date = new Date('2022-01-01');
+ const layers = [{ visible: false, startDate: '2020-01-01' }, { visible: true }];
+ expect(getLayersActiveAtDate(layers, date)).toEqual([]);
+ });
+
+ test('returns matching visible layer with startDate [layers-active-match]', () => {
+ const date = new Date('2022-01-01');
+ const layers = [{ visible: true, startDate: '2023-01-01' }];
+ const result = getLayersActiveAtDate(layers, date);
+ expect(Array.isArray(result)).toBe(true);
+ });
+});
+
+describe('formatISODate', () => {
+ test('formats a date to YYYY-MM-DD [format-iso-date]', () => {
+ const d = new Date(2022, 0, 15);
+ expect(formatISODate(d)).toBe('2022-01-15');
+ });
+
+ test('formats June correctly [format-iso-date-june]', () => {
+ const d = new Date(2020, 5, 1);
+ expect(formatISODate(d)).toBe('2020-06-01');
+ });
+});
+
+describe('mapLocationToDateState', () => {
+ test('returns unchanged state when no time or t param [date-parse-no-param]', () => {
+ let stateFromLocation = { date: { selected: state.date.selected } };
+ stateFromLocation = mapLocationToDateState({}, stateFromLocation, state);
+ expect(stateFromLocation.date.selected).toEqual(state.date.selected);
+ });
+
+ test('handles rt parameter for relative time [date-parse-rt]', () => {
+ const param = { rt: '-PT60M' };
+ let stateFromLocation = { date: {} };
+ stateFromLocation = mapLocationToDateState(param, stateFromLocation, state);
+ expect(stateFromLocation.date.selected).toBeDefined();
+ });
+
+ test('handles time param when t is not present [date-parse-time-legacy]', () => {
+ const d = new Date(Date.UTC(2013, 0, 5));
+ const param = { time: '2013-01-05' };
+ let stateFromLocation = { date: {} };
+ stateFromLocation = mapLocationToDateState(param, stateFromLocation, state);
+ expect(stateFromLocation.date.selected).toMatchObject(d);
+ });
+
+ test('ignores time param when t is also present [date-parse-time-ignored-with-t]', () => {
+ const param = { time: '2013-01-05', t: '2014-06-01' };
+ let stateFromLocation = { date: { selected: state.date.selected } };
+ stateFromLocation = mapLocationToDateState(param, stateFromLocation, state);
+ expect(stateFromLocation.date.selected).toEqual(state.date.selected);
+ });
+});
+
+describe('outOfStepChange', () => {
+ const testState = {
+ ...state,
+ date: { ...state.date, delta: 1, interval: 3, customSelected: false },
+ };
+
+ test('returns false when newDate is the next step [out-of-step-false]', () => {
+ const nextDate = getNextDateTime(testState, 1);
+ expect(outOfStepChange(testState, nextDate)).toBe(false);
+ });
+
+ test('returns false when newDate is the previous step [out-of-step-prev-false]', () => {
+ const prevDate = getNextDateTime(testState, -1);
+ expect(outOfStepChange(testState, prevDate)).toBe(false);
+ });
+
+ test('returns true when newDate is out of step [out-of-step-true]', () => {
+ const randomDate = new Date(Date.UTC(2000, 5, 17, 0, 0, 0));
+ expect(outOfStepChange(testState, randomDate)).toBe(true);
+ });
+});
+
+describe('getNumberStepsBetween', () => {
+ const testState = {
+ ...state,
+ date: { ...state.date, delta: 1, interval: 3, customSelected: false },
+ };
+
+ test('returns a number [steps-between-type]', () => {
+ const start = new Date(Date.UTC(2022, 0, 10));
+ const end = new Date(Date.UTC(2022, 0, 1));
+ expect(typeof getNumberStepsBetween(testState, start, end)).toBe('number');
+ });
+
+ test('returns positive when start is after end [steps-between-positive]', () => {
+ const start = new Date(Date.UTC(2022, 0, 10));
+ const end = new Date(Date.UTC(2022, 0, 1));
+ expect(getNumberStepsBetween(testState, start, end)).toBeGreaterThan(0);
+ });
+
+ test('returns negative when start is before end [steps-between-negative]', () => {
+ const start = new Date(Date.UTC(2022, 0, 1));
+ const end = new Date(Date.UTC(2022, 0, 10));
+ expect(getNumberStepsBetween(testState, start, end)).toBeLessThan(0);
+ });
+});
+
+describe('coverageDateFormatter', () => {
+ test('returns undefined when date is null [coverage-date-formatter-null]', () => {
+ expect(coverageDateFormatter('START-DATE', null, 'daily')).toBeUndefined();
+ });
+
+ test('returns undefined when date is undefined [coverage-date-formatter-undefined]', () => {
+ expect(coverageDateFormatter('START-DATE', undefined, 'subdaily')).toBeUndefined();
+ });
+
+ test('formats subdaily date [coverage-date-formatter-subdaily]', () => {
+ expect(coverageDateFormatter('START-DATE', '2022-01-15T13:45:00Z', 'subdaily')).toBeDefined();
+ });
+
+ test('formats yearly START-DATE [coverage-date-formatter-yearly-start]', () => {
+ expect(coverageDateFormatter('START-DATE', '2022-01-15T00:00:00Z', 'yearly')).toBeDefined();
+ });
+
+ test('formats yearly END-DATE [coverage-date-formatter-yearly-end]', () => {
+ expect(coverageDateFormatter('END-DATE', '2022-01-15T00:00:00Z', 'yearly')).toBeDefined();
+ });
+
+ test('formats monthly START-DATE [coverage-date-formatter-monthly-start]', () => {
+ expect(coverageDateFormatter('START-DATE', '2022-01-15T00:00:00Z', 'monthly')).toBeDefined();
+ });
+
+ test('formats monthly END-DATE [coverage-date-formatter-monthly-end]', () => {
+ expect(coverageDateFormatter('END-DATE', '2022-01-15T00:00:00Z', 'monthly')).toBeDefined();
+ });
+
+ test('formats default period [coverage-date-formatter-default]', () => {
+ expect(coverageDateFormatter('START-DATE', '2022-01-15T00:00:00Z', 'daily')).toBeDefined();
+ });
+});
+
+describe('parsePermalinkDate', () => {
+ const defaultDate = new Date(Date.UTC(2022, 5, 1));
+
+ test('returns startDate when parsed time is before startDate [permalink-before-start]', () => {
+ const cfg = { ...config, startDate: '2010-01-01' };
+ const result = parsePermalinkDate(defaultDate, '2000-01-01', null, cfg);
+ expect(result).toEqual(new Date(cfg.startDate));
+ });
+
+ test('returns parsed date when time is within valid range [permalink-in-range]', () => {
+ const cfg = { ...config, startDate: '2000-01-01' };
+ const result = parsePermalinkDate(defaultDate, '2015-06-15', null, cfg);
+ expect(result).toEqual(new Date(Date.UTC(2015, 5, 15)));
+ });
+
+ test('returns a Date when time is in future and no layer date range [permalink-future-no-range]', () => {
+ const cfg = { ...config, startDate: '2000-01-01' };
+ const result = parsePermalinkDate(defaultDate, '2099-01-01', null, cfg);
+ expect(result instanceof Date).toBe(true);
+ });
+
+ test('returns initialState when str is invalid [permalink-invalid-str]', () => {
+ const cfg = { ...config, startDate: '2000-01-01' };
+ const result = parsePermalinkDate(defaultDate, 'bad-date', null, cfg);
+ expect(result).toEqual(defaultDate);
+ });
+});
+
+describe('serializeDateWrapper', () => {
+ const initialDate = new Date(Date.UTC(2022, 0, 1));
+
+ test('returns undefined when animation is playing [serialize-wrapper-playing]', () => {
+ const s = {
+ ...state,
+ animation: { isPlaying: true },
+ config: { ...config, initialDate },
+ compare: { active: false, isCompareA: true },
+ date: { ...state.date, selected: initialDate },
+ };
+ expect(serializeDateWrapper(initialDate, s, {})).toBeUndefined();
+ });
+
+ test('returns undefined when no prev params and date is default [serialize-wrapper-default]', () => {
+ const s = {
+ ...state,
+ animation: { isPlaying: false },
+ config: { ...config, initialDate },
+ compare: { active: false, isCompareA: true },
+ date: { ...state.date, selected: initialDate },
+ };
+ expect(serializeDateWrapper(initialDate, s, {})).toBeUndefined();
+ });
+
+ test('returns serialized date when date differs from initial [serialize-wrapper-non-default]', () => {
+ const selected = new Date(Date.UTC(2022, 5, 15));
+ const s = {
+ ...state,
+ animation: { isPlaying: false },
+ config: { ...config, initialDate },
+ compare: { active: false, isCompareA: true },
+ date: { ...state.date, selected },
+ };
+ const result = serializeDateWrapper(selected, s, {});
+ expect(typeof result).toBe('string');
+ });
+
+ test('returns serialized dateB when compare exited with B selected [serialize-wrapper-dateb-selected]', () => {
+ const dateB = new Date(Date.UTC(2021, 3, 10));
+ const s = {
+ ...state,
+ animation: { isPlaying: false },
+ config: { ...config, initialDate },
+ compare: { active: false, isCompareA: false },
+ date: { ...state.date, selectedB: dateB },
+ };
+ const result = serializeDateWrapper(dateB, s, { someParam: true });
+ expect(typeof result).toBe('string');
+ });
+});
+
+describe('serializeDateBWrapper', () => {
+ const initialDate = new Date(Date.UTC(2022, 0, 1));
+
+ test('returns undefined when compare is not active [serialize-b-wrapper-inactive]', () => {
+ const s = {
+ ...state,
+ animation: { isPlaying: false },
+ config: { ...config, initialDate },
+ compare: { active: false },
+ date: { ...state.date },
+ };
+ expect(serializeDateBWrapper(initialDate, s, {})).toBeUndefined();
+ });
+
+ test('returns serialized date when compare is active and date differs from default [serialize-b-wrapper-active]', () => {
+ const dateB = new Date(Date.UTC(2021, 3, 10));
+ const s = {
+ ...state,
+ animation: { isPlaying: false },
+ config: { ...config, initialDate },
+ compare: { active: true },
+ date: { ...state.date, selectedB: dateB },
+ };
+ const result = serializeDateBWrapper(dateB, s, { someParam: true });
+ expect(typeof result).toBe('string');
+ });
+
+ test('returns undefined when compare active but date is default minus 7 days with no prev params [serialize-b-wrapper-default]', () => {
+ const s = {
+ ...state,
+ animation: { isPlaying: false },
+ config: { ...config, initialDate },
+ compare: { active: true },
+ date: { ...state.date },
+ };
+ const defaultB = new Date(Date.UTC(2021, 11, 25));
+ expect(serializeDateBWrapper(defaultB, s, {})).toBeUndefined();
+ });
+});
+
+describe('serializeDateChartingWrapper', () => {
+ test('returns undefined when charting is not active [serialize-charting-inactive]', () => {
+ const s = { ...state, charting: { active: false, timeSpanStartDate: null } };
+ expect(serializeDateChartingWrapper(new Date(), s)).toBeUndefined();
+ });
+
+ test('returns undefined when timeSpanStartDate is falsy [serialize-charting-no-start]', () => {
+ const s = { ...state, charting: { active: true, timeSpanStartDate: null } };
+ expect(serializeDateChartingWrapper(new Date(), s)).toBeUndefined();
+ });
+
+ test('returns serialized date when charting is active with timeSpanStartDate [serialize-charting-active]', () => {
+ const d = new Date(Date.UTC(2022, 0, 15));
+ const s = { ...state, charting: { active: true, timeSpanStartDate: d } };
+ const result = serializeDateChartingWrapper(d, s);
+ expect(typeof result).toBe('string');
+ });
+});
+
+describe('checkHasFutureLayers', () => {
+ test('returns false when no future layers in non-compare mode [has-future-layers-false]', () => {
+ expect(checkHasFutureLayers(state)).toBe(false);
+ });
+
+ test('returns false when compare active and no future layers [has-future-layers-compare-false]', () => {
+ const s = {
+ ...state,
+ compare: { ...state.compare, active: true },
+ layers: {
+ ...state.layers,
+ active: { layers: [] },
+ activeB: { layers: [] },
+ },
+ };
+ expect(checkHasFutureLayers(s)).toBe(false);
+ });
+});
+
+describe('getNextImageryDelta', () => {
+ test('returns 1 when all layers are invalid (no dateRanges) [imagery-delta-invalid]', () => {
+ const layers = [{ visible: true }, { visible: false }];
+ expect(getNextImageryDelta(layers, '2022-01-01T00:00:00Z', 1)).toBe(1);
+ });
+
+ test('returns 1 when layers array is empty [imagery-delta-empty]', () => {
+ expect(getNextImageryDelta([], '2022-01-01T00:00:00Z', 1)).toBe(1);
+ });
+
+ test('returns delta from tempoDateRanges when present [imagery-delta-tempo]', () => {
+ const layers = [{
+ visible: true,
+ tempoDateRanges: [{
+ startDate: '2022-01-01T00:00:00Z',
+ endDate: '2022-01-01T00:10:00Z',
+ dateInterval: '10',
+ }],
+ }];
+ const result = getNextImageryDelta(layers, '2021-12-31T00:00:00Z', 1);
+ expect(typeof result).toBe('number');
+ });
+
+ test('returns delta from dateRanges when present [imagery-delta-dateranges]', () => {
+ const layers = [{
+ visible: true,
+ dateRanges: [{
+ startDate: '2022-01-01T00:00:00Z',
+ endDate: '2022-01-01T01:00:00Z',
+ dateInterval: '60',
+ }],
+ }];
+ const result = getNextImageryDelta(layers, '2021-12-31T00:00:00Z', 1);
+ expect(typeof result).toBe('number');
+ });
+
+ test('handles granuleDateRanges with explicit interval [imagery-delta-granule-with-interval]', () => {
+ const layers = [{
+ visible: true,
+ granuleDateRanges: [
+ ['2022-01-01T00:00:00Z', '2022-01-01T00:10:00Z', '10'],
+ ],
+ }];
+ const result = getNextImageryDelta(layers, '2021-12-31T00:00:00Z', 1);
+ expect(typeof result).toBe('number');
+ });
+
+ test('handles granuleDateRanges without explicit interval (CMR derived) [imagery-delta-granule-no-interval]', () => {
+ const layers = [{
+ visible: true,
+ granuleDateRanges: [
+ ['2022-01-01T00:00:00Z', '2022-01-01T01:00:00Z', null],
+ ],
+ }];
+ const result = getNextImageryDelta(layers, '2021-12-31T00:00:00Z', 1);
+ expect(typeof result).toBe('number');
+ });
+
+ test('handles backward direction (signConstant < 0) [imagery-delta-backward]', () => {
+ const layers = [{
+ visible: true,
+ dateRanges: [{
+ startDate: '2021-01-01T00:00:00Z',
+ endDate: '2021-12-31T00:00:00Z',
+ dateInterval: '60',
+ }],
+ }];
+ const result = getNextImageryDelta(layers, '2022-01-01T00:00:00Z', -1);
+ expect(typeof result).toBe('number');
});
- test('feb, leap [date-leap]', () => {
- const d = new Date(Date.UTC(2016, 1, 15));
- expect(getDaysInMonth(d)).toBe(29);
+ test('skips layer with no dateRanges and counts as invalid [imagery-delta-no-ranges-visible]', () => {
+ const result = getNextImageryDelta([{ visible: true }], '2022-01-01T00:00:00Z', 1);
+ expect(result).toBe(1);
});
});
diff --git a/web/js/modules/embed/reducers.test.js b/web/js/modules/embed/reducers.test.js
new file mode 100644
index 000000000..d44cad7fd
--- /dev/null
+++ b/web/js/modules/embed/reducers.test.js
@@ -0,0 +1,51 @@
+import embedReducers, { embedState } from './reducers';
+
+describe('embedState', () => {
+ test('has isEmbedModeActive set to false by default [embed-state-default]', () => {
+ expect(embedState.isEmbedModeActive).toBe(false);
+ });
+
+ test('has exactly one key [embed-state-shape]', () => {
+ expect(Object.keys(embedState)).toEqual(['isEmbedModeActive']);
+ });
+});
+
+describe('embedReducers', () => {
+ test('returns the initial embedState when called with no state [embed-reducer-initial]', () => {
+ const result = embedReducers(undefined, {});
+ expect(result).toEqual(embedState);
+ });
+
+ test('returns the initial embedState when called with an empty action [embed-reducer-empty-action]', () => {
+ const result = embedReducers(embedState, {});
+ expect(result).toEqual(embedState);
+ });
+
+ test('returns existing state unchanged for unknown action type [embed-reducer-unknown-action]', () => {
+ const result = embedReducers(embedState, { type: 'UNKNOWN_ACTION' });
+ expect(result).toEqual(embedState);
+ });
+
+ test('returns existing state unchanged for any action [embed-reducer-any-action]', () => {
+ const result = embedReducers(embedState, { type: 'SOME_OTHER_ACTION', payload: 123 });
+ expect(result).toBe(embedState);
+ });
+
+ test('preserves a custom state passed in [embed-reducer-custom-state]', () => {
+ const customState = { isEmbedModeActive: true };
+ const result = embedReducers(customState, { type: 'UNKNOWN' });
+ expect(result).toEqual(customState);
+ expect(result.isEmbedModeActive).toBe(true);
+ });
+
+ test('does not mutate the state object [embed-reducer-no-mutation]', () => {
+ const customState = { isEmbedModeActive: true };
+ const result = embedReducers(customState, { type: 'UNKNOWN' });
+ expect(result).toBe(customState);
+ });
+
+ test('isEmbedModeActive is false in initial state [embed-reducer-initial-false]', () => {
+ const result = embedReducers(undefined, {});
+ expect(result.isEmbedModeActive).toBe(false);
+ });
+});
diff --git a/web/js/modules/embed/util.test.js b/web/js/modules/embed/util.test.js
index 4072f4f95..daa84f9a9 100644
--- a/web/js/modules/embed/util.test.js
+++ b/web/js/modules/embed/util.test.js
@@ -1,3 +1,171 @@
-test('util module test', () => {
+import { mapLocationToEmbedState } from './util';
+const visibleLayer = { id: 'layer-a', visible: true, group: 'overlays' };
+const hiddenLayer = { id: 'layer-b', visible: false, group: 'overlays' };
+const referenceLayer = { id: 'layer-ref', visible: true, group: 'overlays' };
+
+const baseStateFromLocation = {
+ embed: { isEmbedModeActive: false },
+ layers: {
+ active: {
+ layers: [visibleLayer, hiddenLayer],
+ overlayGroups: [],
+ },
+ activeB: {
+ layers: [visibleLayer, hiddenLayer],
+ overlayGroups: [],
+ },
+ },
+};
+
+describe('mapLocationToEmbedState', () => {
+ test('returns stateFromLocation unchanged when em parameter is not "true" [embed-util-no-em]', () => {
+ const result = mapLocationToEmbedState({}, baseStateFromLocation);
+ expect(result).toBe(baseStateFromLocation);
+ });
+
+ test('returns stateFromLocation unchanged when em is absent [embed-util-em-absent]', () => {
+ const result = mapLocationToEmbedState({ em: undefined }, baseStateFromLocation);
+ expect(result).toBe(baseStateFromLocation);
+ });
+
+ test('returns stateFromLocation unchanged when em is "false" [embed-util-em-false]', () => {
+ const result = mapLocationToEmbedState({ em: 'false' }, baseStateFromLocation);
+ expect(result).toBe(baseStateFromLocation);
+ });
+
+ test('sets isEmbedModeActive to true when em is "true" [embed-util-em-true]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ expect(result.embed.isEmbedModeActive).toBe(true);
+ });
+
+ test('does not mutate the original stateFromLocation [embed-util-no-mutation]', () => {
+ mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ expect(baseStateFromLocation.embed.isEmbedModeActive).toBe(false);
+ });
+
+ test('filters out invisible layers from active when em is "true" [embed-util-filters-active-invisible]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ expect(result.layers.active.layers.every((l) => l.visible)).toBe(true);
+ });
+
+ test('filters out invisible layers from activeB when em is "true" [embed-util-filters-activeb-invisible]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ expect(result.layers.activeB.layers.every((l) => l.visible)).toBe(true);
+ });
+
+ test('hidden layer is excluded from active.layers [embed-util-hidden-excluded-active]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ const ids = result.layers.active.layers.map((l) => l.id);
+ expect(ids).not.toContain(hiddenLayer.id);
+ });
+
+ test('hidden layer is excluded from activeB.layers [embed-util-hidden-excluded-activeb]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ const ids = result.layers.activeB.layers.map((l) => l.id);
+ expect(ids).not.toContain(hiddenLayer.id);
+ });
+
+ test('visible layer is retained in active.layers [embed-util-visible-retained-active]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ const ids = result.layers.active.layers.map((l) => l.id);
+ expect(ids).toContain(visibleLayer.id);
+ });
+
+ test('visible layer is retained in activeB.layers [embed-util-visible-retained-activeb]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ const ids = result.layers.activeB.layers.map((l) => l.id);
+ expect(ids).toContain(visibleLayer.id);
+ });
+
+ test('Reference overlay group is removed from active.overlayGroups [embed-util-reference-removed-active]', () => {
+ const stateWithReference = {
+ ...baseStateFromLocation,
+ layers: {
+ active: {
+ layers: [visibleLayer, referenceLayer],
+ overlayGroups: [
+ { groupName: 'Reference', layers: [referenceLayer] },
+ { groupName: 'Overlays', layers: [visibleLayer] },
+ ],
+ },
+ activeB: {
+ layers: [visibleLayer],
+ overlayGroups: [
+ { groupName: 'Overlays', layers: [visibleLayer] },
+ ],
+ },
+ },
+ };
+ const result = mapLocationToEmbedState({ em: 'true' }, stateWithReference);
+ const groupNames = result.layers.active.overlayGroups.map((g) => g.groupName);
+ expect(groupNames).not.toContain('Reference');
+ });
+
+ test('Reference overlay group is removed from activeB.overlayGroups [embed-util-reference-removed-activeb]', () => {
+ const stateWithReference = {
+ ...baseStateFromLocation,
+ layers: {
+ active: {
+ layers: [visibleLayer],
+ overlayGroups: [{ groupName: 'Overlays', layers: [visibleLayer] }],
+ },
+ activeB: {
+ layers: [visibleLayer, referenceLayer],
+ overlayGroups: [
+ { groupName: 'Reference', layers: [referenceLayer] },
+ { groupName: 'Overlays', layers: [visibleLayer] },
+ ],
+ },
+ },
+ };
+ const result = mapLocationToEmbedState({ em: 'true' }, stateWithReference);
+ const groupNames = result.layers.activeB.overlayGroups.map((g) => g.groupName);
+ expect(groupNames).not.toContain('Reference');
+ });
+
+ test('result layers object is a deep clone, not the original [embed-util-deep-clone]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ expect(result.layers).not.toBe(baseStateFromLocation.layers);
+ expect(result.layers.active).not.toBe(baseStateFromLocation.layers.active);
+ });
+
+ test('returns a new object reference when em is "true" [embed-util-new-reference]', () => {
+ const result = mapLocationToEmbedState({ em: 'true' }, baseStateFromLocation);
+ expect(result).not.toBe(baseStateFromLocation);
+ });
+
+ test('handles empty active layers array when em is "true" [embed-util-empty-active]', () => {
+ const emptyState = {
+ ...baseStateFromLocation,
+ layers: {
+ active: { layers: [], overlayGroups: [] },
+ activeB: { layers: [], overlayGroups: [] },
+ },
+ };
+ const result = mapLocationToEmbedState({ em: 'true' }, emptyState);
+ expect(result.layers.active.layers).toEqual([]);
+ expect(result.layers.activeB.layers).toEqual([]);
+ expect(result.embed.isEmbedModeActive).toBe(true);
+ });
+
+ test('preserves other stateFromLocation properties when em is "true" [embed-util-preserves-other-state]', () => {
+ const stateWithExtra = {
+ ...baseStateFromLocation,
+ date: { selected: new Date('2022-01-01') },
+ compare: { active: false },
+ };
+ const result = mapLocationToEmbedState({ em: 'true' }, stateWithExtra);
+ expect(result.date).toEqual(stateWithExtra.date);
+ expect(result.compare).toEqual(stateWithExtra.compare);
+ });
+
+ test('preserves other stateFromLocation properties when em is not "true" [embed-util-preserves-state-no-em]', () => {
+ const stateWithExtra = {
+ ...baseStateFromLocation,
+ date: { selected: new Date('2022-01-01') },
+ };
+ const result = mapLocationToEmbedState({}, stateWithExtra);
+ expect(result.date).toEqual(stateWithExtra.date);
+ });
});
diff --git a/web/js/modules/feedback/actions.test.js b/web/js/modules/feedback/actions.test.js
new file mode 100644
index 000000000..85e123de9
--- /dev/null
+++ b/web/js/modules/feedback/actions.test.js
@@ -0,0 +1,9 @@
+import actions from './actions';
+
+describe('InitFeedback actions', () => {
+ it('Call initFeedback and return INITIATE _FEEDBACK_MODULE', () => {
+ expect(actions()).toEqual({
+ type: 'INITIATE_FEEDBACK_MODULE',
+ });
+ });
+});
diff --git a/web/js/modules/feedback/reducers.test.js b/web/js/modules/feedback/reducers.test.js
index 04cce6a78..30773843d 100644
--- a/web/js/modules/feedback/reducers.test.js
+++ b/web/js/modules/feedback/reducers.test.js
@@ -1,3 +1,23 @@
-test('reducers module test', () => {
+import { assign as lodashAssign } from 'lodash';
+import { INIT_FEEDBACK } from './constants';
+import feedbackReducer from './reducers';
+describe('feedbackReducer', () => {
+ it('should return the initial state', () => {
+ const expected = feedbackReducer(undefined, {});
+ expect(expected).toEqual({
+ isInitiated: false,
+ });
+ });
+
+ it('should handle INIT_FEEDBACK', () => {
+ const expected = feedbackReducer(undefined, {
+ type: INIT_FEEDBACK,
+ });
+ expect(expected).toEqual(lodashAssign({}, {
+ isInitiated: false,
+ }, {
+ isInitiated: true,
+ }));
+ });
});
diff --git a/web/js/modules/feedback/util.test.js b/web/js/modules/feedback/util.test.js
index 4072f4f95..3cb5246b4 100644
--- a/web/js/modules/feedback/util.test.js
+++ b/web/js/modules/feedback/util.test.js
@@ -1,3 +1,30 @@
-test('util module test', () => {
+import onClickFeedback from './util';
+describe('onClickFeedback', () => {
+ it('should call feedback.init and feedback.showForm if not initiated and feedback is defined', () => {
+ window.feedback = {
+ init: jest.fn(),
+ showForm: jest.fn(),
+ };
+ onClickFeedback(false, false);
+ expect(window.feedback.init).toHaveBeenCalledWith({
+ showIcon: false,
+ });
+ expect(window.feedback.showForm).toHaveBeenCalled();
+ });
+
+ it('should call feedback.showForm if already initiated and feedback is defined', () => {
+ window.feedback = {
+ init: jest.fn(),
+ showForm: jest.fn(),
+ };
+ onClickFeedback(true, false);
+ expect(window.feedback.init).not.toHaveBeenCalled();
+ expect(window.feedback.showForm).toHaveBeenCalled();
+ });
+
+ it('should not call feedback methods if feedback is not defined', () => {
+ delete window.feedback;
+ onClickFeedback(false, false);
+ });
});
diff --git a/web/js/modules/image-download/actions.test.js b/web/js/modules/image-download/actions.test.js
index 22bc698b0..eac05e917 100644
--- a/web/js/modules/image-download/actions.test.js
+++ b/web/js/modules/image-download/actions.test.js
@@ -1,3 +1,39 @@
-test('actions module test', () => {
+import { updateBoundaries, onPanelChange } from './actions';
+describe('actions module', () => {
+ it('should create an action to update boundaries', () => {
+ const boundaries = { left: 1, right: 2, top: 3, bottom: 4 };
+ const expectedAction = {
+ type: 'IMAGE-DOWNLOAD/UPDATE_BOUNDARIES',
+ boundaries,
+ };
+ expect(updateBoundaries(boundaries)).toEqual(expectedAction);
+ });
+
+ it('should create an action to update file type', () => {
+ const value = 'png';
+ const expectedAction = {
+ type: 'IMAGE-DOWNLOAD/UPDATE_FILE_TYPE',
+ value,
+ };
+ expect(onPanelChange('fileType', value)).toEqual(expectedAction);
+ });
+
+ it('should create an action to update resolution', () => {
+ const value = '300';
+ const expectedAction = {
+ type: 'IMAGE-DOWNLOAD/UPDATE_RESOLUTION',
+ value,
+ };
+ expect(onPanelChange('resolution', value)).toEqual(expectedAction);
+ });
+
+ it('should create an action to update worldfile', () => {
+ const value = true;
+ const expectedAction = {
+ type: 'IMAGE-DOWNLOAD/UPDATE_WORLDFILE',
+ value,
+ };
+ expect(onPanelChange('worldfile', value)).toEqual(expectedAction);
+ });
});
diff --git a/web/js/modules/image-download/reducers.test.js b/web/js/modules/image-download/reducers.test.js
index 04cce6a78..0729bd886 100644
--- a/web/js/modules/image-download/reducers.test.js
+++ b/web/js/modules/image-download/reducers.test.js
@@ -1,3 +1,63 @@
-test('reducers module test', () => {
+import { imageDownloadReducer, defaultState } from './reducers';
+import { assign as lodashAssign } from 'lodash';
+import {
+ UPDATE_BOUNDARIES,
+ UPDATE_FILE_TYPE,
+ UPDATE_WORLDFILE,
+ UPDATE_RESOLUTION,
+} from './constants';
+import { CHANGE_PROJECTION } from '../projection/constants';
+describe('imageDownloadReducer', () => {
+ it('should return the default state', () => {
+ expect(imageDownloadReducer(undefined, {})).toEqual(defaultState);
+ });
+ it('should update boundaries', () => {
+ const boundaries = [1, 2, 3, 4];
+ expect(imageDownloadReducer(undefined, {
+ type: UPDATE_BOUNDARIES,
+ boundaries,
+ })).toEqual(lodashAssign({}, defaultState, { boundaries }));
+ });
+
+ it('should update file type', () => {
+ const fileType = 'image/png';
+ expect(imageDownloadReducer(undefined, {
+ type: UPDATE_FILE_TYPE,
+ value: fileType,
+ })).toEqual(lodashAssign({}, defaultState, { fileType }));
+ });
+
+ it('should update worldfile', () => {
+ const isWorldfile = true;
+ expect(imageDownloadReducer(undefined, {
+ type: UPDATE_WORLDFILE,
+ value: isWorldfile,
+ })).toEqual(lodashAssign({}, defaultState, { isWorldfile }));
+ });
+
+ it('should update resolution', () => {
+ const resolution = '10';
+ expect(imageDownloadReducer(undefined, {
+ type: UPDATE_RESOLUTION,
+ value: resolution,
+ })).toEqual(lodashAssign({}, defaultState, { resolution }));
+ });
+
+ it('should change projection and reset to default state', () => {
+ const selected = 'geographic';
+ expect(imageDownloadReducer(undefined, {
+ type: CHANGE_PROJECTION,
+ selected,
+ })).toEqual(defaultState);
+ });
+
+ it('should change projection and reset to default state with file type image/jpeg', () => {
+ const selected = 'polar';
+ const fileType = 'image/png';
+ expect(imageDownloadReducer(lodashAssign({}, defaultState, { fileType }), {
+ type: CHANGE_PROJECTION,
+ selected,
+ })).toEqual(lodashAssign({}, defaultState, { fileType: 'image/png' }));
+ });
});