// What this module covers: CaMa's follow-up as the WebApi's cohort endpoint answers it (`GET /cama/seguimiento`): // the answer's validation and labels, the table the page draws from it, its states, the record of one patient and the // rows of a file. Nothing here is a status, a priority or a figure the data doesn't hold. // Fixtures (`fixtures/cama_seguimiento_cohorte_real*.json`): answers of the endpoint over the local installation's // synthetic CaMa data: `_inicial` (default: today, three months), `_consulta` (six months, BI-RADS 5), the whole cohort // at 2026-11-16 and the 403 body of a group of fewer than five patients. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { ComponentFixture } from '@angular/core/testing'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; import { consultaAplicada, contextoDe, seguimientoTablaResponse, SeguimientoTablaQuery } from './seguimiento-tabla.service'; import { identidadesDe } from './paciente-identidad'; import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; import { flatTable } from './export/tracking-export-table'; import inicialData from './fixtures/cama_seguimiento_cohorte_real_inicial.json'; import consultaData from './fixtures/cama_seguimiento_cohorte_real_consulta.json'; import cohorteData from './fixtures/cama_seguimiento_cohorte_real.json'; import pequenoData from './fixtures/cama_seguimiento_cohorte_real_403.json'; const copia = (v: unknown) => structuredClone(v) as unknown as Record; describe('Seguimiento de CaMa sobre la cohorte del servidor', () => { it('la respuesta cumple el contrato, nombra la cohorte y rotula los códigos sin cambiar los valores enviados', () => { // Pins down: the answer is accepted as is (every row names its patient by `pac_id`, a decimal text), the cohort // context is read from it, and codes read as the clinic writes them while the code stays in `_codigo`. // Fails if the endpoint's shape stops passing the client's validation, or a label replaces a code the requests send. const respuesta = seguimientoTablaResponse(copia(cohorteData)); expect(respuesta.items).toHaveLength(61); expect(identidadesDe(respuesta.items)!.every(i => i.campo === 'pac_id' && /^[1-9][0-9]*$/.test(i.id))).toBe(true); expect(contextoDe(respuesta)).toEqual({ cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: expect.stringMatching(/^[0-9a-f]{64}$/) }); const fila = respuesta.items.find(i => i['birads_codigo'] === 'BIRADS_4')!; expect(fila['birads']).toBe('BI-RADS 4'); expect(respuesta.filtros_disponibles.find(f => f.clave === 'birads')!.opciones.map(o => [o.codigo, o.etiqueta])) .toContainEqual(['BIRADS_4A', 'BI-RADS 4A']); expect(respuesta.filtros_disponibles.find(f => f.clave === 'grupo_edad')!.opciones.map(o => o.etiqueta)) .toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); expect(respuesta.columnas.map(c => c.clave)).toEqual(['pac_id', 'grupo_edad', 'birads', 'biopsia']); }); it('una página o un archivo solo se acepta si es de la consulta, la cohorte y la revisión que se pidieron', () => { // Pins down: the answer must repeat the window, filters and context asked for. Fails if rows of another revision // or another selection could be shown under the title of this one. const respuesta = seguimientoTablaResponse(copia(consultaData)); const contexto = contextoDe(respuesta)!; const pedido: SeguimientoTablaQuery = { corte: respuesta.corte, meses: 6, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto }; expect(consultaAplicada(pedido, respuesta)).toBe(true); expect(consultaAplicada({ ...pedido, contexto: { ...contexto, revision: 'otra' } }, respuesta)).toBe(false); expect(consultaAplicada({ ...pedido, filtros: {} }, respuesta)).toBe(false); expect(consultaAplicada({ ...pedido, meses: 3 }, respuesta)).toBe(false); }); it('la ficha de una paciente muestra lo que trae la fila y deja sin dato estatus, prioridad y días', () => { // Pins down: the record reads BI-RADS, its date, the age group and the biopsy from the row, and what the list // doesn't carry stays `null` (shown as «No disponible»), never a value made up. Fails if the summary fills // status, priority or the days to diagnosis from anywhere. const r = seguimientoTablaResponse(copia(cohorteData)); const conBiopsia = r.items.find(i => i['biopsia'] !== null)!, sinBiopsia = r.items.find(i => i['biopsia'] === null)!; const resumen = toCamaPatientSummary(conBiopsia, r.corte, r.columnas)!; expect(resumen).toMatchObject({ patientId: String(conBiopsia['pac_id']), idField: 'pac_id', cutoff: r.corte, status: null, priority: null, daysMammographyToDiagnosis: null, birads: conBiopsia['birads'], biopsyDate: conBiopsia['biopsia_fecha'] }); expect(resumen.biopsyDateLabel).toBe('Fecha de reporte'); expect(toCamaPatientSummary(sinBiopsia, r.corte, r.columnas)).toMatchObject({ histopathology: null, biopsyDate: null }); }); it('el archivo lleva las columnas del servidor, sin estatus, prioridad ni días de diagnóstico', () => { // Pins down: the file's columns are the announced ones (with their date details) and no other, and a missing biopsy // is `null`. Fails if the files add a column the cohort doesn't have. const r = seguimientoTablaResponse(copia(cohorteData)); const tabla = flatTable({ corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items }); expect(tabla.columns.map(c => c.label)).toEqual(['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Última mastografía: Fecha', 'Resultado histopatológico', 'Resultado histopatológico: Fecha de reporte']); expect(tabla.rows).toHaveLength(61); expect(tabla.rows.some(fila => fila[4] === null && fila[5] === null)).toBe(true); }); }); describe('Seguimiento de CaMa (tabla) con las respuestas del servidor', () => { let fixture: ComponentFixture, 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('active', true); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); }); const root = () => fixture.nativeElement as HTMLElement; const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento'); async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement; const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!; const filas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => [...td.childNodes] .filter(n => n.nodeType !== Node.COMMENT_NODE).map(n => (n.textContent ?? '').trim()).filter(Boolean).join(' '))); const elegir = (etiqueta: string, valor: string) => { const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.value.endsWith(valor))!.value; s.dispatchEvent(new Event('change')); }; it('la primera consulta pide la ventana de 3 meses y dibuja las cuatro columnas de la cohorte con los datos que hay', async () => { // Pins down: the table has the cohort's four columns and no status, priority or days; the first request is three // months, page one of 50, with no cut-off (the server's today); a patient without biopsy reads «No disponible». // Fails if the table asks for or draws a column the endpoint doesn't announce. const r = solicitud(); expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({ meses: '3', page: '1', page_size: '50' }); r.flush(inicialData); await asentar(); expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual( ['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Resultado histopatológico']); expect(filas()).toHaveLength(16); const sin = filas().find(f => f[3] === 'No disponible'); expect(sin).toBeDefined(); expect(sin![2]).toMatch(/^BI-RADS (4|4A|4B|4C|5|6) Fecha: 20\d\d-\d\d-\d\d$/); expect(root().textContent).toContain(`Ventana consultada: ${(inicialData as any).ventana.desde} al ${(inicialData as any).ventana.hasta}.`); }); it('el formulario ofrece los filtros que anuncia el servidor y Consultar envía el filtro elegido, el corte y la revisión que devolvió', async () => { // Pins down: the filters are BI-RADS, age group and biopsy result as announced, and a second query sends the cut-off // the first answer gave, with its cohort, scenario and revision, plus the chosen window and filter. Fails if the revision isn't quoted back or a filter the server doesn't announce appears // (BRCA, stage, size, priority...). solicitud().flush(inicialData); await asentar(); expect([...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim())) .toEqual(['Fecha de corte', 'Ventana de meses', 'Categoría BI-RADS', 'Grupo de edad', 'Resultado de la biopsia', 'Registros por página']); expect([...campo('Resultado de la biopsia').querySelectorAll('option')].map(o => o.text.trim())).toEqual( ['Todos', 'Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Biopsia reportada sin resultado', 'Sin biopsia reportada']); elegir('Ventana de meses', '6'); elegir('Categoría BI-RADS', 'BIRADS_5'); await asentar(); boton('Consultar').click(); fixture.detectChanges(); const r = solicitud(); expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({ meses: '6', page: '1', page_size: '50', corte: (inicialData as any).corte, birads: 'BIRADS_5', cohorte: (inicialData as any).cohorte, escenario: (inicialData as any).escenario, revision: (inicialData as any).revision }); r.flush(consultaData); await asentar(); expect(root().textContent).toContain(`Ventana consultada: ${(consultaData as any).ventana.desde} al ${(consultaData as any).ventana.hasta}.`); expect(filas().every(f => f[2].startsWith('BI-RADS 5'))).toBe(true); }); it('un grupo de menos de cinco pacientes se dice con su motivo y no se dibuja ninguna fila', async () => { // Pins down: the server's 403 for a small selection is shown as a message and clears the table. Fails if rows of a // previous selection stay on screen or the page says nothing. solicitud().flush(inicialData); await asentar(); elegir('Categoría BI-RADS', 'BIRADS_6'); await asentar(); boton('Consultar').click(); fixture.detectChanges(); solicitud().flush(pequenoData, { status: 403, statusText: 'Forbidden' }); await asentar(); expect(root().querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes'); expect(filas()).toHaveLength(0); }); it('si el servidor responde 404 en CaMa dice que la cohorte no está disponible, sin pantalla vacía', async () => { // Pins down: an endpoint that isn't there leaves an informative state. Fails if the tab shows an empty table or an // unhandled error. solicitud().flush({}, { status: 404, statusText: 'Not Found' }); await asentar(); expect(root().querySelector('[role=alert]')?.textContent).toContain('cohorte no está disponible'); }); });