import { Component, input, output } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { By } from '@angular/platform-browser'; import fixtureData from './fixtures/eu7-c2-ejemplos.json'; import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadoresSnapshots } from './indicadores-snapshots'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { GlobalApplied } from './indicadores-memory'; import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', template: '' }) class ChartStub { figure = input(); label = input(); showNotes = input(); animated = input(); plotClick = output(); } describe('EU7 integración Angular y caché compartida', () => { const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0', figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'], filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] }; let f: ReturnType>; let http: HttpTestingController; let data: typeof fixtureData; beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData); f = TestBed.createComponent(IndicadorEu7Escenario); f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); }); afterEach(() => { f.destroy(); http.verify(); vi.useRealTimers(); }); function requests() { const general = http.expectOne(r => r.url.endsWith('/datos') && !r.params.has('estrato')); const escenarios = http.expectOne(r => r.url.endsWith('/datos') && r.params.get('estrato') === 'estatus_seguimiento'); expect(general.request.params.get('periodos')).toBe(escenarios.request.params.get('periodos')); return { general, escenarios }; } function flush() { const r = requests(); r.general.flush(data.general); r.escenarios.flush(data.estatus_seguimiento); f.detectChanges(); } it('carga diferida; dos GET compartidos con el KPI y ningún GET por clic, tema o navegación de selección', () => { f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe(); f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); flush(); expect(f.componentInstance.model!.total).toBe(946); expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]); const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement; expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1); expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682'); const general = data.general; const original = structuredClone(applied); const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf).find(b => b.textContent!.includes('Anormal'))!; anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub; chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges(); expect(f.componentInstance.selection.categoria).toBe('LIEAG'); expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG'); f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges(); expect(f.componentInstance.selection).toEqual({}); f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839'); expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe(); }); it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => { const periods: [string, string] = ['2025-S1', '2025-S2']; for (const d of [data.general, data.estatus_seguimiento]) { d.periodos = periods; d.filas = [...d.filas.map(r => ({ ...r, periodo: '2025-S1', n: r.n * 2 })), ...d.filas] as typeof d.filas; d.totales_estrato = [...d.totales_estrato.map(t => ({ ...t, periodo: '2025-S1', n: t.n * 2 })), ...d.totales_estrato]; } f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush(); expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364); const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub); f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges(); expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2'); expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682); expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined(); expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts); expect(charts.map(chart => chart.animated())).toEqual([true, true]); expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2'); expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true); }); it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => { f.detectChanges(); const r = requests(); r.general.flush(data.general); r.escenarios.flush({}, { status: 500, statusText: 'Internal Server Error' }); f.detectChanges(); expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); f.componentInstance.retry(); http.expectNone(r => r.url.endsWith('/datos') && !r.params.has('estrato')); http.expectOne(r => r.params.get('estrato') === 'estatus_seguimiento').flush(data.estatus_seguimiento); f.detectChanges(); expect(f.componentInstance.status()).toBe('ready'); }); it('timeout cancela transportes y permite recuperación', async () => { vi.useFakeTimers(); f.detectChanges(); const r = requests(); await vi.advanceTimersByTimeAsync(40001); f.detectChanges(); expect(r.general.cancelled && r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.textContent).toContain('tardó demasiado'); f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready'); }); it('error de red permite reintento sin figuras engañosas', () => { f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges(); expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error'); expect(f.componentInstance.donutFigure).toBeUndefined(); f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready'); }); it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => { f.detectChanges(); const old = requests(); f.componentRef.setInput('visible', false); f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S1'] } }); f.detectChanges(); expect(old.general.cancelled && old.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); for (const d of [data.general, data.estatus_seguimiento]) { d.periodos = ['2025-S1']; d.filas.forEach(r => r.periodo = '2025-S1'); d.totales_estrato.forEach(t => t.periodo = '2025-S1'); } f.componentRef.setInput('visible', true); f.detectChanges(); flush(); expect(f.componentInstance.model!.periodo).toBe('2025-S1'); }); it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => { data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); }); it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => { data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = []; f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); expect(f.nativeElement.textContent).toContain('No hay pacientes publicados'); }); it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => { Object.assign(data.general.filas[0], { n: 987654, suprimido: 1 }); Object.assign(data.estatus_seguimiento.filas[0], { n: 987654, suprimido: 1 }); f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido'); expect(f.nativeElement.textContent).not.toContain('987654'); expect(f.nativeElement.querySelector('table caption')).not.toBeNull(); expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0); }); it('catálogo sin capacidad temporal o clínica no inicia GET', () => { f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges(); expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); }); it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => { f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges(); const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure; f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges(); f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars); expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true); }); it('«Cómo leer» muestra solo la descripción y el como_leer publicados de dona y barras, sin la ficha', () => { f.componentRef.setInput('visible', false); f.detectChanges(); const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested); const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; toggle.click(); f.detectChanges(); expect(requested).toHaveBeenCalledTimes(1); expect(f.nativeElement.querySelector('.methodology').textContent).toContain('Metadatos publicados pendientes'); f.componentRef.setInput('metadata', { descripcion: 'Descripción del indicador', ficha: { pregunta: '¿Pregunta?', definicion: 'Definición', unidad: 'pacientes', nota: 'Nota de ficha' }, referencias: [{ tipo: 'cita', etiqueta: 'Referencia', ref: null }], figuras_detalle: [ { figura: 'fig_c2_barras', descripcion: 'Barras por escenario.', como_leer: ['Lee las barras así.', ' '] }, { figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona así.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra figura', como_leer: ['No va.'] }, ], }); f.detectChanges(); const help = f.nativeElement.querySelector('.methodology') as HTMLElement; const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[]; expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Dona de dos anillos', 'Barras por escenario clínico']); expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']); expect(guides[1].querySelector('p')!.textContent).toBe('Barras por escenario.'); expect([...guides[1].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las barras así.']); for (const absent of ['Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior']) expect(help.textContent).not.toContain(absent); expect(help.querySelector('details')).toBeNull(); f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges(); expect(help.textContent).toContain('no publica instrucciones de lectura'); http.expectNone(() => true); }); it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => { f.componentRef.setInput('visible', false); f.detectChanges(); const card = TestBed.createComponent(IndicadorCatalogCard); card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador); card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges(); expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(1); expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0); for (const [domain, id] of [['cacu', 'cacu_eu13'], ['tea', 'M23_pacientes_evaluados'], ['cama', 'cama_birads_456_paciente'], ['tea', 'cacu_eu7']]) { card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges(); expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(0); expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(2); } card.destroy(); http.expectNone(() => true); }); });