import { Component, 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 { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis'; import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; import { analisisAgregado } from './indicadores-analisis.service'; import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing'; // Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer // (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group // sends to Seguimiento, and the tab's requests and states. The fixtures are in indicadores-analisis.testing.ts. describe('Respuesta del análisis', () => { it('admite el agregado de la cohorte, con la extensión de grupos y el arreglo de indicadores vacío', () => { // Fails if the real answer (with the fields the prototype leaves empty) stops being accepted. expect(analisisAgregado(agregadoJson()).grupos).toHaveLength(6); }); it('rechaza lo que no es un agregado: filas de paciente, un grupo suprimido con conteo o un grupo publicado bajo el umbral', () => { // Fails if a guard stops rejecting patient rows at any depth, or a count that should be hidden. expect(() => analisisAgregado({ ...agregadoJson(), simulado: false })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), pacientes: [] })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false, items: [{ id_seudonimo: 'M-1' }] }] })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_4', n: 3, suprimido: true }] })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 4, suprimido: false }] })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), grupos: [{ codigo: 'BIRADS_5', n: 6, suprimido: false }, { codigo: 'BIRADS_5', n: 7, suprimido: false }] })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), revision: 'abc' })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), corte: '2026-13-40' })).toThrow(); expect(() => analisisAgregado({ ...agregadoJson(), grupos: [] })).toThrow(); }); }); describe('Figura del análisis', () => { it('dibuja una barra por categoría con sus pacientes y la suprimida vacía, gris y sin cifra', () => { // Fails if a suppressed category is drawn as a zero count, or loses its explanation. const fig = gruposFigura(agregado(), 'claro'); const barra = fig.data[0]; expect(barra['x']).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); expect(barra['y']).toEqual([0, 0, 0, 0, 6, 0]); expect((barra['text'] as string[]).filter(t => t === 'No publicado')).toHaveLength(5); expect((barra['hovertemplate'] as string[])[0]).toContain('Menos de 5 pacientes: no se publica'); expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes'); }); it('un clic solo da el código de una barra publicada', () => { // Fails if a click on a suppressed or unknown bar could open its list. expect(grupoDelClic({ points: [{ customdata: 'BIRADS_5' }] }, agregado())).toBe('BIRADS_5'); expect(grupoDelClic({ points: [{ customdata: 'BIRADS_4' }] }, agregado())).toBeUndefined(); expect(grupoDelClic({ points: [{ customdata: 'OTRO' }] }, agregado())).toBeUndefined(); expect(grupoDelClic({ points: [{}] }, agregado())).toBeUndefined(); expect(grupoDelClic(undefined, agregado())).toBeUndefined(); }); it('escribe los códigos como en la clínica', () => { expect(etiquetaBirads('BIRADS_4A')).toBe('BI-RADS 4A'); expect(etiquetaBirads('OTRO')).toBe('OTRO'); }); }); describe('Selección que va a Seguimiento', () => { it('un grupo publicado lleva su filtro, el corte, el nombre, cuántas pacientes cuenta y la cohorte con su revisión', () => { // Fails if the list is opened without the cohort's revision, at another cut-off, or on another group. expect(seleccionDeGrupo(agregado(), 'BIRADS_5')).toEqual({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 6, contexto: CONTEXTO }); }); it('un grupo suprimido o desconocido no abre nada y dice por qué', () => { // Fails if the list of a group the answer hid could be opened. expect(motivoSinLista(agregado(), 'BIRADS_4')).toBe(MOTIVO_GRUPO_SUPRIMIDO); expect(seleccionDeGrupo(agregado(), 'BIRADS_4')).toBeUndefined(); expect(seleccionDeGrupo(agregado(), 'OTRO')).toBeUndefined(); expect(motivoSinLista(agregado(), 'BIRADS_5')).toBeUndefined(); }); it('hoy se escribe como la fecha de un campo de fecha, en el día del usuario', () => { expect(hoyIso(new Date(2026, 10, 3, 23, 59))).toBe('2026-11-03'); }); }); @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub { readonly plotClick = output(); } describe('Pestaña Análisis epidemiológico', () => { let fixture: ReturnType>, http: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro'); }); afterEach(() => { fixture.destroy(); http.verify(); }); const root = () => fixture.nativeElement as HTMLElement; const text = () => root().textContent as string; const pedido = (corte = hoyIso()) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte); const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); }; const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined; // The date goes in as the user would type it; ngModel writes its value in a microtask. async function escribirCorte(valor: string) { // A form control is registered in a microtask after its first render: it is only ready to be typed into after that. fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); const c = root().querySelector('input[name="corte"]') as HTMLInputElement; c.value = valor; c.dispatchEvent(new Event('input', { bubbles: true })); c.dispatchEvent(new Event('change', { bubbles: true })); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); expect(c.value, 'el campo conserva lo escrito').toBe(valor === '2026-02-31' ? '' : valor); } it('no pide nada hasta abrirse; luego pide el agregado al corte de hoy y lo dibuja con su tabla', () => { // Fails if the tab loads while hidden, or its first request stops carrying a cut-off. fixture.detectChanges(); http.expectNone(() => true); abrir(); expect(text()).toContain('Pacientes por categoría BI-RADS'); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.'); expect(text()).toContain('No estima incidencia, recurrencia ni supervivencia.'); const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[]; expect(filas.map(f => f.querySelector('th')!.textContent!.trim())).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); expect(filas.map(f => f.children[1].textContent!.trim())).toEqual(['No publicado', 'No publicado', 'No publicado', 'No publicado', '6', 'No publicado']); }); it('encabeza la vista y deriva las dos tarjetas de los estados de los grupos, sin sumar pacientes', () => { // Fails if the cards count patients instead of categories, appear before an answer, or the heading and denominator are lost. abrir(); expect(root().querySelector('h2')!.textContent).toBe('Análisis epidemiológico'); expect(root().querySelector('app-indicador-kpi-card')).toBeNull(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); const tarjetas = Array.from(root().querySelectorAll('app-indicador-kpi-card')) as HTMLElement[]; expect(tarjetas.map(t => t.querySelector('h3')!.textContent)).toEqual(['Categorías publicadas', 'Categorías no publicadas']); expect(tarjetas.map(t => t.querySelector('.value')!.textContent!.trim())).toEqual(['1', '5']); expect(tarjetas[0].textContent).toContain('de 6 categorías BI-RADS'); expect(tarjetas[0].textContent).not.toContain('6 pacientes'); expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS'); expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.'); expect(text()).toContain('abrir la lista en Seguimiento'); }); it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => { // Fails if the cards stay on screen without an answer with categories. abrir(); const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true })); pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges(); expect(Array.from(root().querySelectorAll('app-indicador-kpi-card .value')).map(v => v.textContent!.trim())).toEqual(['0', '6']); fixture.componentInstance.consultar(); fixture.detectChanges(); expect(root().querySelector('app-indicador-kpi-card')).toBeNull(); pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges(); expect(root().querySelector('app-indicador-kpi-card')).toBeNull(); }); it('«Consultar» pide el agregado a la fecha elegida y la respuesta tardía de una consulta anterior no se dibuja', async () => { // Fails if a slow answer replaces the aggregate of a later cut-off. abrir(); const primera = pedido(); primera.flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); await escribirCorte('2026-09-01'); expect(fixture.componentInstance.corte).toBe('2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges(); const lenta = pedido('2026-09-01'); // The button is disabled while a query runs, so the later query comes from the code (a retry, a programmatic refresh). expect(boton('Consultar')!.disabled).toBe(true); await escribirCorte('2026-08-01'); fixture.componentInstance.consultar(); fixture.detectChanges(); expect(lenta.cancelled).toBe(true); pedido('2026-08-01').flush(agregadoJson({ corte: '2026-08-01' })); fixture.detectChanges(); expect(text()).toContain('Fecha de corte: 2026-08-01.'); }); it('una fecha que no es de calendario no sale del navegador', async () => { // Fails if an invalid cut-off is sent to the server. abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); await escribirCorte('2026-02-31'); boton('Consultar')!.click(); fixture.detectChanges(); http.expectNone(() => true); expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte'); }); it('si ninguna categoría se publica, lo dice y conserva «No publicado»: la respuesta no distingue una cohorte vacía de grupos pequeños', () => { // Fails if an empty cohort is announced when the answer cannot tell it, or the explanation of the suppression is lost. abrir(); const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true })); pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges(); expect(text()).toContain('Ninguna categoría alcanza el mínimo de 5 pacientes para publicarse a esta fecha de corte.'); expect(text()).not.toContain('Sin pacientes'); expect(Array.from(root().querySelectorAll('tbody tr')).every(f => f.children[1].textContent!.trim() === 'No publicado' && !f.querySelector('button'))).toBe(true); }); it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => { // Fails if the table offers the patients of a hidden group. abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[]; expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]); expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO); expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento'); }); it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => { // Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits. const emitidas: SeleccionPacientes[] = []; fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s)); abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); (root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement).click(); fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_5' }] }); fixture.componentInstance.clicGrupo({ points: [{ customdata: 'BIRADS_4' }] }); expect(emitidas).toHaveLength(2); expect(emitidas[0]).toEqual(emitidas[1]); expect(emitidas[0]).toMatchObject({ filtros: { birads: 'BIRADS_5' }, corte: hoyIso(), esperados: 6, contexto: { ...CONTEXTO } }); }); it('al volver restaura el foco en el control de origen y no repite ninguna consulta', () => { // Fails if coming back from Seguimiento loses the focus or the answer already loaded. fixture.componentInstance.verPacientes.subscribe(() => undefined); abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); const origen = root().querySelector('tr[data-grupo="BIRADS_5"] button.ver') as HTMLButtonElement; origen.focus(); origen.click(); (document.activeElement as HTMLElement | null)?.blur(); fixture.componentInstance.restaurar(); http.expectNone(() => true); expect(document.activeElement).toBe(origen); expect(fixture.componentInstance.datos()?.grupos).toHaveLength(6); }); it('sin endpoint publicado queda pendiente, sin mostrarse como un error', () => { // Fails if a 404 is shown as a broken page instead of a feature not yet published. abrir(); pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges(); expect(text()).toContain('Funcionalidad pendiente de publicación'); expect(root().querySelector('[role=alert]')).toBeNull(); }); it('con la cohorte no disponible (503) lo dice y deja reintentar; el reintento repite la misma consulta', () => { // Fails if a cohort that is not configured is hidden, or the retry asks for another date. abrir(); pedido().flush({ error: 'Cohorte no disponible' }, { status: 503, statusText: 'Unavailable' }); fixture.detectChanges(); expect(text()).toContain('La cohorte no está disponible en este momento.'); boton('Reintentar consulta')!.click(); fixture.detectChanges(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); expect(root().querySelector('tbody')).not.toBeNull(); }); it('un error del servicio se muestra con su reintento y con el mensaje fijo, nunca con el cuerpo', () => { // Fails if a real failure is swallowed or the server's own text reaches the page. abrir(); pedido().flush('detalle interno', { status: 500, statusText: 'Error' }); fixture.detectChanges(); expect(root().querySelector('[role=alert]')?.textContent).toContain('El servicio encontró un error interno'); expect(text()).not.toContain('detalle interno'); expect(boton('Reintentar consulta')).toBeDefined(); }); it('una respuesta fuera de contrato no se dibuja', () => { // Fails if an answer with patient rows or counts under the threshold reaches the page. abrir(); pedido().flush({ ...agregadoJson({ corte: hoyIso() }), pacientes: [{ id_seudonimo: 'M-0001' }] }); fixture.detectChanges(); expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado'); expect(root().querySelector('tbody')).toBeNull(); expect(text()).not.toContain('M-0001'); }); });