import assert from 'assert'; import moment from 'moment'; /* eslint-disable @typescript-eslint/no-explicit-any */ (global as any).matchMedia = (global as any).matchMedia || (() => ({ matches: false, addListener: () => {}, removeListener: () => {}, })); const mockDoc = { createElement: (): Record => ({ setAttribute: () => {}, style: {}, classList: { add: () => {}, remove: () => {} }, addEventListener: () => {}, removeEventListener: () => {}, querySelector: () => null, querySelectorAll: () => [], }), documentElement: { style: {}, }, head: { appendChild: () => {}, }, body: { appendChild: () => {}, querySelector: () => null, querySelectorAll: () => [], }, getElementsByTagName: (): any[] => [], addEventListener: () => {}, removeEventListener: () => {}, cookie: '', }; (global as any).document = mockDoc; const mockWindow: Record = { addEventListener: () => {}, removeEventListener: () => {}, document: mockDoc, navigator: { userAgent: 'node', cookieEnabled: true }, localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, sessionStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} }, location: { href: 'http://localhost', origin: 'http://localhost', protocol: 'http:', host: 'localhost', hostname: 'localhost', port: '', pathname: '/', search: '', hash: '' }, }; (global as any).window = mockWindow; // inputmask reads the bare `navigator` global, which is read-only in Node 24 Object.defineProperty(global, 'navigator', { value: mockWindow.navigator, writable: true, configurable: true, }); /* eslint-enable @typescript-eslint/no-explicit-any */ import GDSSelect from './GDSSelect'; describe('GDSSelect', () => { it('forces client-side search by clearing searchField for reference-data (/v2/entities/) selects', () => { const selectComponent = new GDSSelect({ type: 'select', key: 'port', searchField: 'name', dataSrc: 'url', data: { url: '/refdata/v2/entities/port' }, }, {}); selectComponent.init(); assert.strictEqual(selectComponent.component.searchField, ''); }); it('clears searchField for non-reference-data URL selects that have searchField set (client-side search)', () => { const selectComponent = new GDSSelect({ type: 'select', key: 'officer', searchField: 'email', dataSrc: 'url', data: { url: '/users/emails' }, }, {}); selectComponent.init(); assert.strictEqual(selectComponent.component.searchField, '', 'searchField must be cleared for client-side search'); }); it('sets disableLimit for non-reference-data URL selects with searchField so the full dataset loads', () => { const selectComponent = new GDSSelect({ type: 'select', key: 'officer', searchField: 'email', limit: 25, dataSrc: 'url', data: { url: '/users/emails' }, }, {}); selectComponent.init(); assert.strictEqual(selectComponent.component.disableLimit, true, 'disableLimit must be set to load full dataset'); }); it('enables Choices search so the patched matcher owns filtering for reference-data selects', () => { const selectComponent = new GDSSelect({ type: 'select', key: 'port', searchThreshold: 0, selectThreshold: 0.5, dataSrc: 'url', data: { url: '/refdata/v2/entities/port' }, }, {}); const options = selectComponent.choicesOptions(); assert.strictEqual(options.searchChoices, true); assert.strictEqual(options.searchFloor, 0); assert.deepStrictEqual(options.searchFields, ['label', 'value']); }); it('enables client-side Choices search for non-reference-data URL selects with searchField', () => { const selectComponent = new GDSSelect({ type: 'select', key: 'officer', searchField: 'email', dataSrc: 'url', data: { url: '/users/emails' }, customOptions: { searchFloor: 3 }, }, {}); const options = selectComponent.choicesOptions(); assert.strictEqual(options.searchChoices, true, 'searchChoices must be true for client-side filtering'); assert.strictEqual(options.searchFloor, 0, 'searchFloor must be overridden to 0 so filtering starts immediately'); assert.deepStrictEqual(options.searchFields, ['label', 'value']); }); it('does not apply client-side search settings to URL selects without searchField', () => { const selectComponent = new GDSSelect({ type: 'select', key: 'status', dataSrc: 'url', data: { url: '/statuses' }, }, {}); selectComponent.init(); // eslint-disable-next-line @typescript-eslint/no-explicit-any assert.ok(!(selectComponent as any)._gdsClientSideSearch, '_gdsClientSideSearch must be falsy for a select with no searchField'); const options = selectComponent.choicesOptions(); assert.notStrictEqual(options.searchFloor, 0, 'searchFloor must not be forced to 0 for non-search URL selects'); }); it('keeps Choices search enabled for reference data', () => { const selectComponent = new GDSSelect({ type: 'select', key: 'currency', searchThreshold: 0.3, dataSrc: 'url', data: { url: '/v2/entities/currency' }, }, {}); const options = selectComponent.choicesOptions(); assert.strictEqual(options.searchChoices, true); }); it('updateItems re-populates choices from cache after activate() shows spinner', () => { /* eslint-disable @typescript-eslint/no-explicit-any */ const selectComponent = new GDSSelect({ type: 'select', key: 'terminal', dataSrc: 'url', filter: '?mode=dataOnly', data: { url: '/v2/entities/terminal' }, }, {}); const component = selectComponent as any; const gdsProto = GDSSelect.prototype as any; const original = gdsProto.setItems; let setItemsCalled = false; let setItemsArg: unknown; gdsProto.setItems = (items: unknown) => { setItemsCalled = true; setItemsArg = items; }; const cachedItems = [{ id: 1, name: 'Eastern Docks' }, { id: 2, name: 'Western Docks' }]; component.downloadedResources = cachedItems; component.loading = false; component.itemsLoadedResolve = () => {}; component._gdsFilterKey = ''; component.interpolate = () => ''; try { component.updateItems(null, false); assert.strictEqual(setItemsCalled, true, 'setItems must be called to restore choices from cache'); assert.strictEqual(setItemsArg, cachedItems, 'setItems must receive the cached downloadedResources'); setItemsCalled = false; component.choices = { _isSearching: true, _currentValue: 'andrew', _store: { choices: [], dispatch: () => {} } }; component.updateItems(null, false); assert.strictEqual(setItemsCalled, false, 'must not restore cache while choices is searching'); } finally { gdsProto.setItems = original; } /* eslint-enable @typescript-eslint/no-explicit-any */ }); it('updateItems skips URL re-fetch when items and the dynamic filter are unchanged', () => { /* eslint-disable @typescript-eslint/no-explicit-any */ const selectComponent = new GDSSelect({ type: 'select', key: 'currency', dataSrc: 'url', filter: '{{row.countryFilter}}', data: { url: '/v2/entities/currency' }, }, {}); let superCalled = false; const proto = Object.getPrototypeOf(GDSSelect.prototype); const original = proto.updateItems; proto.updateItems = () => { superCalled = true; }; (selectComponent as any).downloadedResources = [{ value: 'USD', label: 'USD' }]; (selectComponent as any).itemsLoadedResolve = () => {}; (selectComponent as any)._gdsFilterKey = ''; (selectComponent as any).interpolate = () => ''; (selectComponent as any).updateItems(null, false); assert.strictEqual(superCalled, false, 'should skip re-fetch when items are loaded'); (selectComponent as any).updateItems(null, true); assert.strictEqual(superCalled, true, 'should allow re-fetch when forceUpdate is true'); proto.updateItems = original; /* eslint-enable @typescript-eslint/no-explicit-any */ }); it('refreshes URL selects when an interpolated filter has changed', () => { /* eslint-disable @typescript-eslint/no-explicit-any */ const selectComponent = new GDSSelect({ type: 'select', key: 'port', dataSrc: 'url', filter: '{{row.countryFilter}}&mode=dataOnly', data: { url: '/v2/entities/port' }, }, {}); let superCalled = false; const proto = Object.getPrototypeOf(GDSSelect.prototype); const original = proto.updateItems; proto.updateItems = () => { superCalled = true; }; (selectComponent as any).downloadedResources = [{ value: 'PORT-1', label: 'Port 1' }]; (selectComponent as any).itemsLoadedResolve = () => {}; (selectComponent as any)._gdsFilterKey = 'countryid=eq.1'; (selectComponent as any).interpolate = () => 'countryid=eq.2'; (selectComponent as any).updateItems(null, false); assert.strictEqual(superCalled, true, 'dynamic filters must be re-evaluated'); proto.updateItems = original; /* eslint-enable @typescript-eslint/no-explicit-any */ }); it('reloads an already-visible select when its filter dependency changes', () => { /* eslint-disable @typescript-eslint/no-explicit-any */ const selectComponent = new GDSSelect({ type: 'select', key: 'departurePort', dataSrc: 'url', filter: '{{row.departurePortFilter}}&mode=dataOnly', data: { url: '/v2/entities/port' }, }, {}); const component = selectComponent as any; const proto = Object.getPrototypeOf(GDSSelect.prototype); const originalCheck = proto.checkComponentConditions; proto.checkComponentConditions = () => true; const updates: unknown[][] = []; component.triggerUpdate = (...args: unknown[]) => updates.push(args); component.downloadedResources = [{ value: 'PORT-1', label: 'Port 1' }]; component.itemsLoadedResolve = () => {}; component._gdsFilterKey = 'filter=countryid=eq.1&mode=dataOnly'; let filterKey = 'filter=countryid=eq.1&mode=dataOnly'; component.interpolate = () => filterKey; try { component.checkComponentConditions({}, {}, {}); assert.strictEqual(updates.length, 0, 'must not re-fetch when the filter is unchanged'); filterKey = 'filter=countryid=eq.2&mode=dataOnly'; component.checkComponentConditions({}, {}, {}); assert.deepStrictEqual(updates, [[null, true]], 'must force a re-fetch when the filter changes'); component.checkComponentConditions({}, {}, {}); assert.strictEqual(updates.length, 1, 'must not queue duplicate fetches'); } finally { proto.checkComponentConditions = originalCheck; } /* eslint-enable @typescript-eslint/no-explicit-any */ }); it('does not reload a lazily-loaded select before its options have loaded', () => { /* eslint-disable @typescript-eslint/no-explicit-any */ const selectComponent = new GDSSelect({ type: 'select', key: 'departurePort', dataSrc: 'url', lazyLoad: true, filter: '{{row.departurePortFilter}}&mode=dataOnly', data: { url: '/v2/entities/port' }, }, {}); const component = selectComponent as any; const proto = Object.getPrototypeOf(GDSSelect.prototype); const originalCheck = proto.checkComponentConditions; proto.checkComponentConditions = () => true; const updates: unknown[][] = []; component.triggerUpdate = (...args: unknown[]) => updates.push(args); component.interpolate = () => 'filter=countryid=eq.2'; component._gdsFilterKey = undefined; try { component.checkComponentConditions({}, {}, {}); assert.strictEqual(updates.length, 0, 'must not fetch before the first load'); } finally { proto.checkComponentConditions = originalCheck; } /* eslint-enable @typescript-eslint/no-explicit-any */ }); it('substring search logic: finds "usd" in "USD - United States Dollar"', () => { const choices = [ { label: 'USD - United States Dollar', active: true, rank: 1 }, { label: 'AUD - Australian Dollar', active: true, rank: 2 }, { label: 'EUR - Euro', active: true, rank: 3 }, ]; function substringSearch(needle: string, allChoices: typeof choices): typeof choices { if (!needle) return []; const words = needle.toLowerCase().split(/\s+/).filter(Boolean); const matched: typeof choices = []; const prefix: typeof choices = []; const contains: typeof choices = []; for (const choice of allChoices) { const label = (choice.label || '').toLowerCase(); const allMatch = words.every((w) => label.includes(w)); if (!allMatch) continue; if (label.startsWith(needle.toLowerCase())) { prefix.push(choice); } else { contains.push(choice); } } prefix.sort((a, b) => a.label.localeCompare(b.label)); contains.sort((a, b) => a.label.localeCompare(b.label)); matched.push(...prefix, ...contains); return matched; } const results = substringSearch('usd', choices); assert.strictEqual(results.length, 1, 'should find 1 match for "usd"'); assert.strictEqual(results[0].label, 'USD - United States Dollar'); const results2 = substringSearch('dollar', choices); assert.strictEqual(results2.length, 2, 'should find 2 matches for "dollar"'); const results3 = substringSearch('united states', choices); assert.strictEqual(results3.length, 1, 'should find 1 match for "united states"'); assert.strictEqual(results3[0].label, 'USD - United States Dollar'); const results4 = substringSearch('AUD', choices); assert.strictEqual(results4.length, 1, 'should find 1 match for "AUD"'); assert.strictEqual(results4[0].label, 'AUD - Australian Dollar'); const htmlChoices = [ { label: 'USD - United States Dollar', active: true, rank: 1 }, { label: 'AUD - Australian Dollar', active: true, rank: 2 }, { label: 'AED - United Arab Emirates Dirham', active: true, rank: 3 }, ]; const htmlResults = substringSearch('usd', htmlChoices); assert.strictEqual(htmlResults.length, 1, 'should find 1 match for "usd" in HTML-wrapped labels'); assert.strictEqual(htmlResults[0].label, 'USD - United States Dollar'); const htmlResults2 = substringSearch('AED', htmlChoices); assert.strictEqual(htmlResults2.length, 1, 'should find 1 match for "AED" in HTML-wrapped labels'); assert.strictEqual(htmlResults2[0].label, 'AED - United Arab Emirates Dirham'); const htmlResults3 = substringSearch('dollar', htmlChoices); assert.strictEqual(htmlResults3.length, 2, 'should find 2 matches for "dollar" in HTML-wrapped labels'); }); it('dispatches Choices-compatible search results for currency codes', () => { /* eslint-disable @typescript-eslint/no-explicit-any */ const selectComponent = new GDSSelect({ type: 'select', key: 'currency', dataSrc: 'url', data: { url: '/v2/entities/currency' }, }, {}); const dispatched: any[] = []; const choices: any = { _currentValue: '', _isSearching: false, _store: { choices: [ { id: 1, label: 'USD - United States Dollar' }, { id: 2, label: 'AUD - Australian Dollar' }, ], dispatch: (action: any) => dispatched.push(action), }, }; (selectComponent as any).choices = choices; (selectComponent as any)._patchChoicesSearch(); const resultCount = choices._searchChoices('usd'); assert.strictEqual(resultCount, 1); assert.deepStrictEqual(dispatched[0], { type: 'FILTER_CHOICES', results: [{ item: choices._store.choices[0], score: 0, rank: 1, }], }); /* eslint-enable @typescript-eslint/no-explicit-any */ }); it('getOptionTemplate: escapes XSS payloads in item data using _.escape before interpolation', () => { /* eslint-disable @typescript-eslint/no-explicit-any */ const selectComponent = new GDSSelect({ type: 'select', key: 'port', dataSrc: 'url', template: '{{ item.name }}', data: { url: '/v2/entities/port' }, }, {}); (selectComponent as any).interpolate = (tpl: string, ctx: any) => tpl.replace(/\{\{\s*item\.name\s*\}\}/g, ctx.item.name); (selectComponent as any).templateData = {}; const xssPayload = ''; const result = (selectComponent as any).getOptionTemplate({ name: xssPayload }, null, 0); assert.ok(typeof result === 'string', 'result must be a string'); assert.ok(!result.includes('' }, null, 0); assert.ok(!result.includes(''; const sanitizedByGetOptionTemplate = ''; (selectComponent as any).getOptionTemplate = (_d: any, _v: any, _i: any) => sanitizedByGetOptionTemplate; (selectComponent as any).t = (s: string) => s; (selectComponent as any).sanitize = (s: string) => s; const result = (selectComponent as any).itemTemplate({ name: xssName }, null, 0); assert.ok( typeof result === 'string' && !result.includes('@x' }, null, 0); assert.ok(!label.includes('