// Covers CaMa's history tab: what it requests and when, the controls (interval, periods to show, custom // periods), the pending panels for indicators the catalog does not publish, and error handling. Responses are // synthetic, shaped like /cama/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 { of } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { HISTORICO_CAMA, IndicadoresHistorico } from './indicadores-historico'; import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub { figure?: { data: { name?: string }[] }; label?: string; } const MESES = ['2025-01', '2025-02', '2025-03', '2025-04', '2025-05', '2025-06', '2025-07']; const SEMESTRES = ['2024-S2', '2025-S1']; const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // What 18080 publishes for CaMa, including biopsias, which the history does not draw. const CATALOGO = [item('cama_biopsias', 'C2'), item('cama_birads_456_mastografia', 'C2'), item('cama_birads_456_paciente', 'C2'), item('cama_confirmacion_birads45', 'C1'), item('cama_dias_toma_diagnostico', 'C3r'), item('cama_eu38a', 'C3r')]; const PUBLICADOS = CATALOGO.filter(i => i.id !== 'cama_biopsias'); function datos(id: string, contrato: string, tipo: string, periodos: string[]) { const fila = (periodo: string, campos: Record) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos }); const filas = contrato === 'C2' ? periodos.flatMap(p => [fila(p, { categoria: 'B5', n: 7, orden: 0 }), fila(p, { categoria: 'B4', n: 5, orden: 1 })]) : contrato === 'C1' ? periodos.map(p => fila(p, { valor: 50, numerador: 5, denominador: 10, ic_bajo: 30, ic_alto: 70 })) : 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' && id.includes('paciente') ? 'paciente' : 'examen', filas, categorias: { B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F' }, B4: { etiqueta: 'B4', color: null } } }; } describe('Histórico de CaMa', () => { 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', 'cama'); 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. function responder(fallo?: (r: TestRequest) => boolean) { const vistos: string[] = []; for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { for (const r of ola) { const url = r.request.url; vistos.push(url + (r.request.params.get('periodos') ? '?' + r.request.params.get('periodos') : '')); const id = url.split('/').at(-2)!, entrada = CATALOGO.find(i => i.id === id)!; if (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(','); r.flush(datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos)); } } fixture.detectChanges(); } return vistos; } const root = () => fixture.nativeElement as HTMLElement; const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[]; const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); it('no pide nada hasta que la pestaña está activa, y entonces solo los indicadores de la lista que el catálogo publica', () => { // Fails if the tab loads data while hidden, or if biopsias (not in the history) is requested. montar(); http.expectNone(() => true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); const vistos = responder(); const ids = new Set(vistos.map(u => u.split('/').at(-2))); expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort()); expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false); }); it('dibuja los ocho paneles en el orden del mockup: cinco con gráfica y tres pendientes por falta de indicador', () => { montar(CATALOGO, true); responder(); expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo)); const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent); expect(pendientes).toEqual(['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']); expect(graficas()).toHaveLength(5); expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0); }); it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => { montar(CATALOGO, true); responder(); expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual'); expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)'); }); it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => { montar(CATALOGO, true); responder(); const toggle = fixture.debugElement.query(By.css('mat-button-toggle-group')); toggle.triggerEventHandler('change', { value: 'semestre' }); fixture.detectChanges(); const semestrales = responder(); expect(semestrales.length).toBeGreaterThan(0); expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true); expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)'); toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges(); http.expectNone(() => true); }); it('«Periodos a mostrar» ofrece pasos de cinco y «Todos»; elegir los últimos cinco recorta cada gráfica', () => { montar(CATALOGO, true); responder(); const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } }; expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']); fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)'); }); it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => { montar(CATALOGO, true); responder(); abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(['2025-02', '2025-05']) }); fixture.componentInstance.elegirVentana(-1); fixture.detectChanges(); expect(abrirDialogo).toHaveBeenCalledTimes(1); const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] }; expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES); expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) }); fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges(); expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); }); it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => { // Fails if one failing indicator blanks the others, leaks its body, or cannot be retried. montar(CATALOGO, true); responder(r => r.request.url.includes('cama_eu38a/periodos')); const panel = paneles().find(p => p.querySelector('h2')!.textContent === 'Días de la toma de la mastografía a su resultado')!; expect(panel.querySelector('[role=alert]')).not.toBeNull(); expect(panel.textContent).not.toContain('private'); expect(graficas()).toHaveLength(4); (panel.querySelector('[role=alert] button') as HTMLButtonElement).click(); fixture.detectChanges(); const nuevos = responder(); expect(nuevos.length).toBeGreaterThan(0); expect(paneles().some(p => p.querySelector('[role=alert]'))).toBe(false); expect(graficas()).toHaveLength(5); }); it('sin ningún indicador de la lista en el catálogo no hay paneles ni consultas', () => { montar([item('cama_biopsias', 'C2')], true); http.expectNone(() => true); expect(paneles()).toHaveLength(0); }); });