Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

Fix for web/js/containers/sidebar/smart-handoff.test.js

Jason Hurley2d3e3026238f
diff --git a/web/js/containers/sidebar/smart-handoff.test.js b/web/js/containers/sidebar/smart-handoff.test.js
index c3508b4e1..606bcf825 100644
--- a/web/js/containers/sidebar/smart-handoff.test.js
+++ b/web/js/containers/sidebar/smart-handoff.test.js
@@ -1,21 +1,11 @@
/* eslint-disable react/prop-types */
-import React from 'react';
-import { render, fireEvent, act } from '@testing-library/react';
+import {
+ render, fireEvent, act,
+} from '@testing-library/react';
+import { Provider } from 'react-redux';
+import configureMockStore from 'redux-mock-store';
import '@testing-library/jest-dom';
-// ─── Mocks ───────────────────────────────────────────────────────────────────
-jest.mock('react-redux', () => {
- const actual = jest.requireActual('react-redux');
- const capture = {};
- const mockConnect = (msp, mdp) => {
- capture.msp = msp;
- capture.mdp = mdp;
- return (Component) => Component;
- };
- mockConnect.connectCapture = capture;
- return { ...actual, connect: mockConnect };
-});
-
jest.mock('googleTagManager', () => ({ pushEvent: jest.fn() }), { virtual: true });
jest.mock('ol/proj', () => ({
@@ -120,13 +110,14 @@ jest.mock(
);
jest.mock('../../components/smart-handoffs/granule-count', () => function MockGranuleCount({
- displayDate, selectedCollection,
+ displayDate, selectedCollection, showGranuleHelpModal,
}) {
const React = require('react');
return React.createElement('div', {
'data-testid': 'granule-count',
'data-display-date': displayDate,
'data-collection': selectedCollection ? selectedCollection.value : '',
+ onClick: showGranuleHelpModal,
});
});
@@ -144,8 +135,8 @@ jest.mock('../../modules/layers/selectors', () => ({
}));
jest.mock('../../modules/smart-handoff/selectors', () => ({
- getValidLayersForHandoffs: jest.fn(() => []),
- getConceptUrl: jest.fn(() => jest.fn((val) => `https://cmr.example.com/${val}`)),
+ getValidLayersForHandoffs: jest.fn((state) => state.smartHandoffs.availableLayers),
+ getConceptUrl: jest.fn(() => (val) => `https://cmr.example.com/${val}`),
getGranulesUrl: jest.fn(() => jest.fn()),
}));
@@ -194,40 +185,22 @@ jest.mock('../../util/util', () => ({
}));
jest.mock('../../modules/date/util', () => ({
- formatDisplayDate: jest.fn((date) => '2020 JAN 01'),
+ formatDisplayDate: jest.fn(() => '2020 JAN 01'),
}));
-// ─── Imports after mocks ──────────────────────────────────────────────────────
-
import SmartHandoff from './smart-handoff';
import googleTagManager from 'googleTagManager';
import safeLocalStorage from '../../util/local-storage';
import openEarthDataSearch from '../../modules/smart-handoff/util';
import { openCustomContent } from '../../modules/modal/actions';
-import {
- selectCollection as selectCollectionAction,
- fetchAvailableTools as fetchAvailableToolsAction,
- validateLayersConceptIds as validateLayersConceptIdsAction,
-} from '../../modules/smart-handoff/actions';
-
-// ─── Shared captured connect ──────────────────────────────────────────────────
-let capturedMapStateToProps;
-let capturedMapDispatchToProps;
-
-beforeAll(() => {
- const { connect } = jest.requireMock('react-redux');
- capturedMapStateToProps = connect.connectCapture.msp;
- capturedMapDispatchToProps = connect.connectCapture.mdp;
-});
+const mockStore = configureMockStore();
beforeEach(() => {
jest.clearAllMocks();
safeLocalStorage.getItem.mockReturnValue(null);
});
-// ─── Fixtures ─────────────────────────────────────────────────────────────────
-
const layer1 = {
id: 'layer1',
title: 'Layer One',
@@ -239,93 +212,105 @@ const layer1 = {
],
};
-const defaultProps = {
- availableLayers: [layer1],
- availableTools: [],
- displayDate: '2020 JAN 01',
- isLoading: false,
- isGranuleLayer: false,
- endDate: '2020-01-01T23:59:59.999Z',
- startDate: '2020-01-01T00:00:00.000Z',
- getConceptUrl: jest.fn((val) => `https://cmr.example.com/${val}`),
- getGranulesUrl: jest.fn(),
- granuleLayers: {},
- map: {
- ui: { selected: {} },
- extent: [-180, -90, 180, 90],
- },
- proj: {
- id: 'geographic',
- crs: 'EPSG:4326',
- maxExtent: [-180, -90, 180, 90],
- },
- fetchAvailableTools: jest.fn(),
- requestFailed: false,
- screenHeight: 800,
- screenWidth: 1200,
- selectCollection: jest.fn(),
- selectedDate: '2020-01-01',
- selectedLayer: layer1,
- selectedCollection: { type: 'STD', value: 'C1-STD', version: '6.0', title: 'Layer One' },
- showWarningModal: jest.fn(),
- showGranuleHelpModal: jest.fn(),
- showNotAvailableModal: jest.fn(),
- validatedLayers: [layer1],
- validatedConceptIds: { 'C1-STD': true, 'C1-NRT': true },
- validateLayersConceptIds: jest.fn(),
+const geographicProj = {
+ id: 'geographic',
+ crs: 'EPSG:4326',
+ maxExtent: [-180, -90, 180, 90],
};
-const renderComponent = (propOverrides = {}) => render(
- React.createElement(SmartHandoff, { ...defaultProps, ...propOverrides }),
-);
+const arcticProj = { id: 'arctic', crs: 'EPSG:3413', maxExtent: [-180, 60, 180, 90] };
-// ─── Loading state ────────────────────────────────────────────────────────────
+const buildState = (overrides = {}) => {
+ const { smartHandoffs = {}, map = {}, proj = {}, ...rest } = overrides;
+ return {
+ screenSize: { screenWidth: 1200, screenHeight: 800 },
+ map: {
+ ui: { selected: {} },
+ extent: [-180, -90, 180, 90],
+ ...map,
+ },
+ proj: { selected: { ...geographicProj, ...proj.selected } },
+ smartHandoffs: {
+ conceptId: 'C1-STD',
+ layerId: 'layer1',
+ availableLayers: [layer1],
+ availableTools: [],
+ validatedConceptIds: { 'C1-STD': true, 'C1-NRT': true },
+ validatedLayers: [layer1],
+ isLoadingTools: false,
+ isValidatingCollections: false,
+ requestFailed: false,
+ ...smartHandoffs,
+ },
+ date: {},
+ layers: {},
+ config: {},
+ ...rest,
+ };
+};
+
+const renderComponent = (stateOverrides = {}) => {
+ const store = mockStore(buildState(stateOverrides));
+ const utils = render(
+ <Provider store={store}>
+ <SmartHandoff />
+ </Provider>,
+ );
+ return { ...utils, store };
+};
+
+const actionsOfType = (store, type) => store.getActions().filter((a) => a.type === type);
+const findCustomContent = (store, id) => store
+ .getActions()
+ .find((a) => a.type === 'OPEN_CUSTOM_CONTENT' && a.id === id);
describe('SmartHandoff loading state', () => {
- it('renders spinner when isLoading is true', () => {
- const { getByTestId } = renderComponent({ isLoading: true });
+ it('renders spinner when isLoadingTools is true', () => {
+ const { getByTestId } = renderComponent({ smartHandoffs: { isLoadingTools: true } });
+ expect(getByTestId('spinner')).toBeInTheDocument();
+ });
+
+ it('renders spinner when isValidatingCollections is true', () => {
+ const { getByTestId } = renderComponent({ smartHandoffs: { isValidatingCollections: true } });
expect(getByTestId('spinner')).toBeInTheDocument();
});
it('does not render panel when loading', () => {
- renderComponent({ isLoading: true });
+ renderComponent({ smartHandoffs: { isLoadingTools: true } });
expect(document.querySelector('.smart-handoff-side-panel')).not.toBeInTheDocument();
});
});
-// ─── No layers state ─────────────────────────────────────────────────────────
-
describe('SmartHandoff no layers state', () => {
it('renders no-layers panel when validatedLayers is empty', () => {
- const { container } = renderComponent({ validatedLayers: [] });
+ const { container } = renderComponent({ smartHandoffs: { validatedLayers: [] } });
expect(container.querySelector('.smart-handoff-side-panel.error')).toBeInTheDocument();
});
it('renders CMR error message when requestFailed is true', () => {
- const { getByText } = renderComponent({ validatedLayers: [], requestFailed: true });
+ const { getByText } = renderComponent({
+ smartHandoffs: { validatedLayers: [], requestFailed: true },
+ });
expect(getByText(/Common Metadata Repository/)).toBeInTheDocument();
});
it('renders not-available message when requestFailed is false', () => {
- const { getByText } = renderComponent({ validatedLayers: [] });
+ const { getByText } = renderComponent({ smartHandoffs: { validatedLayers: [] } });
expect(getByText(/None of your current layers are available/)).toBeInTheDocument();
});
it('renders help link when requestFailed is false', () => {
- const { getByText } = renderComponent({ validatedLayers: [] });
+ const { getByText } = renderComponent({ smartHandoffs: { validatedLayers: [] } });
expect(getByText(/Why are my layers not available/)).toBeInTheDocument();
});
- it('calls showNotAvailableModal when help link is clicked in no-layers view', () => {
- const showNotAvailableModal = jest.fn();
- const { getByText } = renderComponent({ validatedLayers: [], showNotAvailableModal });
+ it('dispatches not-available modal when help link is clicked in no-layers view', () => {
+ const { getByText, store } = renderComponent({ smartHandoffs: { validatedLayers: [] } });
fireEvent.click(getByText(/Why are my layers not available/));
- expect(showNotAvailableModal).toHaveBeenCalled();
+ expect(findCustomContent(store, 'layers-not-available')).toBeTruthy();
});
});
-// ─── Main panel rendering ─────────────────────────────────────────────────────
-
describe('SmartHandoff main panel', () => {
it('renders the side panel', () => {
const { container } = renderComponent();
@@ -342,11 +327,14 @@ describe('SmartHandoff main panel', () => {
expect(getByText(/Why are some layers not available/)).toBeInTheDocument();
});
- it('calls showNotAvailableModal when help link is clicked', () => {
- const showNotAvailableModal = jest.fn();
- const { getByText } = renderComponent({ showNotAvailableModal });
+ it('dispatches not-available modal when help link is clicked', () => {
+ const { getByText, store } = renderComponent();
fireEvent.click(getByText(/Why are some layers not available/));
- expect(showNotAvailableModal).toHaveBeenCalled();
+ const action = findCustomContent(store, 'layers-not-available');
+ expect(action).toBeTruthy();
+ expect(action.opts).toEqual(
+ expect.objectContaining({ headerText: 'Data Download Availability' }),
+ );
});
it('renders download button', () => {
@@ -360,12 +348,12 @@ describe('SmartHandoff main panel', () => {
});
it('download button is not valid when no selectedLayer', () => {
- const { getByTestId } = renderComponent({ selectedLayer: null, selectedCollection: null });
+ const { getByTestId } = renderComponent({ smartHandoffs: { layerId: 'nonexistent' } });
expect(getByTestId('download-btn')).toHaveAttribute('data-valid', 'false');
});
it('download button is not valid when no selectedCollection', () => {
- const { getByTestId } = renderComponent({ selectedCollection: null });
+ const { getByTestId } = renderComponent({ smartHandoffs: { conceptId: 'NO-MATCH' } });
expect(getByTestId('download-btn')).toHaveAttribute('data-valid', 'false');
});
@@ -375,13 +363,11 @@ describe('SmartHandoff main panel', () => {
});
it('does not render GranuleCount when no selectedLayer', () => {
- const { queryByTestId } = renderComponent({ selectedLayer: null, selectedCollection: null });
+ const { queryByTestId } = renderComponent({ smartHandoffs: { layerId: 'nonexistent' } });
expect(queryByTestId('granule-count')).not.toBeInTheDocument();
});
});
-// ─── renderLayerChoices ───────────────────────────────────────────────────────
-
describe('renderLayerChoices', () => {
it('renders layer list div', () => {
const { container } = renderComponent();
@@ -420,13 +406,11 @@ describe('renderLayerChoices', () => {
expect(getByText(/Near Real-Time/)).toBeInTheDocument();
});
- it('calls selectCollection when unselected radio is clicked', () => {
- const selectCollection = jest.fn();
- const { container } = renderComponent({ selectCollection });
- // First radio is already checked; click the second (unselected) one to trigger onChange
+ it('dispatches selectCollection when unselected radio is clicked', () => {
+ const { container, store } = renderComponent();
const radios = container.querySelectorAll('input[type="radio"]');
fireEvent.click(radios[1]);
- expect(selectCollection).toHaveBeenCalled();
+ expect(actionsOfType(store, 'SELECT_COLLECTION').length).toBeGreaterThan(0);
});
it('selected item has selected class when layerIsSelected', () => {
@@ -436,7 +420,7 @@ describe('renderLayerChoices', () => {
it('does not filter out conceptIds with validated value', () => {
const { container } = renderComponent({
- validatedConceptIds: { 'C1-STD': true },
+ smartHandoffs: { validatedConceptIds: { 'C1-STD': true } },
});
const radios = container.querySelectorAll('input[type="radio"]');
expect(radios.length).toBe(1);
@@ -453,15 +437,16 @@ describe('renderLayerChoices', () => {
conceptIds: [{ type: 'STD', value: '' }],
};
const { queryAllByTestId } = renderComponent({
- validatedLayers: [noValueLayer],
- validatedConceptIds: { '': true },
+ smartHandoffs: {
+ availableLayers: [noValueLayer],
+ validatedLayers: [noValueLayer],
+ validatedConceptIds: { '': true },
+ },
});
expect(queryAllByTestId('tooltip').length).toBe(0);
});
});
-// ─── renderCropBox ────────────────────────────────────────────────────────────
-
describe('renderCropBox', () => {
it('renders checkbox when selectedLayer, selectedCollection and geographic proj', () => {
const { getByTestId } = renderComponent();
@@ -469,12 +454,12 @@ describe('renderCropBox', () => {
});
it('does not render checkbox when proj is not geographic', () => {
- const { queryByTestId } = renderComponent({ proj: { id: 'arctic', crs: 'EPSG:3413', maxExtent: [-180, 60, 180, 90] } });
+ const { queryByTestId } = renderComponent({ proj: { selected: arcticProj } });
expect(queryByTestId('crop-checkbox')).not.toBeInTheDocument();
});
it('does not render checkbox when no selectedCollection', () => {
- const { queryByTestId } = renderComponent({ selectedCollection: null });
+ const { queryByTestId } = renderComponent({ smartHandoffs: { conceptId: 'NO-MATCH' } });
expect(queryByTestId('crop-checkbox')).not.toBeInTheDocument();
});
@@ -518,27 +503,21 @@ describe('renderCropBox', () => {
});
});
-// ─── onBoundaryChange ─────────────────────────────────────────────────────────
-
describe('onBoundaryChange', () => {
it('does nothing when no selectedCollection', () => {
- renderComponent({ selectedCollection: null, selectedLayer: layer1 });
- // No crop checkbox rendered without selectedCollection, so nothing to fire
+ renderComponent({ smartHandoffs: { conceptId: 'NO-MATCH' } });
expect(document.querySelector('.smart-handoff-crop-toggle')).not.toBeInTheDocument();
});
it('updates currentExtent when setExtent is true (onDragStop)', () => {
const { getByTestId } = renderComponent();
fireEvent.click(getByTestId('crop-checkbox'));
- // doubleClick triggers onDragStop which calls onBoundaryChange with setExtent=true
fireEvent.doubleClick(getByTestId('crop-tool'));
- // GranuleCount should still be present (isValidDownload still true)
expect(getByTestId('granule-count')).toBeInTheDocument();
});
it('clamps coordinates exceeding positive bounds (x1>180, y1>90, x2>180, y2>90)', () => {
const { imageUtilGetCoordsFromPixelValues } = require('../../modules/image-download/util');
- // Both points outside positive bounds → hits x=180 and y=90 clamp branches
imageUtilGetCoordsFromPixelValues.mockReturnValue([[200, 100], [210, 95]]);
const { getByTestId } = renderComponent();
fireEvent.click(getByTestId('crop-checkbox'));
@@ -548,7 +527,6 @@ describe('onBoundaryChange', () => {
it('clamps coordinates below negative bounds (x1<-180, x2<-180, y1<-90, y2<-90)', () => {
const { imageUtilGetCoordsFromPixelValues } = require('../../modules/image-download/util');
- // Both points outside negative bounds → hits x=-180 and y=-90 clamp branches
imageUtilGetCoordsFromPixelValues.mockReturnValue([[-200, -100], [-190, -95]]);
const { getByTestId } = renderComponent();
fireEvent.click(getByTestId('crop-checkbox'));
@@ -557,8 +535,6 @@ describe('onBoundaryChange', () => {
});
});
-// ─── renderSelectionWarning ───────────────────────────────────────────────────
-
describe('renderSelectionWarning', () => {
it('does not render alert by default', () => {
const { queryByTestId } = renderComponent();
@@ -566,64 +542,41 @@ describe('renderSelectionWarning', () => {
});
it('renders dateline alert when zoomed into dateline (left wing)', () => {
- const { container } = render(
- React.createElement(SmartHandoff, {
- ...defaultProps,
- map: { ui: { selected: {} }, extent: [-200, -90, -185, 90] },
- proj: {
- id: 'geographic',
- crs: 'EPSG:4326',
- maxExtent: [-180, -90, 180, 90],
- },
- }),
- );
+ const { container } = renderComponent({
+ map: { extent: [-200, -90, -185, 90] },
+ });
expect(container.querySelector('#data-download-unavailable-dateline-alert')).toBeInTheDocument();
});
it('renders dateline alert when zoomed into dateline (right wing)', () => {
- const { container } = render(
- React.createElement(SmartHandoff, {
- ...defaultProps,
- map: { ui: { selected: {} }, extent: [185, -90, 200, 90] },
- proj: {
- id: 'geographic',
- crs: 'EPSG:4326',
- maxExtent: [-180, -90, 180, 90],
- },
- }),
- );
+ const { container } = renderComponent({
+ map: { extent: [185, -90, 200, 90] },
+ });
expect(container.querySelector('#data-download-unavailable-dateline-alert')).toBeInTheDocument();
});
it('download button not valid when showZoomedIntoDatelineAlert is true', () => {
- const { getByTestId } = render(
- React.createElement(SmartHandoff, {
- ...defaultProps,
- map: { ui: { selected: {} }, extent: [-200, -90, -185, 90] },
- proj: {
- id: 'geographic',
- crs: 'EPSG:4326',
- maxExtent: [-180, -90, 180, 90],
- },
- }),
- );
+ const { getByTestId } = renderComponent({
+ map: { extent: [-200, -90, -185, 90] },
+ });
expect(getByTestId('download-btn')).toHaveAttribute('data-valid', 'false');
});
});
-// ─── onClickDownload ──────────────────────────────────────────────────────────
-
describe('onClickDownload', () => {
- it('calls showWarningModal when HIDE_EDS_WARNING not set', () => {
+ it('dispatches warning modal when HIDE_EDS_WARNING not set', () => {
safeLocalStorage.getItem.mockReturnValue(null);
- const showWarningModal = jest.fn();
- const { getByTestId } = renderComponent({ showWarningModal });
+ const { getByTestId, store } = renderComponent();
fireEvent.click(getByTestId('download-btn'));
- expect(showWarningModal).toHaveBeenCalledWith(
- '2020 JAN 01',
- layer1,
- defaultProps.selectedCollection,
- expect.any(Function),
+ const action = findCustomContent(store, 'transferring-to-earthdata-search');
+ expect(action).toBeTruthy();
+ expect(action.opts.bodyComponentProps).toEqual(
+ expect.objectContaining({
+ displayDate: '2020 JAN 01',
+ selectedLayer: layer1,
+ selectedCollection: expect.objectContaining({ value: 'C1-STD' }),
+ continueToEDS: expect.any(Function),
+ }),
);
});
@@ -636,364 +589,249 @@ describe('onClickDownload', () => {
it('uses granule date range when isGranuleLayer is true', () => {
safeLocalStorage.getItem.mockReturnValue(null);
- const showWarningModal = jest.fn();
- const { getByTestId } = renderComponent({
- showWarningModal,
- isGranuleLayer: true,
- startDate: '2020-01-01T00:00:00.000Z',
- endDate: '2020-01-01T23:59:59.999Z',
+ const granuleLayer = { ...layer1, type: 'granule' };
+ const { getByTestId, store } = renderComponent({
+ smartHandoffs: {
+ availableLayers: [granuleLayer],
+ validatedLayers: [granuleLayer],
+ },
});
fireEvent.click(getByTestId('download-btn'));
- expect(showWarningModal).toHaveBeenCalledWith(
+ const action = findCustomContent(store, 'transferring-to-earthdata-search');
+ expect(action.opts.bodyComponentProps.displayDate).toEqual(
expect.stringContaining(' - '),
- expect.anything(),
- expect.anything(),
- expect.any(Function),
);
});
it('continueToEDS calls openEarthDataSearch with correct options', () => {
safeLocalStorage.getItem.mockReturnValue(null);
- let capturedContinue;
- const showWarningModal = jest.fn((date, layer, collection, continueToEDS) => {
- capturedContinue = continueToEDS;
- });
- const { getByTestId } = renderComponent({ showWarningModal });
+ const { getByTestId, store } = renderComponent();
fireEvent.click(getByTestId('download-btn'));
- capturedContinue();
+ const action = findCustomContent(store, 'transferring-to-earthdata-search');
+ action.opts.bodyComponentProps.continueToEDS();
expect(openEarthDataSearch).toHaveBeenCalledWith(
- defaultProps.availableTools,
+ [],
expect.objectContaining({
- projection: defaultProps.proj.crs,
- conceptId: defaultProps.selectedCollection.value,
+ projection: geographicProj.crs,
+ conceptId: 'C1-STD',
}),
);
});
});
-// ─── componentDidMount ────────────────────────────────────────────────────────
-
describe('componentDidMount', () => {
- it('calls fetchAvailableTools on mount', () => {
- const fetchAvailableTools = jest.fn();
- renderComponent({ fetchAvailableTools });
- expect(fetchAvailableTools).toHaveBeenCalled();
+ it('dispatches fetchAvailableTools on mount', () => {
+ const { store } = renderComponent();
+ expect(actionsOfType(store, 'FETCH_AVAILABLE_TOOLS').length).toBe(1);
});
- it('calls validateLayersConceptIds with availableLayers on mount', () => {
- const validateLayersConceptIds = jest.fn();
- renderComponent({ validateLayersConceptIds });
- expect(validateLayersConceptIds).toHaveBeenCalledWith([layer1]);
+ it('dispatches validateLayersConceptIds with availableLayers on mount', () => {
+ const { store } = renderComponent();
+ const [validate] = actionsOfType(store, 'VALIDATE_LAYERS');
+ expect(validate.layers).toEqual([layer1]);
});
it('does not check extent when proj is not geographic', () => {
- // No dateline alert rendered for non-geographic proj
const { queryByTestId } = renderComponent({
- proj: { id: 'arctic', crs: 'EPSG:3413', maxExtent: [-180, 60, 180, 90] },
+ proj: { selected: arcticProj },
+ map: { extent: [-200, -90, -185, 90] },
});
expect(queryByTestId('alert')).not.toBeInTheDocument();
});
});
-// ─── componentDidUpdate ───────────────────────────────────────────────────────
-
describe('componentDidUpdate', () => {
- it('calls validateLayersConceptIds when availableLayers changes', () => {
- const validateLayersConceptIds = jest.fn();
- const { rerender } = renderComponent({ validateLayersConceptIds });
- validateLayersConceptIds.mockClear();
+ it('dispatches validateLayersConceptIds when availableLayers changes', () => {
const newLayer = { ...layer1, id: 'layer2' };
- rerender(React.createElement(SmartHandoff, {
- ...defaultProps,
- validateLayersConceptIds,
- availableLayers: [newLayer],
+ const { rerender } = renderComponent();
+ const updatedStore = mockStore(buildState({
+ smartHandoffs: { availableLayers: [newLayer] },
}));
- expect(validateLayersConceptIds).toHaveBeenCalledWith([newLayer]);
+ rerender(
+ <Provider store={updatedStore}>
+ <SmartHandoff />
+ </Provider>,
+ );
+ const [validate] = actionsOfType(updatedStore, 'VALIDATE_LAYERS');
+ expect(validate.layers).toEqual([newLayer]);
});
it('resets to baseState when selectedCollection set but layer no longer active', () => {
const { rerender, getByTestId, queryByTestId } = renderComponent();
- // Toggle bounding box on to verify initial state mutation
fireEvent.click(getByTestId('crop-checkbox'));
- // Rerender with layer gone AND collection cleared (parent would do this after reset)
- rerender(React.createElement(SmartHandoff, {
- ...defaultProps,
- availableLayers: [],
- selectedCollection: null,
- validatedLayers: [layer1],
+ const updatedStore = mockStore(buildState({
+ smartHandoffs: { availableLayers: [], conceptId: 'NO-MATCH' },
}));
- // showBoundingBox resets to false — crop tool no longer visible
+ rerender(
+ <Provider store={updatedStore}>
+ <SmartHandoff />
+ </Provider>,
+ );
expect(queryByTestId('crop-tool')).not.toBeInTheDocument();
});
it('hides bounding box when proj changes away from geographic', () => {
const { rerender, getByTestId } = renderComponent();
fireEvent.click(getByTestId('crop-checkbox'));
- rerender(React.createElement(SmartHandoff, {
- ...defaultProps,
- proj: { id: 'arctic', crs: 'EPSG:3413', maxExtent: [-180, 60, 180, 90] },
- }));
- // Crop box should be gone (not geographic)
+ const updatedStore = mockStore(buildState({ proj: { selected: arcticProj } }));
+ rerender(
+ <Provider store={updatedStore}>
+ <SmartHandoff />
+ </Provider>,
+ );
expect(document.querySelector('.smart-handoff-crop-toggle')).not.toBeInTheDocument();
});
it('re-checks extent when map.extent changes in geographic proj', () => {
const { rerender, container } = renderComponent();
- // Initially normal extent, no alert
expect(container.querySelector('#data-download-unavailable-dateline-alert')).not.toBeInTheDocument();
- // Rerender with dateline extent
- rerender(React.createElement(SmartHandoff, {
- ...defaultProps,
- map: { ui: { selected: {} }, extent: [-200, -90, -185, 90] },
- }));
+ const updatedStore = mockStore(buildState({ map: { extent: [-200, -90, -185, 90] } }));
+ rerender(
+ <Provider store={updatedStore}>
+ <SmartHandoff />
+ </Provider>,
+ );
expect(container.querySelector('#data-download-unavailable-dateline-alert')).toBeInTheDocument();
});
it('clears showZoomedIntoDatelineAlert when proj changes to non-geographic', () => {
- const { rerender, container } = render(
- React.createElement(SmartHandoff, {
- ...defaultProps,
- map: { ui: { selected: {} }, extent: [-200, -90, -185, 90] },
- }),
- );
+ const { rerender, container } = renderComponent({ map: { extent: [-200, -90, -185, 90] } });
expect(container.querySelector('#data-download-unavailable-dateline-alert')).toBeInTheDocument();
- rerender(React.createElement(SmartHandoff, {
- ...defaultProps,
- map: { ui: { selected: {} }, extent: [-200, -90, -185, 90] },
- proj: { id: 'arctic', crs: 'EPSG:3413', maxExtent: [-180, 60, 180, 90] },
+ const updatedStore = mockStore(buildState({
+ map: { extent: [-200, -90, -185, 90] },
+ proj: { selected: arcticProj },
}));
+ rerender(
+ <Provider store={updatedStore}>
+ <SmartHandoff />
+ </Provider>,
+ );
expect(container.querySelector('#data-download-unavailable-dateline-alert')).not.toBeInTheDocument();
});
});
-// ─── updateSelectionAlerts ────────────────────────────────────────────────────
-
describe('updateSelectionAlerts', () => {
it('renders selection outside extents alert when selection is outside map area', async () => {
const { imageUtilGetCoordsFromPixelValues } = require('../../modules/image-download/util');
- // Return coords outside bounds so x1 > 180 → entireSelectionOutside = true
imageUtilGetCoordsFromPixelValues.mockReturnValue([[190, 30], [200, 50]]);
const { getByTestId, findByTestId } = renderComponent();
await act(async () => {
fireEvent.click(getByTestId('crop-checkbox'));
});
expect(await findByTestId('alert')).toBeInTheDocument();
- // Restore default mock
imageUtilGetCoordsFromPixelValues.mockReturnValue([[-100, 30], [-80, 50]]);
});
});
-// ─── mapStateToProps ──────────────────────────────────────────────────────────
-
describe('mapStateToProps', () => {
- const makeState = (overrides = {}) => ({
- screenSize: { screenWidth: 1200, screenHeight: 800, ...overrides.screenSize },
- map: {
- ui: { selected: {} },
- extent: [-180, -90, 180, 90],
- ...overrides.map,
- },
- proj: {
- selected: {
- id: 'geographic',
- crs: 'EPSG:4326',
- maxExtent: [-180, -90, 180, 90],
- },
- ...overrides.proj,
- },
- smartHandoffs: {
- conceptId: 'C1-STD',
- layerId: 'layer1',
- availableTools: [],
- validatedConceptIds: { 'C1-STD': true },
- validatedLayers: [layer1],
- isLoadingTools: false,
- isValidatingCollections: false,
- requestFailed: false,
- ...overrides.smartHandoffs,
- },
- date: {},
- layers: {},
- config: {},
- ...overrides,
- });
-
- beforeEach(() => {
- const selectors = jest.requireMock('../../modules/smart-handoff/selectors');
- selectors.getValidLayersForHandoffs.mockReturnValue([layer1]);
- selectors.getConceptUrl.mockReturnValue((val) => `https://cmr.example.com/${val}`);
- selectors.getGranulesUrl.mockReturnValue(jest.fn());
- const dateSelectors = jest.requireMock('../../modules/date/selectors');
- dateSelectors.getSelectedDate.mockReturnValue(new Date('2020-01-01'));
- const layerSelectors = jest.requireMock('../../modules/layers/selectors');
- layerSelectors.getActiveGranuleLayers.mockReturnValue({});
- });
-
- it('returns screenWidth and screenHeight from screenSize', () => {
- const result = capturedMapStateToProps(makeState(), {});
- expect(result.screenWidth).toBe(1200);
- expect(result.screenHeight).toBe(800);
- });
-
- it('returns proj.selected as proj', () => {
- const state = makeState();
- const result = capturedMapStateToProps(state, {});
- expect(result.proj.id).toBe('geographic');
- });
-
- it('returns map from state', () => {
- const state = makeState();
- const result = capturedMapStateToProps(state, {});
- expect(result.map).toBe(state.map);
- });
-
- it('returns requestFailed from smartHandoffs', () => {
- const result = capturedMapStateToProps(makeState({
- smartHandoffs: { requestFailed: true },
- }), {});
- expect(result.requestFailed).toBe(true);
- });
-
- it('sets isLoading true when isLoadingTools is true', () => {
- const result = capturedMapStateToProps(
- makeState({ smartHandoffs: { isLoadingTools: true } }),
- {},
- );
- expect(result.isLoading).toBe(true);
- });
-
- it('sets isLoading true when isValidatingCollections is true', () => {
- const result = capturedMapStateToProps(
- makeState({ smartHandoffs: { isValidatingCollections: true } }),
- {},
- );
- expect(result.isLoading).toBe(true);
- });
-
- it('selectedLayer is the layer matching layerId', () => {
- const result = capturedMapStateToProps(makeState(), {});
- expect(result.selectedLayer).toBe(layer1);
- });
-
- it('selectedLayer is undefined when layerId does not match', () => {
- const result = capturedMapStateToProps(
- makeState({ smartHandoffs: { layerId: 'nonexistent' } }),
- {},
- );
- expect(result.selectedLayer).toBeUndefined();
+ it('passes screenWidth/screenHeight from screenSize into boundary state', () => {
+ const { getByTestId } = renderComponent();
+ fireEvent.click(getByTestId('crop-checkbox'));
+ const cropTool = getByTestId('crop-tool');
+ expect(cropTool).toHaveAttribute('data-x', String(1200 / 2 - 100));
+ expect(cropTool).toHaveAttribute('data-y', String(800 / 2 - 100));
});
- it('selectedCollection is the collection matching conceptId', () => {
- const result = capturedMapStateToProps(makeState(), {});
- expect(result.selectedCollection.value).toBe('C1-STD');
+ it('selects the layer matching layerId', () => {
+ const { container } = renderComponent();
+ expect(container.querySelector('.layer-item.selected')).toBeInTheDocument();
});
- it('selectedCollection is undefined when no selectedLayer', () => {
- const result = capturedMapStateToProps(
- makeState({ smartHandoffs: { layerId: 'nonexistent' } }),
- {},
- );
- expect(result.selectedCollection).toBeUndefined();
+ it('does not select a layer when layerId does not match', () => {
+ const { container } = renderComponent({ smartHandoffs: { layerId: 'nonexistent' } });
+ expect(container.querySelector('.layer-item.selected')).not.toBeInTheDocument();
});
- it('isGranuleLayer is true for granule type layer', () => {
- const granuleLayer = { ...layer1, type: 'granule', conceptIds: [{ type: 'STD', value: 'C1-STD' }] };
- jest.requireMock('../../modules/smart-handoff/selectors')
- .getValidLayersForHandoffs.mockReturnValue([granuleLayer]);
- const result = capturedMapStateToProps(makeState(), {});
- expect(result.isGranuleLayer).toBe(true);
+ it('selects the collection matching conceptId', () => {
+ const { container } = renderComponent();
+ const checked = container.querySelector('input[type="radio"]:checked');
+ expect(checked).toBeInTheDocument();
});
- it('startDate and endDate come from getStartEndDates for regular layer', () => {
- const result = capturedMapStateToProps(makeState(), {});
- expect(result.startDate).toBe('2020-01-01T00:00:00.000Z');
- expect(result.endDate).toBe('2020-01-01T23:59:59.999Z');
+ it('does not mark a collection when conceptId does not match', () => {
+ const { container } = renderComponent({ smartHandoffs: { conceptId: 'NO-MATCH' } });
+ expect(container.querySelector('input[type="radio"]:checked')).not.toBeInTheDocument();
});
- it('startDate/endDate are undefined when no selectedLayer', () => {
- const result = capturedMapStateToProps(
- makeState({ smartHandoffs: { layerId: 'none' } }),
- {},
+ it('treats granule-type layers as granule layers in the download flow', () => {
+ safeLocalStorage.getItem.mockReturnValue(null);
+ const granuleLayer = { ...layer1, type: 'granule' };
+ const { getByTestId, store } = renderComponent({
+ smartHandoffs: {
+ availableLayers: [granuleLayer],
+ validatedLayers: [granuleLayer],
+ },
+ });
+ fireEvent.click(getByTestId('download-btn'));
+ const action = findCustomContent(store, 'transferring-to-earthdata-search');
+ expect(action.opts.bodyComponentProps.displayDate).toEqual(
+ expect.stringContaining(' - '),
);
- expect(result.startDate).toBeUndefined();
- expect(result.endDate).toBeUndefined();
- });
-
- it('returns validatedConceptIds from smartHandoffs', () => {
- const result = capturedMapStateToProps(makeState(), {});
- expect(result.validatedConceptIds).toEqual({ 'C1-STD': true });
- });
-
- it('returns availableTools from smartHandoffs', () => {
- const result = capturedMapStateToProps(makeState(), {});
- expect(result.availableTools).toEqual([]);
});
});
-// ─── mapDispatchToProps ───────────────────────────────────────────────────────
-
describe('mapDispatchToProps', () => {
- let dispatch;
- let mapped;
-
- beforeEach(() => {
- dispatch = jest.fn();
- mapped = capturedMapDispatchToProps(dispatch);
- });
-
- it('selectCollection dispatches selectCollectionAction', () => {
- mapped.selectCollection('C1-STD', 'layer1');
- expect(selectCollectionAction).toHaveBeenCalledWith('C1-STD', 'layer1');
- expect(dispatch).toHaveBeenCalled();
+ it('selectCollection dispatches SELECT_COLLECTION', () => {
+ const { container, store } = renderComponent();
+ const radios = container.querySelectorAll('input[type="radio"]');
+ fireEvent.click(radios[1]);
+ const [action] = actionsOfType(store, 'SELECT_COLLECTION');
+ expect(action).toEqual(
+ expect.objectContaining({ type: 'SELECT_COLLECTION', conceptId: 'C1-NRT', layerId: 'layer1' }),
+ );
});
- it('fetchAvailableTools dispatches fetchAvailableToolsAction', () => {
- mapped.fetchAvailableTools();
- expect(fetchAvailableToolsAction).toHaveBeenCalled();
- expect(dispatch).toHaveBeenCalled();
+ it('fetchAvailableTools dispatches FETCH_AVAILABLE_TOOLS', () => {
+ const { store } = renderComponent();
+ expect(actionsOfType(store, 'FETCH_AVAILABLE_TOOLS').length).toBe(1);
});
- it('validateLayersConceptIds dispatches validateLayersConceptIdsAction', () => {
- mapped.validateLayersConceptIds([layer1]);
- expect(validateLayersConceptIdsAction).toHaveBeenCalledWith([layer1]);
- expect(dispatch).toHaveBeenCalled();
+ it('validateLayersConceptIds dispatches VALIDATE_LAYERS', () => {
+ const { store } = renderComponent();
+ const [validate] = actionsOfType(store, 'VALIDATE_LAYERS');
+ expect(validate.layers).toEqual([layer1]);
});
it('showWarningModal pushes GTM event', () => {
- mapped.showWarningModal('2020 JAN 01', layer1, { value: 'C1-STD' }, jest.fn());
+ const { getByTestId } = renderComponent();
+ fireEvent.click(getByTestId('download-btn'));
expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
event: 'smart_handoffs_open_warning_modal',
});
});
it('showWarningModal dispatches openCustomContent', () => {
- mapped.showWarningModal('2020 JAN 01', layer1, { value: 'C1-STD' }, jest.fn());
- expect(openCustomContent).toHaveBeenCalledWith(
- 'transferring-to-earthdata-search',
+ const { getByTestId, store } = renderComponent();
+ fireEvent.click(getByTestId('download-btn'));
+ const action = findCustomContent(store, 'transferring-to-earthdata-search');
+ expect(action.opts).toEqual(
expect.objectContaining({ headerText: 'Leaving @NAME@' }),
);
- expect(dispatch).toHaveBeenCalled();
+ expect(openCustomContent).toHaveBeenCalled();
});
it('showNotAvailableModal dispatches openCustomContent', () => {
- mapped.showNotAvailableModal();
- expect(openCustomContent).toHaveBeenCalledWith(
- 'layers-not-available',
+ const { getByText, store } = renderComponent();
+ fireEvent.click(getByText(/Why are some layers not available/));
+ const action = findCustomContent(store, 'layers-not-available');
+ expect(action.opts).toEqual(
expect.objectContaining({ headerText: 'Data Download Availability' }),
);
});
it('showGranuleHelpModal pushes GTM event', () => {
- mapped.showGranuleHelpModal();
+ const { getByTestId } = renderComponent();
+ fireEvent.click(getByTestId('granule-count'));
expect(googleTagManager.pushEvent).toHaveBeenCalledWith({
event: 'smart_handoffs_open_granule_help_link',
});
});
it('showGranuleHelpModal dispatches openCustomContent', () => {
- mapped.showGranuleHelpModal();
- expect(openCustomContent).toHaveBeenCalledWith(
- 'granule-help',
+ const { getByTestId, store } = renderComponent();
+ fireEvent.click(getByTestId('granule-count'));
+ const action = findCustomContent(store, 'granule-help');
+ expect(action.opts).toEqual(
expect.objectContaining({ headerText: 'Granule Availability' }),
);
});