// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing // until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and // the notice. Responses are synthetic, shaped like /cacu/indicadores//periodos and /datos. import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; import { By } from '@angular/platform-browser'; import { MatDialog } from '@angular/material/dialog'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresHistorico } from './indicadores-historico'; import { AVISO_CACU, HISTORICO_CACU } from './indicadores-historico-config'; import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; } const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`); const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1']; const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']; const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // Every measure the catalog could publish, reserved ones included: publishing them must not activate them. const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) { const contrato = opciones.contrato ?? CONTRATOS[id]; const fila = (periodo: string, campos: Record) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos }); const vacio = (p: string) => p === opciones.sinPoblacion; const filas = contrato === 'C2' ? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })]) : contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null })) : periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' })); return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' ? 'paciente' : 'examen', filas, categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } }, ...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) }; } describe('Histórico de CaCu', () => { let fixture: ReturnType>, http: HttpTestingController; const abrirDialogo = vi.fn(); function montar(catalog: Indicador[] = CATALOGO, active = false) { TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }] }); TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active); fixture.detectChanges(); } afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); }); // Answers in waves, because the shared request queue runs four at a time. `pedidos` keeps what each data request asked for. const pedidos: { id: string; periodos: string[] }[] = []; function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) { for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { for (const r of ola) { const url = r.request.url, id = url.split('/').at(-2)!; if (opciones.fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; } if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] }); else { const periodos = r.request.params.get('periodos')!.split(','); pedidos.push({ id, periodos }); r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id))); } } fixture.detectChanges(); } } beforeEach(() => { pedidos.length = 0; }); const root = () => fixture.nativeElement as HTMLElement; const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[]; const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!; const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo; const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!; it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => { // Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it. montar(); http.expectNone(() => true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); const vistos = new Set(); for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { for (const r of ola) { vistos.add(r.request.url.split('/').at(-2)!); const id = r.request.url.split('/').at(-2)!; if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) }); else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(','))); } fixture.detectChanges(); } expect([...vistos].sort()).toEqual([...ACTIVOS].sort()); for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false); }); it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => { montar(CATALOGO, true); responder(); expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo)); expect(paneles()).toHaveLength(9); expect(graficas()).toHaveLength(6); const reservados = paneles().slice(6); expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true); expect(reservados.map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']); expect(reservados[0].textContent).toContain('Integración pendiente'); expect(reservados[2].textContent).toContain('Pendiente de validación'); // Title and description, no figures, no invented numbers. expect(reservados[2].textContent).toContain('banda de riesgo de CIN2+'); expect(reservados.every(p => !/\d+ de \d+|0 %|rango/i.test(p.querySelector('p.rango')?.textContent ?? ''))).toBe(true); }); it('un panel reservado sigue reservado aunque el catálogo no lo publique ni lo publique', () => { // Pins down: the state of a reserved panel comes from the config alone. for (const catalogo of [ACTIVOS.map(item), CATALOGO]) { montar(catalogo, true); responder(); expect(paneles().slice(6).map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']); fixture.destroy(); TestBed.resetTestingModule(); } }); it('el aviso de validación clínica y supresión se ve siempre', () => { montar(); const aviso = root().querySelector('[data-aviso="historico"]')!; expect(aviso.textContent).toBe(AVISO_CACU); expect(aviso.textContent).toContain('validación clínica'); expect(aviso.textContent).toContain('supresión'); }); it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => { // Pins down the first request: the page asks for the latest five months, not the twelve it could. montar(CATALOGO, true); responder(); expect(pedidos).toHaveLength(6); for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5)); expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)'); }); it('elegir «Todos» pide solo los periodos que faltan y los suma', () => { montar(CATALOGO, true); responder(); pedidos.length = 0; fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder(); expect(pedidos).toHaveLength(6); for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7)); expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)'); expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12); // Going back to five is local: nothing is asked again. pedidos.length = 0; fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder(); expect(pedidos).toEqual([]); expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)'); }); it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => { montar(CATALOGO, true); responder(); pedidos.length = 0; fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder(); expect(pedidos).toHaveLength(6); for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5)); pedidos.length = 0; fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder(); fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder(); expect(pedidos).toEqual([]); }); it('una medida activa que el catálogo no publica es «Integración pendiente» y no se consulta', () => { montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder(); const panel = panelDe(tituloDe('cacu_eu13')); expect(panel.textContent).toContain('Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.'); expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false); expect(graficas()).toHaveLength(5); }); it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => { montar(CATALOGO, true); responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') }); const panel = panelDe(tituloDe('cacu_eu13')); expect(panel.querySelector('[role="alert"]')).not.toBeNull(); expect(panel.textContent).not.toContain('private'); expect(graficas()).toHaveLength(5); const reintentar = panel.querySelector('button') as HTMLButtonElement; reintentar.click(); fixture.detectChanges(); responder(); expect(graficas()).toHaveLength(6); }); it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => { // Pins down the expected contract: the panel does not draw a C1 where it declared a composition. montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} }); const panel = panelDe(tituloDe('cacu_eu7')); expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1'); expect(graficas()).toHaveLength(5); }); it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => { montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} }); expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]); expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull(); const eu7 = panelDe(tituloDe('cacu_eu7')); expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)'); expect(eu7.textContent).toContain('oct 2025'); expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]); }); it('los tiempos hablan de citologías', () => { montar(CATALOGO, true); responder(); for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) { expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías'); expect(panelDe(tituloDe(id)).textContent).toContain('las citologías'); expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf'); } }); it('sin ninguna medida activa en el catálogo no hay paneles ni consultas', () => { montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true); expect(paneles()).toEqual([]); http.expectNone(() => true); }); });