import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { of, Subject, throwError } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing'; import { instanteUtc, PacienteRiesgoTabla } from './paciente-riesgo-tabla'; describe('RIESGO-CACU-02: presentación y aislamiento', () => { function setup(provider?: PacienteRiesgoProvider) { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), ...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] }); const fixture = TestBed.createComponent(PacienteRiesgoTabla); fixture.componentRef.setInput('pacId', '42'); fixture.detectChanges(); fixture.detectChanges(); return fixture; } afterEach(() => { TestBed.inject(HttpTestingController).expectNone(() => true); TestBed.inject(HttpTestingController).verify(); }); it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => { const f = setup(), root: HTMLElement = f.nativeElement; TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42') .flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' }); f.detectChanges(); expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); expect(root.textContent).toContain('Recomendaciones no disponibles'); expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/); expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0); }); it('un Bundle vacío es una paciente sin riesgo confirmado', () => { const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) }); expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.'); expect(f.nativeElement.querySelector('table')).toBeNull(); }); it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => { const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data)); const baseline = structuredClone(data); const f = setup({ obtener }), root: HTMLElement = f.nativeElement; expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); // horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval expect(root.querySelectorAll('table.risk thead th')).toHaveLength(3); expect([...root.querySelectorAll('table.risk thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); expect(root.querySelectorAll('table.risk tbody th[scope="row"]')).toHaveLength(3); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)'); // the record names the model, its index date and outcome, not its version nor the batch's state expect(root.textContent).not.toMatch(/Final \(final\)|2\.1\.0/); for (const value of ['modelo-cacu', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) { expect(root.textContent).toContain(value); } // The record no longer shows the cohort's internals (its definition, version or model variables). expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/); // The record never says its data are test data: with real information it makes real predictions. expect(root.textContent).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica|simuladas/); expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); // The resource id (batch and patient) stays in the contract, never in a UI label. expect(root.textContent).not.toMatch(/lote_id|12-42/); expect(data).toEqual(baseline); }); it('mantiene tabla desplazable, foco de teclado y detalles técnicos accesibles', () => { const f = setup({ obtener: () => of(riesgoCacuEjemplo()) }), root: HTMLElement = f.nativeElement; const scroll = root.querySelector('.risk-scroll')!; expect(scroll.tabIndex).toBe(0); expect(scroll.getAttribute('role')).toBe('region'); expect(scroll.getAttribute('aria-label')).toContain('tabla desplazable'); expect(getComputedStyle(scroll).overflow).toBe('auto'); expect(getComputedStyle(scroll).maxWidth).toBe('100%'); expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem'); expect(getComputedStyle(root.querySelector('table.risk thead th')!).position).toBe('sticky'); }); it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => { const data = riesgoCacuEjemplo(); data.entry[0].resource.status = 'preliminary'; data.entry[0].resource.prediction = [ prediccion(0, '2026-06-01', '2026-12-01', [0, 0]), prediccion(1, '2026-06-01', '2034-06-01'), prediccion(0.00123, '2026-06-01', '2038-09-01'), ]; const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; expect([...root.querySelectorAll('table.risk tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']); expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']); expect(root.textContent).not.toContain('Preliminar (preliminary)'); }); it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => { const data = riesgoCacuEjemplo(); if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag; const f = setup({ obtener: () => of(data) }); expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); expect(f.nativeElement.textContent).not.toContain('modelo-cacu'); expect(f.nativeElement.querySelector('table')).toBeNull(); }); it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => { const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12; const f = setup({ obtener: () => of(data) }); expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0); }); it('representa carga y cancela la suscripción al desmontarse', () => { const source = new Subject(), f = setup({ obtener: () => source }); expect(f.nativeElement.textContent).toContain('Cargando riesgo individual'); expect(source.observed).toBe(true); f.destroy(); expect(source.observed).toBe(false); }); it('aísla estado y fixture entre instancias sin reutilizar información', () => { const source = new Subject(), f = setup({ obtener: () => source }); const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges(); data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges(); expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %'); f.destroy(); const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.componentRef.setInput('pacId', '43'); otra.detectChanges(); expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual'); expect(otra.nativeElement.querySelector('table')).toBeNull(); expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08); otra.destroy(); expect(source.observed).toBe(false); }); it.each(['observable', 'sincrono'])('oculta detalles internos del error %s', tipo => { const error = new Error('private pac_id=4821'); const f = setup({ obtener: () => { if (tipo === 'sincrono') throw error; return throwError(() => error); } }); expect(f.nativeElement.querySelector('[role="alert"]')!.textContent).toContain('No se pudo validar o cargar'); expect(f.nativeElement.textContent).not.toMatch(/private|4821|pac_id/); expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles'); }); }); describe('instanteUtc', () => { it('shows the day and the minute of a UTC instant, and leaves anything else as it came', () => { expect(instanteUtc('2026-11-21T23:17:45.120Z')).toBe('2026-11-21 23:17 UTC'); expect(instanteUtc('no es una fecha')).toBe('no es una fecha'); }); });