import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { provideRouter } from '@angular/router'; import { By } from '@angular/platform-browser'; import { NgModel } from '@angular/forms'; import { MatSelect } from '@angular/material/select'; import { IndicadoresPage } from './indicadores-page'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadoresMemory } from './indicadores-memory'; import { Indicador } from './indicadores.models'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; const items: Indicador[] = [ { id: 'A01', titulo: 'Edad', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, { id: 'B02', titulo: 'Evaluación inicial', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, { id: 'M02_sexo', titulo: 'Distribución por sexo', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, { id: 'D04', titulo: 'Seguimiento', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, { id: 'E05', titulo: 'Evaluación final', contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'] }, ]; describe('UX-05C búsqueda local y partición estable', () => { let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; const disconnect = vi.fn(); beforeEach(() => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; }); TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); }); afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); function load(catalog = items, domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); } function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); } function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); } async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } async function search(value: string) { input().value = value; input().dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); await settle(); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); } it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => { load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count); expect(cards().every(c => !c.visible)).toBe(true); http.expectNone(() => true); if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); it.each([ ['sexo', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], ['M02', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], ['tribuci', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], ['SEXO', ['M02_sexo', 'A01', 'B02', 'D04', 'E05'], 1], ['evaluacion', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2], [' EVALUACIÓN ', ['B02', 'E05', 'A01', 'M02_sexo', 'D04'], 2], ['imposible', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], ['', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], [' ', ['A01', 'B02', 'M02_sexo', 'D04', 'E05'], 0], ])('consulta %s preserva todos los objetos y el catálogo original', async (query, ids, count) => { load(); const original = page.catalog(), snapshot = JSON.stringify(original), before = cards(); await search(query as string); expect(cards().map(c => c.indicador.id)).toEqual(ids); expect(page.searchResults().count).toBe(count); expect(page.searchResults().active).toBe(!!(query as string).trim()); expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); for (const card of cards()) { expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id)); expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false); } if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe(''); http.expectNone(() => true); }); it('D.1 mantiene KPI fuera de la búsqueda y del recuento y utiliza un único suffix Material', async () => { load(); await settle(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')); const field = fixture.nativeElement.querySelector('.catalog-search mat-form-field') as HTMLElement; const clear = field.querySelector('button')!; expect(clear.hasAttribute('matIconSuffix')).toBe(true); expect(clear.closest('.mat-mdc-form-field-icon-suffix')).toBeTruthy(); expect(fixture.nativeElement.querySelectorAll('.catalog-search button')).toHaveLength(1); expect(input().type).toBe('search'); for (const query of ['sexo', 'Indicador destacado', '']) { await search(query); expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis); expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados'); expect(cards()).toHaveLength(5); } http.expectNone(() => true); }); it('escritura y limpieza mantienen foco, cursor, etiqueta y ayudas sin HTTP', async () => { load(); await settle(); const field = input(); field.focus(); await search('sexo'); expect(document.activeElement).toBe(field); expect(field.value).toBe('sexo'); field.setSelectionRange(2, 2); fixture.detectChanges(); await settle(); expect(field.selectionStart).toBe(2); expect(field.selectionEnd).toBe(2); expect(field.labels?.[0].textContent).toContain('Buscar indicadores'); for (const id of field.getAttribute('aria-describedby')!.split(' ')) expect(document.getElementById(id)).toBeTruthy(); expect(fixture.nativeElement.querySelector('#catalog-search-result').getAttribute('aria-live')).toBeNull(); const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement; expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); clear.focus(); expect(document.activeElement).toBe(clear); clear.click(); fixture.detectChanges(); await settle(); expect(page.searchQuery()).toBe(''); expect(field.value).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); expect(clear.disabled).toBe(true); expect(input()).toBe(field); expect(document.activeElement).toBe(field); await search('edad'); field.setSelectionRange(2, 2); expect(document.activeElement).toBe(field); expect(field.selectionStart).toBe(2); http.expectNone(() => true); }); it('botón nativo iconográfico conserva nombre, semántica, tamaño y estado sin HTTP', async () => { load(); await settle(); const clear = fixture.nativeElement.querySelector('.catalog-search button') as HTMLButtonElement; expect(clear.type).toBe('button'); expect(clear.disabled).toBe(true); expect(clear.getAttribute('aria-label')).toBe('Limpiar búsqueda'); const icon = clear.querySelector('mat-icon')!; expect(icon.textContent).toBe('close'); expect(icon.getAttribute('aria-hidden')).toBe('true'); expect(clear.textContent).not.toContain('Limpiar'); expect(getComputedStyle(clear).width).toBe('48px'); expect(getComputedStyle(clear).height).toBe('48px'); await search('sexo'); expect(clear.disabled).toBe(false); expect(clear.tabIndex).toBe(0); // jsdom does not synthesize native keyboard activation. Verify that keys remain // available to the browser; Enter/Space activation is a Chrome acceptance check. for (const key of ['Enter', ' ']) { const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); clear.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); } clear.focus(); clear.click(); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(input()); expect(clear.disabled).toBe(true); http.expectNone(() => true); }); it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => { load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle(); const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts(); const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add(); page.applyFilters(); fixture.detectChanges(); respond(); await settle(); c.year = '2025'; c.unit = 'S2'; c.add(); c.year = '2026'; fixture.detectChanges(); await settle(); const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result()); const titleIds = beforePanels.map(p => p.titleId); expect(new Set(titleIds).size).toBe(beforePanels.length); const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement); const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple); const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue')); const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal'); const reacts = runtime.react.mock.calls.length; const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[]; expect(helps).toHaveLength(5); const helpIds = helps.map(button => button.getAttribute('aria-controls')!); expect(new Set(helpIds).size).toBe(5); for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true); helps[0].click(); fixture.detectChanges(); http.expectOne(r => r.url.endsWith('/metadatos')).flush({}); fixture.detectChanges(); await settle(); expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]); for (const query of ['sexo', 'evaluacion', '']) { if (query) await search(query); else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); } for (const card of beforeCards) expect(cards().find(c => c.indicador.id === card.indicador.id)).toBe(card); for (const panel of beforePanels) expect(panels().find(p => p.indicador.id === panel.indicador.id)).toBe(panel); beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c)); beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c)); } expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true); for (const button of helps) expect(button.isConnected).toBe(true); expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); helps[0].click(); fixture.detectChanges(); await settle(); expect(document.getElementById(helpIds[0])?.hidden).toBe(true); expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts); expect(beforePanels.map(p => p.titleId)).toEqual(titleIds); for (const id of titleIds) { const heading = document.getElementById(id)!; expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id); } beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); }); beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i])); expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']); for (const write of writes) expect(write).not.toHaveBeenCalled(); expect(saves).not.toHaveBeenCalled(); expect(restores).not.toHaveBeenCalled(); expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); http.expectNone(() => true); }); it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => { load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo'); b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle(); await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error'); expect(panels()).toEqual([before[2], before[0], before[1]]); http.expectNone(() => true); a.flush({ data: [{ y: [1] }], layout: {} }); await settle(); expect(before[0].result().figure?.data[0]['y']).toEqual([1]); const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} }); expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true); }); it('reordenar el catálogo conserva foco en el selector global existente', async () => { load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); filters()[0].changeMode('manual'); fixture.detectChanges(); await settle(); const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf).at(-1)!; field.focus(); expect(document.activeElement).toBe(field); page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true); page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); http.expectNone(() => true); }); it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => { load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add(); await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe(''); load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].visible).toBe(false); page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]); http.expectNone(() => true); cards()[2].setVisible(true); fixture.detectChanges(); const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} }); expect(filters()[0].selectedPeriods).toEqual(['2025-S1']); await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond(); expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); }); });