Files
WebApp/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts
T
Angel Capetillo Zavala 3b246b4f1f Identify follow-up patients by pac_id
Rows name their patient with pac_id (a decimal string) or the legacy
id_seudonimo. pac_id wins; an invalid pac_id is never replaced by the
legacy field, and a page that repeats a patient or mixes both fields is
not drawn or exported. The table, patient record, PDF and spreadsheet
follow the announced identifier column and label. CaCu requests risk
only with a pac_id.
2026-11-13 18:19:27 -06:00

297 lines
16 KiB
TypeScript

import { EnvironmentInjector, createEnvironmentInjector } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatSelectHarness } from '@angular/material/select/testing';
import { MatInputHarness } from '@angular/material/input/testing';
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
import { MatDialog } from '@angular/material/dialog';
import { firstValueFrom, of } from 'rxjs';
import fixtureData from '../fixtures/cacu_seguimiento.json';
import { SeguimientoPaciente } from '../cacu-seguimiento.models';
import { seguimientoResponse } from '../cacu-seguimiento.service';
import { IndicadoresTracking } from '../indicadores-tracking';
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
import { PacienteDetalleState } from './paciente-detalle.state';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { PacienteRegistroDialog } from './paciente-registro-dialog';
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
import { identidadDe } from '../paciente-identidad';
import { TipoRegistroTemporal } from './paciente-registro.models';
// The fixture is the legacy contract: every row has id_seudonimo.
const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[];
const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [
{ tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' },
{ tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' },
{ tipo: 'resultado', texto: 'Agregar resultado', opcion: 'VPH', resultado: 'VPH no detectado' },
];
describe('Altas de demostración desde la ficha de Seguimiento', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>;
let root: HTMLElement;
let http: HttpTestingController;
let dialog: MatDialog;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
http = TestBed.inject(HttpTestingController);
dialog = TestBed.inject(MatDialog);
montarTracking();
});
function montarTracking() {
fixture = TestBed.createComponent(IndicadoresTracking);
root = fixture.nativeElement;
fixture.componentRef.setInput('dominio', 'cacu');
fixture.componentRef.setInput('active', true);
fixture.detectChanges();
http.expectOne(r => r.url === '/cacu/seguimiento' && r.method === 'GET').flush(fixtureData);
http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/metadatos' && r.method === 'GET').flush({});
fixture.detectChanges();
}
afterEach(() => {
dialog.closeAll();
fixture.destroy();
http.verify();
});
function abrir(index = 0) {
root.querySelectorAll<HTMLButtonElement>('tbody button')[index].click();
fixture.detectChanges();
}
function volver() {
root.querySelector<HTMLButtonElement>('app-paciente-detalle > button')!.click();
fixture.detectChanges();
}
function boton(texto: string) {
return Array.from(root.querySelectorAll<HTMLButtonElement>('app-paciente-detalle button')).find(b => b.textContent?.trim() === texto)!;
}
async function abrirDialogo(texto: string) {
const origen = boton(texto);
origen.focus(); origen.click();
expect(dialog.openDialogs).toHaveLength(1);
const ref = dialog.openDialogs[0];
const abierto = firstValueFrom(ref.afterOpened());
fixture.detectChanges();
await abierto;
await fixture.whenStable();
fixture.detectChanges();
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-labelledby')).toBeTruthy();
expect(document.querySelector('[role="dialog"]')?.getAttribute('aria-describedby')).toBeNull();
expect(document.querySelector('[role="dialog"]')?.contains(document.activeElement)).toBe(true);
return { ref, origen };
}
async function confirmar() {
const ref = dialog.openDialogs[0];
const cerrado = firstValueFrom(ref.afterClosed());
document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.click();
await cerrado;
fixture.detectChanges(); await fixture.whenStable();
}
async function capturarFecha(dia: string, mes: string, anio: string) {
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
for (const [parte, valor] of [['dia', dia], ['mes', mes], ['anio', anio]]) {
const input = await loader.getHarness(MatInputHarness.with({ selector: `[data-fecha="${parte}"]` }));
await input.setValue(valor);
}
}
for (const accion of acciones) {
it(`abre, valida y confirma «${accion.texto}» sin HTTP y restaura el foco`, async () => {
const inicial = JSON.stringify(PACIENTES_DETALLE_SINTETICOS);
const resumen = JSON.stringify(fixture.componentInstance.data);
abrir();
const { origen } = await abrirDialogo(accion.texto);
const loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
const tipo = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="seleccion"]' }));
await tipo.clickOptions({ text: accion.opcion });
if (accion.resultado) {
const resultado = await loader.getHarness(MatSelectHarness.with({ selector: '[formControlName="resultado"]' }));
await resultado.clickOptions({ text: accion.resultado });
}
await capturarFecha('26', 'Octubre', '2026');
expect(document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(false);
await confirmar();
const registro = root.querySelector(`[data-registro-temporal="${accion.tipo}"]`)!;
expect(registro.textContent).toContain(accion.opcion);
expect(registro.textContent).toContain('2026-10-26');
expect(root.querySelectorAll(`[data-registro-temporal="${accion.tipo}"]`)).toHaveLength(1);
if (accion.tipo !== 'resultado') {
expect(registro.closest('.history-card table')).not.toBeNull();
let encabezado = registro.previousElementSibling;
while (encabezado && !encabezado.classList.contains('section-row')) encabezado = encabezado.previousElementSibling;
expect(encabezado?.textContent?.trim()).toBe(accion.tipo === 'condicion' ? 'Condiciones' : 'Procedimientos');
} else {
expect(registro.closest('.tests-card')).not.toBeNull();
}
expect(root.textContent).toContain('Cambios sin guardar');
expect(document.activeElement).toBe(origen);
expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial);
expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen);
const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0];
expect(almacenado.paciente).toBe(pacientes[0].id_seudonimo);
expect(almacenado.origen).toBe('sesion-demostracion');
expect(almacenado.fecha).toBe('2026-10-26');
http.expectNone(() => true);
});
it(`cancela «${accion.texto}» sin guardar el borrador`, async () => {
abrir();
const { ref, origen } = await abrirDialogo(accion.texto);
(ref.componentInstance as PacienteRegistroDialog).form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia');
await capturarFecha('26', 'Octubre', '2026');
const cerrado = firstValueFrom(ref.afterClosed());
document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog button[type="button"]')!.click();
expect(await cerrado).toBeUndefined();
fixture.detectChanges(); await fixture.whenStable();
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
expect(root.querySelector('[data-registro-temporal]')).toBeNull();
expect(document.activeElement).toBe(origen);
await abrirDialogo(accion.texto);
expect((dialog.openDialogs[0].componentInstance as PacienteRegistroDialog).form.controls.seleccion.value).toBe('');
expect(Array.from(document.querySelectorAll<HTMLInputElement>('app-fecha-compuesta input')).every(input => input.value === '')).toBe(true);
http.expectNone(() => true);
});
it(`bloquea fechas incompletas e imposibles en «${accion.texto}» y admite corregirlas`, async () => {
abrir();
const { ref } = await abrirDialogo(accion.texto);
const component = ref.componentInstance as PacienteRegistroDialog;
component.form.controls.seleccion.setValue(accion.tipo === 'resultado' ? 'vph' : accion.tipo === 'condicion' ? 'embarazo' : 'colposcopia');
if (accion.tipo === 'resultado') component.form.controls.resultado.setValue('negativo');
for (const partes of [['29', 'Febrero', ''], ['31', 'Abril', '2024'], ['30', 'Febrero', '2024'], ['29', 'Febrero', '2025']]) {
await capturarFecha(partes[0], partes[1], partes[2]);
expect(component.form.controls.fecha.value).toBe('');
expect(document.querySelector<HTMLButtonElement>('app-paciente-registro-dialog [type="submit"]')!.disabled).toBe(true);
component.agregar();
expect(dialog.openDialogs).toHaveLength(1);
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
}
await capturarFecha('29', '2', '2024');
expect(component.form.controls.fecha.value).toBe('2024-02-29');
await confirmar();
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()[0].fecha).toBe('2024-02-29');
http.expectNone(() => true);
});
it(`Escape cierra las sugerencias de «${accion.texto}» antes de permitir cancelar el diálogo`, async () => {
abrir();
const { ref, origen } = await abrirDialogo(accion.texto);
const mes = await TestbedHarnessEnvironment.documentRootLoader(fixture).getHarness(
MatAutocompleteHarness.with({ selector: '[data-fecha="mes"]' }));
await mes.enterText('ma');
expect(await mes.isOpen()).toBe(true);
const input = document.querySelector<HTMLInputElement>('[data-fecha="mes"]')!;
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
fixture.detectChanges(); await fixture.whenStable();
expect(await mes.isOpen()).toBe(false);
expect(dialog.openDialogs).toHaveLength(1);
expect(document.activeElement).toBe(input);
expect(input.value).toBe('ma');
const cerrado = firstValueFrom(ref.afterClosed());
// Con las sugerencias cerradas, Escape conserva la cancelación habitual del modal.
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, cancelable: true }));
expect(await cerrado).toBeUndefined();
fixture.detectChanges(); await fixture.whenStable();
expect(document.activeElement).toBe(origen);
expect(fixture.componentInstance.pacienteDetalle.registrosTemporales()).toEqual([]);
http.expectNone(() => true);
});
}
it('permite Escape y cierra el diálogo si se abandona la ficha sin confirmar', async () => {
abrir();
const { ref } = await abrirDialogo('Agregar condición');
const cerrado = firstValueFrom(ref.afterClosed());
document.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true }));
expect(await cerrado).toBeUndefined();
fixture.detectChanges();
const otro = await abrirDialogo('Agregar resultado');
const destruido = firstValueFrom(otro.ref.afterClosed());
volver();
expect(await destruido).toBeUndefined();
expect(TestBed.inject(PacienteRegistrosSesion).paraPaciente(pacientes[0].id_seudonimo)).toEqual([]);
expect(root.querySelector('app-paciente-detalle')).toBeNull();
http.expectNone(() => true);
});
it('agrega sin fixture, conserva las tres secciones al navegar y aísla pacientes', async () => {
abrir(2);
const riesgoNoDisponible = root.querySelector('app-paciente-riesgo-tabla')!.textContent;
expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
expect(riesgoNoDisponible).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.textContent).toContain('Información no disponible');
for (const tipo of acciones) {
const { ref } = await abrirDialogo(tipo.texto);
const form = (ref.componentInstance as PacienteRegistroDialog).form;
form.patchValue({ seleccion: tipo.tipo === 'condicion' ? 'lesion_cervical' : tipo.tipo === 'procedimiento' ? 'escision_cervical' : 'histologia', fecha: '2026-10-26' });
if (tipo.tipo === 'resultado') form.controls.resultado.setValue('nic1');
fixture.detectChanges();
await confirmar();
}
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
expect(root.querySelector('app-paciente-riesgo-tabla')!.textContent).toBe(riesgoNoDisponible);
expect(root.textContent).toContain('Recomendaciones no disponibles');
volver(); abrir(0);
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(0);
volver(); abrir(2);
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
volver();
fixture.destroy(); // La navegación puede desmontar Seguimiento; la aplicación sigue viva.
montarTracking(); abrir(2);
expect(root.querySelectorAll('[data-registro-temporal]')).toHaveLength(3);
http.expectNone(() => true);
});
it('no sustituye la última citología o VPH ni modifica el resumen, prioridades o datos recibidos', async () => {
const inicial = structuredClone(fixture.componentInstance.data);
abrir();
const resumen = structuredClone(fixture.componentInstance.pacienteDetalle.estado());
const { ref } = await abrirDialogo('Agregar resultado');
const form = (ref.componentInstance as PacienteRegistroDialog).form;
form.patchValue({ seleccion: 'vph', fecha: '2026-10-26' });
form.controls.resultado.setValue('positivo_16_18');
fixture.detectChanges(); await confirmar();
expect(fixture.componentInstance.pacienteDetalle.estado()).toEqual(resumen);
expect(fixture.componentInstance.data).toEqual(inicial);
expect(root.textContent).toContain('Último resultado de VPH');
expect(root.textContent).toContain('NEGATIVO');
expect(root.textContent).toContain('VPH 16/18 detectado');
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
expect(root.querySelector('app-paciente-riesgo-tabla table')).toBeNull();
http.expectNone(() => true);
});
});
describe('Vida de la selección y de la memoria de sesión', () => {
it('sobrevive a nuevas instancias de selección y rechaza altas de una ficha anterior', () => {
const parent = TestBed.inject(EnvironmentInjector);
const crear = () => createEnvironmentInjector([PacienteDetalleState], parent);
const primero = crear();
const segundo = crear();
try {
const a = primero.get(PacienteDetalleState);
const b = segundo.get(PacienteDetalleState);
a.abrir(pacientes[0], fixtureData.corte);
expect(a.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true);
a.cerrar();
expect(a.registrosTemporales()).toEqual([]);
primero.destroy();
b.abrir(pacientes[0], fixtureData.corte);
expect(b.registrosTemporales()).toHaveLength(1);
b.abrir(pacientes[1], fixtureData.corte);
expect(b.registrosTemporales()).toEqual([]);
expect(b.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false);
} finally {
if (!primero.destroyed) primero.destroy();
segundo.destroy();
}
});
});