223 lines
10 KiB
TypeScript
223 lines
10 KiB
TypeScript
import { Component } from '@angular/core';
|
|
import { TestBed } from '@angular/core/testing';
|
|
import { By } from '@angular/platform-browser';
|
|
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
|
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
|
|
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
|
|
import { MatInputHarness } from '@angular/material/input/testing';
|
|
import { FechaCompuesta } from './fecha-compuesta';
|
|
|
|
@Component({
|
|
imports: [ReactiveFormsModule, FechaCompuesta],
|
|
template: '<app-fecha-compuesta [formControl]="fecha" etiqueta="Fecha del estudio" /><button>Después</button>',
|
|
})
|
|
class FormularioFecha {
|
|
readonly fecha = new FormControl('', { nonNullable: true, validators: [Validators.required] });
|
|
}
|
|
|
|
describe('Fecha compuesta reutilizable', () => {
|
|
let fixture: ReturnType<typeof TestBed.createComponent<FormularioFecha>>;
|
|
let fecha: FormControl<string>;
|
|
let control: FechaCompuesta;
|
|
let root: HTMLElement;
|
|
|
|
beforeEach(() => {
|
|
fixture = TestBed.createComponent(FormularioFecha);
|
|
fecha = fixture.componentInstance.fecha;
|
|
root = fixture.nativeElement;
|
|
fixture.detectChanges();
|
|
control = fixture.debugElement.query(By.directive(FechaCompuesta)).componentInstance;
|
|
});
|
|
|
|
async function escribir(parte: string, valor: string) {
|
|
const input = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
|
MatInputHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
|
await input.setValue(valor);
|
|
}
|
|
async function capturar(dia: string, mes: string, anio: string) {
|
|
await escribir('dia', dia); await escribir('mes', mes); await escribir('anio', anio);
|
|
}
|
|
function entrada(parte: string) { return root.querySelector<HTMLInputElement>(`[data-fecha="${parte}"]`)!; }
|
|
function tecla(input: HTMLInputElement, key: string, keyCode: number) {
|
|
input.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true, cancelable: true }));
|
|
fixture.detectChanges();
|
|
}
|
|
|
|
it('empieza vacío e inválido sin errores prematuros, con etiquetas y orden día-mes-año', () => {
|
|
expect(fecha.invalid).toBe(true);
|
|
expect(root.querySelector('.error')).toBeNull();
|
|
expect(root.querySelector('[role="group"]')?.getAttribute('aria-labelledby')).toBe(control.id + '-titulo');
|
|
expect(root.querySelector('#' + control.id + '-titulo')?.textContent).toContain('Fecha del estudio');
|
|
expect(Array.from(root.querySelectorAll('input')).map(input => input.dataset['fecha'])).toEqual(['dia', 'mes', 'anio']);
|
|
for (const parte of ['dia', 'mes', 'anio']) {
|
|
const input = entrada(parte);
|
|
expect(input.required).toBe(true);
|
|
expect(input.tabIndex).toBe(0);
|
|
expect(root.querySelector(`label[for="${input.id}"]`)?.textContent).toMatch(/Día|Mes|Año/);
|
|
}
|
|
});
|
|
|
|
it('captura manualmente sin seleccionar sugerencias y conserva ISO sin conversión horaria', async () => {
|
|
await capturar('26', 'octubre', '2026');
|
|
expect(fecha.valid).toBe(true);
|
|
expect(fecha.value).toBe('2026-10-26');
|
|
await capturar('1', '01', '0001');
|
|
expect(fecha.value).toBe('0001-01-01');
|
|
await capturar('31', '12', '9999');
|
|
expect(fecha.value).toBe('9999-12-31');
|
|
});
|
|
|
|
it('ofrece doce meses y filtra nombres y números sin aceptar fragmentos ambiguos', async () => {
|
|
const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
|
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
|
await mes.focus();
|
|
expect(await mes.getOptions()).toHaveLength(12);
|
|
await mes.enterText('ma');
|
|
expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Marzo', 'Mayo']);
|
|
await escribir('dia', '15'); await escribir('anio', '2026');
|
|
expect(fecha.value).toBe('');
|
|
expect(fecha.invalid).toBe(true);
|
|
await mes.clear(); await mes.enterText('10');
|
|
expect(await Promise.all((await mes.getOptions()).map(opcion => opcion.getText()))).toEqual(['Octubre']);
|
|
expect(fecha.value).toBe('2026-10-15');
|
|
for (const valor of ['13', '0', 'mes desconocido', 'mar']) {
|
|
await mes.clear(); await mes.enterText(valor);
|
|
expect(fecha.value, valor).toBe('');
|
|
expect(fecha.invalid).toBe(true);
|
|
}
|
|
});
|
|
|
|
it('selecciona los tres componentes mediante autocompletado', async () => {
|
|
const loader = TestbedHarnessEnvironment.loader(fixture);
|
|
for (const [parte, valor] of [['anio', '2024'], ['mes', 'Febrero'], ['dia', '29']]) {
|
|
const input = await loader.getHarness(MatAutocompleteHarness.with({ selector: `[data-fecha="${parte}"]` }));
|
|
if (parte === 'anio') await input.enterText(valor); else await input.focus();
|
|
await input.selectOption({ text: valor });
|
|
}
|
|
expect(fecha.value).toBe('2024-02-29');
|
|
expect(fecha.valid).toBe(true);
|
|
});
|
|
|
|
it('navega las sugerencias con flechas y Enter y cierra con Escape manteniendo el foco', async () => {
|
|
const mes = await TestbedHarnessEnvironment.loader(fixture).getHarness(
|
|
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
|
|
await mes.enterText('ma');
|
|
tecla(entrada('mes'), 'ArrowDown', 40);
|
|
tecla(entrada('mes'), 'ArrowDown', 40);
|
|
tecla(entrada('mes'), 'ArrowUp', 38);
|
|
expect(entrada('mes').getAttribute('aria-activedescendant')).toBeTruthy();
|
|
tecla(entrada('mes'), 'Enter', 13);
|
|
await fixture.whenStable();
|
|
expect(await mes.getValue()).toBe('Marzo');
|
|
expect(await mes.isOpen()).toBe(false);
|
|
await mes.clear(); await mes.enterText('ab');
|
|
tecla(entrada('mes'), 'Escape', 27);
|
|
await fixture.whenStable();
|
|
expect(await mes.isOpen()).toBe(false);
|
|
expect(await mes.isFocused()).toBe(true);
|
|
expect(await mes.getValue()).toBe('ab');
|
|
});
|
|
|
|
it.each([
|
|
['31', 'Abril', '2026'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2026'],
|
|
['29', 'Febrero', '1900'], ['0', 'Enero', '2026'], ['32', 'Enero', '2026'],
|
|
['1.5', 'Enero', '2026'], ['1', 'Enero', '0'], ['1', 'Enero', '10000'],
|
|
['1', 'Enero', '-1'], ['1', 'Enero', '20e2'],
|
|
])('rechaza fecha imposible o entrada inválida %s / %s / %s', async (dia, mes, anio) => {
|
|
await capturar(dia, mes, anio);
|
|
expect(fecha.value).toBe('');
|
|
expect(fecha.invalid).toBe(true);
|
|
});
|
|
|
|
it.each(['2000', '2024'])('admite 29 de febrero en el año bisiesto %s', async anio => {
|
|
await capturar('29', 'Febrero', anio);
|
|
expect(fecha.value).toBe(`${anio}-02-29`);
|
|
expect(fecha.valid).toBe(true);
|
|
});
|
|
|
|
it('invalida el día al cambiar mes o año sin corregirlo silenciosamente ni conservar el ISO anterior', async () => {
|
|
await capturar('31', 'Marzo', '2024');
|
|
expect(fecha.value).toBe('2024-03-31');
|
|
await escribir('mes', 'Abril');
|
|
expect(fecha.value).toBe('');
|
|
expect(entrada('dia').value).toBe('31');
|
|
expect(control.diasSugeridos).toHaveLength(30);
|
|
await capturar('29', 'Febrero', '2024');
|
|
expect(control.diasSugeridos).toHaveLength(29);
|
|
await escribir('anio', '2025');
|
|
expect(fecha.value).toBe('');
|
|
expect(fecha.invalid).toBe(true);
|
|
expect(entrada('dia').value).toBe('29');
|
|
expect(control.diasSugeridos).toHaveLength(28);
|
|
await escribir('anio', '2024');
|
|
expect(fecha.value).toBe('2024-02-29');
|
|
});
|
|
|
|
it.each(['dia', 'mes', 'anio'])('vaciar %s invalida inmediatamente una fecha previamente válida', async parte => {
|
|
await capturar('26', 'Octubre', '2026');
|
|
await escribir(parte, '');
|
|
expect(fecha.value).toBe('');
|
|
expect(fecha.invalid).toBe(true);
|
|
});
|
|
|
|
it('muestra un único error asociado al salir del grupo o al solicitar validación', async () => {
|
|
const dia = entrada('dia');
|
|
dia.focus();
|
|
entrada('mes').focus();
|
|
fixture.detectChanges();
|
|
expect(fecha.touched).toBe(false);
|
|
expect(root.querySelector('.error')).toBeNull();
|
|
root.querySelector('button')!.focus();
|
|
fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges();
|
|
expect(fecha.touched).toBe(true);
|
|
expect(root.querySelectorAll('.error')).toHaveLength(1);
|
|
for (const input of root.querySelectorAll('input')) {
|
|
expect(input.getAttribute('aria-describedby')).toContain(control.id + '-error');
|
|
expect(input.getAttribute('aria-required')).toBe('true');
|
|
}
|
|
fecha.reset(''); fixture.detectChanges();
|
|
expect(root.querySelector('.error')).toBeNull();
|
|
fecha.markAllAsTouched(); fixture.detectChanges();
|
|
expect(root.querySelector('.error')?.textContent).toContain('completa día, mes y año');
|
|
await capturar('31', 'Abril', '2026');
|
|
expect(root.querySelector('.error')?.textContent).toContain('ese día no existe');
|
|
expect(dia.getAttribute('aria-invalid')).toBe('true');
|
|
await escribir('dia', '30');
|
|
expect(root.querySelector('.error')).toBeNull();
|
|
});
|
|
|
|
it('acepta valores externos sin emitir cambios adicionales y no normaliza fechas inválidas', async () => {
|
|
const cambios = vi.fn();
|
|
fecha.valueChanges.subscribe(cambios);
|
|
fecha.setValue('2024-02-29'); fixture.detectChanges();
|
|
await fixture.whenStable();
|
|
expect(cambios).toHaveBeenCalledExactlyOnceWith('2024-02-29');
|
|
expect(entrada('dia').value).toBe('29');
|
|
expect(entrada('mes').value).toBe('Febrero');
|
|
expect(entrada('anio').value).toBe('2024');
|
|
expect(fecha.valid).toBe(true);
|
|
for (const valor of ['2026-02-30', '2026-13-01', 'ayer', '2026-1-1', '2026-10-26T00:00:00Z']) {
|
|
fecha.setValue(valor); fixture.detectChanges();
|
|
expect(fecha.value).toBe(valor);
|
|
expect(fecha.invalid).toBe(true);
|
|
}
|
|
fecha.reset(''); fixture.detectChanges();
|
|
await fixture.whenStable();
|
|
expect(Array.from(root.querySelectorAll('input')).every(input => input.value === '')).toBe(true);
|
|
});
|
|
|
|
it('propaga disabled y permite años históricos y futuros sin listas enormes', async () => {
|
|
fecha.disable(); fixture.detectChanges();
|
|
expect(Array.from(root.querySelectorAll('input')).every(input => input.disabled)).toBe(true);
|
|
fecha.enable(); fixture.detectChanges();
|
|
for (const anio of ['0001', '1500', '2100', '9999']) {
|
|
await capturar('1', 'Enero', anio);
|
|
expect(fecha.value).toBe(`${anio}-01-01`);
|
|
expect(fecha.valid).toBe(true);
|
|
expect(control.aniosSugeridos.length).toBeLessThanOrEqual(7);
|
|
expect(control.aniosSugeridos).toContain(anio);
|
|
expect(control.aniosSugeridos.every(opcion => Number(opcion) >= 1 && Number(opcion) <= 9999)).toBe(true);
|
|
}
|
|
});
|
|
});
|