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 { IndicadoresPage } from './indicadores-page'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { Indicador } from './indicadores.models'; 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('Selección de indicadores gráficos', () => { let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: 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 = vi.fn(); }); 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 ids() { return cards().map(c => c.indicador.id); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); } it.each([0, 1, 2, 5])('no ofrece buscador y muestra el catálogo completo: %i indicadores', count => { load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull(); expect(cards()).toHaveLength(count); http.expectNone(() => true); }); it('lista todo el catálogo, con todos seleccionados al inicio', () => { load(); expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull(); expect(page.selectedIndicators()).toEqual(items.map(i => i.id)); expect(page.selectionSummary()).toBe('Todos los indicadores'); expect(fixture.nativeElement.textContent).not.toContain('Mostrando 5 de 5 indicadores.'); http.expectNone(() => true); }); it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => { load(); const before = cards(), original = page.catalog(); choose(['B02', 'E05']); expect(ids()).toEqual(['B02', 'E05']); expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]); expect(page.selectionSummary()).toBe('2 indicadores'); expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados'); choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo'); expect(page.catalog()).toBe(original); http.expectNone(() => true); }); it('sin selección no muestra tarjetas y Mostrar todos restaura el catálogo', () => { load(); choose([]); expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0); expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados'); page.showAllIndicators(); fixture.detectChanges(); expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); http.expectNone(() => true); }); it('marcar todos equivale a no filtrar', () => { load(); choose(['A01']); choose(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(page.selectionSummary()).toBe('Todos los indicadores'); }); it('los indicadores destacados no dependen de la selección', () => { load(); const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel')); choose(['A01']); expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis); }); it('ir a un indicador oculto lo vuelve a mostrar y desplaza hasta su tarjeta', async () => { const scroll = vi.fn(); Element.prototype.scrollIntoView = scroll; load(); choose(['A01']); expect(document.querySelector('.indicator-select-panel')).toBeNull(); page.goToIndicator('D04'); fixture.detectChanges(); await fixture.whenStable(); expect(page.selectedIndicators()).toEqual(['A01', 'D04']); await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(1); }); expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento'); page.goToIndicator('A01'); fixture.detectChanges(); await fixture.whenStable(); expect(page.selectedIndicators()).toEqual(['A01', 'D04']); await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(2); }); http.match(() => true).forEach(r => r.flush({ data: [], layout: {} })); }); it('no muestra el botón flotante de navegación por indicadores', () => { load(); expect(fixture.nativeElement.querySelector('.graphic-navigation-trigger')).toBeNull(); http.expectNone(() => true); }); it('cambiar de dominio restablece la selección', () => { load(); choose(['A01']); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.indicatorSelection()).toBeNull(); load(items, 'cacu'); expect(ids()).toEqual(items.map(i => i.id)); }); });