// Covers the follow-up list when the epidemiological analysis opens it on a group of the cohort: what it asks for (whole // cohort, the analysis' cut-off, the group's filter and the cohort with its revision), what the user reads, how the // selection is kept, refined and removed, and that a list which does not belong to the selection on screen is never // drawn. Fixture: fixtures/cama_seguimiento.json shaped like the cohort's list (two filters, the cohort quoted back). import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; import { CONTEXTO, CORTE } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; const base = () => structuredClone(fixtureData) as unknown as Record; const NULOS = { birads: null, grupo_edad: null }; const OPCIONES = { birads: ['BIRADS_4', 'BIRADS_5', 'BIRADS_6'], grupo_edad: ['40-49', '50-59', '60-69'] }; // The cohort's answer: only the two filters it announces, the cohort quoted back, window 0 and the filters it applied. function cohorte(filtros: Record, pagina = 1, tam = 50, extra: Record = {}) { const d = base(), todos = d['items'] as unknown[]; d['items'] = todos.slice((pagina - 1) * tam, pagina * tam); d['paginacion'] = { page: pagina, page_size: tam, total_items: todos.length, total_pages: Math.max(1, Math.ceil(todos.length / tam)) }; d['corte'] = CORTE; d['ventana'] = { meses: 0, desde: '2025-01-01', hasta: CORTE }; d['filtros'] = { ...NULOS, ...filtros }; d['filtros_disponibles'] = [ { clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: OPCIONES.birads.map(c => ({ codigo: c, etiqueta: c })) }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: OPCIONES.grupo_edad.map(c => ({ codigo: c, etiqueta: c })) }]; return { ...d, ...CONTEXTO, ...extra }; } const seleccion = (id: number, extra: Partial = {}): SeleccionSeguimiento => ({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id, ...extra }); const PARAMS = { meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO, birads: 'BIRADS_5' }; describe('Seguimiento de CaMa abierto desde el análisis', () => { let fixture: ReturnType>, http: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('active', false); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); }); const root = () => fixture.nativeElement as HTMLElement; const solicitud = (dominio = 'cama') => http.expectOne(r => r.url === `/${dominio}/seguimiento`); const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } const abrirCon = (sel: SeleccionSeguimiento) => { fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', sel); fixture.detectChanges(); }; const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined; const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!; async function elegir(etiqueta: string, valor: string) { const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor || o.value.endsWith(valor))!.value; s.dispatchEvent(new Event('change')); await asentar(); } const banner = () => root().querySelector('.seleccion')?.textContent?.replace(/\s+/g, ' ').trim(); const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim()); const exportar = () => root().querySelector('app-seguimiento-exportar'); it('pide toda la cohorte con el corte del análisis, el filtro del grupo y la cohorte con su revisión, y lo dice con su etiqueta y un camino de regreso', async () => { // Fails if the list opens on another window, cut-off, group or cohort revision, or hides where it came from. http.expectNone(() => true); abrirCon(seleccion(1)); const r = solicitud(); expect(parametros(r)).toEqual(PARAMS); r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico: Categoría BI-RADS: BI-RADS 5. Toda la cohorte, corte 2026-10-20.'); expect(boton('Volver al análisis')).toBeDefined(); expect(boton('Quitar selección')).toBeDefined(); expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.'); expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']); expect(fixture.componentInstance.etiquetaDatos()).toBe('Categoría BI-RADS: BI-RADS 5'); expect(exportar()).not.toBeNull(); }); it.each([1, 3, 6, 12])('una selección calculada con la ventana de %i meses pide esa misma ventana, con el corte, el filtro y la cohorte, y no avisa de diferencia si los pacientes coinciden', async (m) => { // Fails if a bar computed over a window opens the whole cohort (or another window), so the list shows other patients than counted. abrirCon(seleccion(m, { meses: m, filtros: { birads: 'BIRADS_5', grupo_edad: '50-59' } })); const r = solicitud(); expect(parametros(r)).toEqual({ ...PARAMS, meses: String(m), grupo_edad: '50-59' }); r.flush(cohorte({ birads: 'BIRADS_5', grupo_edad: '50-59' }, 1, 50, { ventana: { meses: m, desde: '2026-01-01', hasta: CORTE } })); await asentar(); expect(root().querySelector('.diferencia')).toBeNull(); expect(fixture.componentInstance.draft.meses).toBe(m); expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true); }); it('sin una selección la ventana no ofrece «Toda la cohorte» y la consulta no cita ninguna cohorte', async () => { // Fails if the whole cohort becomes a plain window of the list, or a plain query quotes a revision. fixture.componentRef.setInput('active', true); fixture.detectChanges(); const r = solicitud(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); r.flush({ ...base() }); await asentar(); expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); expect(root().querySelector('.seleccion')).toBeNull(); }); it('si la lista no tiene tantos pacientes como contó el análisis para la misma selección y revisión, lo avisa y no deja exportarla; si coinciden, calla y exporta', async () => { // Fails if a list that breaks the contract can be exported as if it were the group that was counted. abrirCon(seleccion(1, { esperados: 30 })); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); expect(root().querySelector('.diferencia')?.getAttribute('role')).toBe('alert'); expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección y la lista muestra 27. No coinciden, por lo que este resultado no se puede exportar.'); expect([...exportar()!.querySelectorAll('button')].every(b => b.disabled)).toBe(true); expect(root().querySelector('table')).not.toBeNull(); fixture.componentRef.setInput('seleccion', seleccion(2, { esperados: 27 })); fixture.detectChanges(); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); expect(root().querySelector('.diferencia')).toBeNull(); expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true); }); it('una respuesta que pierde el filtro, cambia la ventana o el corte, o no es la cohorte ni la revisión pedidas no se dibuja ni se puede exportar', async () => { // Fails if rows of another population or of another revision are shown (or exported) under the name of the analysis' group. for (const [mal, respuesta] of [ ['pierde el filtro', cohorte({})], ['cambia la ventana', cohorte({ birads: 'BIRADS_5' }, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })], ['cambia el corte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { corte: '2026-09-01' })], ['otra revisión', cohorte({ birads: 'BIRADS_5' }, 1, 50, { revision: 'f'.repeat(64) })], ['otra cohorte', cohorte({ birads: 'BIRADS_5' }, 1, 50, { cohorte: 'otra' })], ['sin cohorte', (() => { const d: Record = cohorte({ birads: 'BIRADS_5' }); delete d['revision']; return d; })()], ] as const) { fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion(mal.length * 7 + mal.charCodeAt(1))); fixture.detectChanges(); solicitud().flush(respuesta); await asentar(); expect(root().querySelector('[role=alert]')?.textContent, mal).toContain('no corresponde a la selección consultada'); expect(root().querySelector('table'), mal).toBeNull(); expect(exportar(), mal).toBeNull(); expect(root().textContent, mal).not.toContain('M-0081'); } }); it('403, 409 y 503 dicen qué pasó, no dejan ninguna lista a la vista y no exponen el cuerpo del servidor', async () => { // Fails if a refused list is explained with the server's text, or the previous rows stay under the failed selection. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); for (const [status, texto] of [[403, 'no hay acceso, o la selección tiene muy pocos pacientes'], [409, 'La cohorte cambió desde que se calculó el análisis'], [503, 'La cohorte no está disponible en este momento']] as const) { const c = root().querySelector('input[name="corte"]') as HTMLInputElement; c.value = `2026-01-0${status === 403 ? 1 : status === 409 ? 2 : 3}`; c.dispatchEvent(new Event('input')); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); const r = solicitud(); expect(r.request.params.get('corte'), String(status)).toBe(c.value); r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar(); const alerta = root().querySelector('[role=alert]')?.textContent; expect(alerta, String(status)).toContain(texto); expect(alerta, String(status)).not.toContain('detalle interno'); expect(root().querySelector('table'), String(status)).toBeNull(); expect(exportar(), String(status)).toBeNull(); } }); it('una selección nueva cancela la anterior: su respuesta tardía no se dibuja y mientras carga no queda la lista anterior', async () => { // Fails if a slow answer replaces the list of a later selection, or the old rows stay under the new banner. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); expect(root().querySelector('table')).not.toBeNull(); fixture.componentRef.setInput('seleccion', seleccion(2, { filtros: { birads: 'BIRADS_6' }, etiqueta: 'Categoría BI-RADS: BI-RADS 6' })); fixture.detectChanges(); const r2 = solicitud(); expect(root().querySelector('table')).toBeNull(); expect(root().textContent).toContain('Cargando seguimiento'); fixture.componentRef.setInput('seleccion', seleccion(3, { filtros: { birads: 'BIRADS_4' }, etiqueta: 'Categoría BI-RADS: BI-RADS 4' })); fixture.detectChanges(); const r3 = solicitud(); expect(r2.cancelled).toBe(true); expect(() => r2.flush(cohorte({ birads: 'BIRADS_6' }))).toThrow(); r3.flush(cohorte({ birads: 'BIRADS_4' })); await asentar(); expect(banner()).toContain('BI-RADS 4'); expect(banner()).not.toContain('BI-RADS 6'); expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 4'); }); it('al paginar conserva la selección, el corte, el filtro y la cohorte, y el nombre sigue a las filas', async () => { // Fails if a later page is asked without the group's filter or the cohort's revision, or loses the name of the selection. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' }, 1, 10)); await asentar(); boton('Siguiente')!.click(); fixture.detectChanges(); const r = solicitud(); expect(parametros(r)).toEqual({ ...PARAMS, page: '2', page_size: '10' }); r.flush(cohorte({ birads: 'BIRADS_5' }, 2, 10)); await asentar(); expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); expect(fixture.componentInstance.etiquetaDatos()).toContain('BI-RADS 5'); expect(banner()).toContain('BI-RADS 5'); }); it('la selección sobrevive a salir de la pestaña y volver, sin pedir otra vez; «Volver al análisis» avisa a la página', async () => { // Fails if coming back to the tab repeats the request, drops the selection or the way back stops working. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); let volvio = 0; fixture.componentInstance.volverAlAnalisis.subscribe(() => volvio++); fixture.componentRef.setInput('active', false); fixture.detectChanges(); fixture.componentRef.setInput('active', true); fixture.detectChanges(); http.expectNone(() => true); expect(banner()).toContain('BI-RADS 5'); expect(root().querySelector('table')).not.toBeNull(); boton('Volver al análisis')!.click(); expect(volvio).toBe(1); expect(banner()).toContain('BI-RADS 5'); }); it('«Consultar» sin cambios repite la misma selección; con otro filtro refina la misma cohorte, citando su revisión, y lo dice', async () => { // Fails if the banner keeps naming a group after the user narrowed the list, or a refinement leaves the cohort. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); let r = solicitud(); expect(parametros(r)).toEqual(PARAMS); r.flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); expect(banner()).toContain('Pacientes de la selección del análisis epidemiológico'); await elegir('Grupo de edad', '50-59'); boton('Consultar')!.click(); fixture.detectChanges(); r = solicitud(); expect(parametros(r)).toEqual({ ...PARAMS, grupo_edad: '50-59' }); r.flush(cohorte({ birads: 'BIRADS_5', grupo_edad: '50-59' })); await asentar(); expect(banner()).toContain('Pacientes de la cohorte del análisis epidemiológico, corte 2026-10-20. Los filtros y la ventana son los de esta consulta.'); expect(banner()).not.toContain('selección del análisis'); expect(exportar()).not.toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBe('Cohorte del análisis epidemiológico'); expect(root().querySelector('.diferencia')).toBeNull(); expect(ventanas()).toContain('Toda la cohorte'); }); it('«Quitar selección» vuelve a la lista habitual: 3 meses, sin filtros ni nombre, y sin citar la revisión anterior', async () => { // Fails if removing the selection leaves its filter, the whole-cohort window or the old revision behind. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); boton('Quitar selección')!.click(); fixture.detectChanges(); const r = solicitud(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); r.flush(cohorte({}, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); expect(exportar()).not.toBeNull(); }); it('al cambiar de dominio la selección y la cohorte se limpian con la lista', async () => { // Fails if a selection (or its cohort) made in one domain survives into another. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); fixture.componentRef.setInput('seleccion', undefined); fixture.componentRef.setInput('dominio', 'cacu'); fixture.detectChanges(); expect(root().querySelector('.seleccion')).toBeNull(); expect(root().querySelector('table')).toBeNull(); const r = solicitud('cacu'); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); r.flush('', { status: 404, statusText: 'Not Found' }); }); it('una selección que llega con la pestaña inactiva espera a que se abra', async () => { // Fails if the list is asked for while its tab is hidden. fixture.componentRef.setInput('seleccion', seleccion(1)); fixture.detectChanges(); http.expectNone(() => true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); }); });