import assert from 'assert'; /* 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; if (!(global as any).HTMLInputElement) { (global as any).HTMLInputElement = class HTMLInputElement { public value: string = ''; }; } 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; Object.defineProperty(global, 'navigator', { value: mockWindow.navigator, writable: true, configurable: true, }); /* eslint-enable @typescript-eslint/no-explicit-any */ import GDSDatetimeComponent from './GDSDatetimeComponent'; const baseSchema = { type: 'datetime', key: 'eventDateTime', label: 'Event date / time', format: 'yyyy-MM-dd HH:mm', enableDate: true, enableTime: true, validate: { required: true }, fields: { day: { type: 'number', required: true }, month: { type: 'number', required: true }, year: { type: 'number', required: true }, }, }; function input(value: string): HTMLInputElement { // eslint-disable-next-line @typescript-eslint/no-explicit-any const el = new (global as any).HTMLInputElement() as HTMLInputElement; el.value = value; return el; } function makeComponent( day: string, month: string, year: string, hour: string, minute: string, schema: Record = {}, ): GDSDatetimeComponent { // eslint-disable-next-line @typescript-eslint/no-explicit-any const Ctor = GDSDatetimeComponent as any; // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = new Ctor({ ...baseSchema, ...schema }, {}, {}) as any; comp.component = { ...baseSchema, ...schema }; comp.refs = { day: input(day), month: input(month), year: input(year), hour: input(hour), minute: input(minute), input: [input('')], }; comp.dataValue = null; return comp as GDSDatetimeComponent; } describe('GDSDatetimeComponent.getDate()', () => { it('returns null when all five fields are empty', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('', '', '', '', '') as any; assert.strictEqual(comp.getDate(null), null); }); it('returns a valid ISO string (not the sentinel) when date fields are filled but both time fields are empty', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '', '') as any; const result = comp.getDate(null); assert.notStrictEqual(result, 'Invalid date'); assert.ok(result.startsWith('2023-06-15'), `expected 2023-06-15..., got ${result}`); }); it('returns a valid ISO string when date fields are filled but only hour is empty', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '', '30') as any; const result = comp.getDate(null); assert.notStrictEqual(result, 'Invalid date'); assert.ok(result.startsWith('2023-06-15'), `expected 2023-06-15..., got ${result}`); }); it('returns a valid ISO string when date fields are filled but only minute is empty', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '') as any; const result = comp.getDate(null); assert.notStrictEqual(result, 'Invalid date'); assert.ok(result.startsWith('2023-06-15T14:00'), `expected 2023-06-15T14:00..., got ${result}`); }); it('returns a valid ISO string when all five fields are filled', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '30') as any; const result = comp.getDate(null); assert.ok(result !== null, 'must return a date string when all fields are present'); assert.ok(result.includes('2023'), 'year must appear in the result'); assert.ok(result.includes('06'), 'month must appear in the result'); assert.ok(!result.includes('T00:00'), 'result must not default to midnight when time was explicitly supplied'); }); it('returns a midnight timestamp when the user explicitly enters 00:00', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('01', '01', '2024', '0', '0') as any; const result = comp.getDate(null); assert.ok(result !== null, 'explicitly entered 00:00 must produce a non-null date'); }); it('does not produce a "00:00" timestamp when time is omitted (no-time-in-schema fallback)', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('', '', '', '', '', { enableTime: false }) as any; assert.strictEqual(comp.getDate(null), null); }); it('returns "Invalid date" when day and month are filled but year is blank', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '', '14', '30') as any; assert.strictEqual(comp.getDate(null), 'Invalid date'); }); it('returns "Invalid date" when year and month are filled but day is blank', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('', '06', '2023', '14', '30') as any; assert.strictEqual(comp.getDate(null), 'Invalid date'); }); it('returns "Invalid date" when year and day are filled but month is blank', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '', '2023', '14', '30') as any; assert.strictEqual(comp.getDate(null), 'Invalid date'); }); it('returns "Invalid date" when only year is filled (all other fields blank)', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('', '', '2023', '', '') as any; assert.strictEqual(comp.getDate(null), 'Invalid date'); }); }); describe('GDSDatetimeComponent.validateRequired()', () => { it('returns false (validation fails) when all fields are empty and required', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('', '', '', '', '') as any; assert.strictEqual(comp.validateRequired(true, null), false); }); it('returns false when date is filled but both time fields are empty', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '', '') as any; assert.strictEqual(comp.validateRequired(true, null), false, 'must return false (required error) when date is filled but time is blank'); }); it('returns false when hour is empty but minute is filled', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '', '30') as any; assert.strictEqual(comp.validateRequired(true, null), false); }); it('returns false when minute is empty but hour is filled', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '') as any; assert.strictEqual(comp.validateRequired(true, null), false); }); it('returns true when all five fields are filled and the value is non-empty', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '30') as any; comp.dataValue = '2023-06-15T14:30:00+01:00'; comp.isEmpty = () => false; assert.strictEqual(comp.validateRequired(true, '2023-06-15T14:30:00+01:00'), true); }); it('is a no-op when required is false', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('', '', '', '', '') as any; comp.component.validate = { required: false }; comp.isEmpty = () => false; assert.strictEqual(comp.validateRequired(false, ''), true); }); }); describe('GDSDatetimeComponent.validationValue', () => { it('returns null when dataValue is the "Invalid date" sentinel', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '', '14', '30') as any; comp.dataValue = 'Invalid date'; assert.strictEqual(comp.validationValue, null); }); it('returns dataValue as-is for a valid ISO string', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '30') as any; comp.dataValue = '2023-06-15T14:30:00+01:00'; assert.strictEqual(comp.validationValue, '2023-06-15T14:30:00+01:00'); }); it('returns null when dataValue is null (untouched component)', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('', '', '', '', '') as any; comp.dataValue = null; assert.strictEqual(comp.validationValue, null); }); it('returns null when time is enabled and both time inputs are blank (so only "required" fires)', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '', '') as any; comp.dataValue = '2023-06-15T00:00:00+01:00'; assert.strictEqual(comp.validationValue, null); }); it('returns null when time is enabled and only hour is blank', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '', '30') as any; comp.dataValue = '2023-06-15T00:30:00+01:00'; assert.strictEqual(comp.validationValue, null); }); it('returns null when time is enabled and only minute is blank', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '') as any; comp.dataValue = '2023-06-15T14:00:00+01:00'; assert.strictEqual(comp.validationValue, null); }); it('returns dataValue when time is enabled and both time inputs are filled', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '30') as any; comp.dataValue = '2023-06-15T14:30:00+01:00'; assert.strictEqual(comp.validationValue, '2023-06-15T14:30:00+01:00'); }); it('returns dataValue when time is disabled and time inputs are blank', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '', '', { enableTime: false }) as any; comp.dataValue = '2023-06-15T00:00:00+01:00'; assert.strictEqual(comp.validationValue, '2023-06-15T00:00:00+01:00'); }); }); describe('GDSDatetimeComponent.validateComponent()', () => { it('appends an invalidDate FieldError when dataValue is the sentinel', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '', '14', '30') as any; Object.defineProperty(comp, 'dataValue', { get: () => 'Invalid date', configurable: true }); Object.defineProperty(comp, 'rootValue', { get: () => ({}), configurable: true }); Object.defineProperty(comp, 'path', { get: () => 'eventDateTime', configurable: true }); comp.data = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any const errors = (GDSDatetimeComponent.prototype as any).validateComponent.call(comp, null, null, {}) as any[]; const hasInvalidDate = errors.some( // eslint-disable-next-line @typescript-eslint/no-explicit-any (e: any) => e?.errorKeyOrMessage === 'invalidDate' && e?.ruleName === 'date', ); assert.ok(hasInvalidDate, `should contain an invalidDate error; got ${errors.length} errors with keys: ` + // eslint-disable-next-line @typescript-eslint/no-explicit-any errors.map((e: any) => `${e?.errorKeyOrMessage}/${e?.ruleName}`).join(', ')); }); it('does not duplicate the invalidDate error if already present', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '', '14', '30') as any; Object.defineProperty(comp, 'dataValue', { get: () => 'Invalid date', configurable: true }); Object.defineProperty(comp, 'rootValue', { get: () => ({}), configurable: true }); comp.data = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any const DayProto = Object.getPrototypeOf(GDSDatetimeComponent.prototype) as any; const originalDayValidate = DayProto.validateComponent; DayProto.validateComponent = () => [{ errorKeyOrMessage: 'invalidDate', ruleName: 'date' }]; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any const errors = (GDSDatetimeComponent.prototype as any).validateComponent.call(comp, null, null, {}) as any[]; assert.strictEqual(errors.length, 1, 'must not duplicate an existing invalidDate error'); } finally { DayProto.validateComponent = originalDayValidate; } }); it('does not inject invalidDate when dataValue is a valid ISO string', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = makeComponent('15', '06', '2023', '14', '30') as any; Object.defineProperty(comp, 'dataValue', { get: () => '2023-06-15T14:30:00+01:00', configurable: true }); Object.defineProperty(comp, 'rootValue', { get: () => ({}), configurable: true }); comp.data = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any const DayProto = Object.getPrototypeOf(GDSDatetimeComponent.prototype) as any; const originalDayValidate = DayProto.validateComponent; DayProto.validateComponent = () => []; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any const errors = (GDSDatetimeComponent.prototype as any).validateComponent.call(comp, null, null, {}) as any[]; assert.strictEqual(errors.length, 0, 'must not inject invalidDate for a valid date'); } finally { DayProto.validateComponent = originalDayValidate; } }); }); describe('GDSDatetimeComponent live validation (attach input handlers)', () => { function makeAttachableComponent(schema: Record = {}): { // eslint-disable-next-line @typescript-eslint/no-explicit-any comp: any; setPristineCalls: boolean[]; checkValidityCalls: Array<{ dirty: boolean }>; triggerChangeCalls: Array>; updateValueCalls: Array; } { // eslint-disable-next-line @typescript-eslint/no-explicit-any const Ctor = GDSDatetimeComponent as any; // eslint-disable-next-line @typescript-eslint/no-explicit-any const comp = new Ctor({ ...baseSchema, ...schema }, {}, {}) as any; comp.component = { ...baseSchema, ...schema }; const setPristineCalls: boolean[] = []; const checkValidityCalls: Array<{ dirty: boolean }> = []; const triggerChangeCalls: Array> = []; const updateValueCalls: Array = []; comp.setPristine = (v: boolean) => setPristineCalls.push(v); comp.checkComponentValidity = (_data: unknown, dirty: boolean) => checkValidityCalls.push({ dirty }); // eslint-disable-next-line @typescript-eslint/no-explicit-any comp.triggerChange = (flags?: Record) => triggerChangeCalls.push(flags ?? {}); comp.updateValue = () => { updateValueCalls.push(true); }; comp.timeHelper = { validateDateInput: () => {}, checkAndValidateHour: () => {}, checkAndValidateMinutes: () => {}, preventNonNumericKeyPress: () => {}, }; return { comp, setPristineCalls, checkValidityCalls, triggerChangeCalls, updateValueCalls }; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function attachWithRefs(comp: any): Record void)[]> }> { // eslint-disable-next-line @typescript-eslint/no-explicit-any const refs: Record void)[]> }> = {}; ['day', 'month', 'year', 'hour', 'minute'].forEach((name) => { refs[name] = { listeners: {} }; }); refs['input'] = { listeners: {} } as unknown as typeof refs[string] & { length: number }; // eslint-disable-next-line @typescript-eslint/no-explicit-any (refs['input'] as any).length = 1; ['day', 'month', 'year', 'hour', 'minute'].forEach((name) => { const el = new (global as any).HTMLInputElement(); el.value = ''; // eslint-disable-next-line @typescript-eslint/no-explicit-any el.addEventListener = (event: string, fn: () => void) => { el.listeners = el.listeners || {}; el.listeners[event] = el.listeners[event] || []; el.listeners[event].push(fn); }; refs[name] = el; }); comp.loadRefs = () => { comp.refs = refs; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const DayProto = Object.getPrototypeOf(GDSDatetimeComponent.prototype) as any; const originalAttach = DayProto.attach; DayProto.attach = () => Promise.resolve(); Object.defineProperty(comp, 'shouldDisabled', { get: () => false, configurable: true }); comp.data = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any comp.addEventListener = (el: any, event: string, fn: () => void) => { if (el && typeof el.addEventListener === 'function') { el.addEventListener(event, fn); } }; comp.attach({}); DayProto.attach = originalAttach; return refs; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function fireInput(refs: any, name: string): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any (refs[name] as any).listeners['input'].forEach((fn: () => void) => fn()); } (['day', 'month', 'year', 'hour', 'minute'] as const).forEach((field) => { it(`calls setPristine(false), updateValue, checkComponentValidity(dirty=true), and triggerChange({ dirty:true }) when ${field} input changes`, () => { const { comp, setPristineCalls, checkValidityCalls, triggerChangeCalls, updateValueCalls, } = makeAttachableComponent(); const refs = attachWithRefs(comp); fireInput(refs, field); assert.ok(setPristineCalls.includes(false), `setPristine(false) must be called on ${field} input`); assert.ok(updateValueCalls.length > 0, `updateValue must be called on ${field} input so dataValue is current before validation`); assert.ok(checkValidityCalls.some((c) => c.dirty === true), `checkComponentValidity(data, dirty=true) must be called on ${field} input`); assert.ok( triggerChangeCalls.some((f) => f['dirty'] === true), `triggerChange must be called with dirty:true on ${field} input so the root validate() propagates dirty=true to all components`, ); }); }); });