Files
WebApp/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts
T
2026-11-13 15:44:01 -06:00

163 lines
12 KiB
TypeScript

// Covers the habitual access to Seguimiento of breast cancer: the list opens on the regular window and, when the server
// answers from the cohort, adopts the cohort and its revision for the next pages and the files; a cut-off or a changed
// revision is asked for without the old revision; and the filters, the cut-off, the page and the rows are kept while the
// record is opened and closed. Fixtures: indicadores-analisis.testing.ts (listaCohorte) and fixtures/cama_seguimiento.json.
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, listaCohorte, REVISION } from './indicadores-analisis.testing';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
const OTRA = 'a'.repeat(64);
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
describe('Seguimiento de CaMa: acceso habitual', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresSeguimientoTabla>>, 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 lista = () => http.expectOne(r => r.url === '/cama/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 abrir = () => { fixture.componentRef.setInput('active', true); 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))!;
const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim());
async function escribir(nombre: string, valor: string) {
const c = root().querySelector(`input[name="${nombre}"]`) as HTMLInputElement; c.value = valor; c.dispatchEvent(new Event('input')); await asentar();
}
async function elegir(etiqueta: string, valor: string) {
const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor)!.value; s.dispatchEvent(new Event('change')); await asentar();
}
// The list opens on the regular window of 3 months and the cohort answers with its revision.
async function abierta(extra: Parameters<typeof listaCohorte>[0] = {}) {
abrir(); lista().flush(listaCohorte({ meses: 3, n: 27, ...extra })); await asentar();
}
it.each([404, 503])('informa que la cohorte no está disponible ante %s y no cambia de fuente', async status => {
// Fails if an unavailable source is reported as an empty list or another source is queried.
abrir(); lista().flush({ error: 'x' }, { status, statusText: 'Unavailable' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte no está disponible');
http.expectNone(r => r.url === '/cama/seguimiento');
});
it('abre en la ventana habitual de 3 meses sin citar ninguna revisión, y adopta la cohorte que el servidor devuelve', async () => {
// Fails if the habitual access asks for another window, or needs a revision it cannot have yet, or shows an analysis banner.
http.expectNone(() => true);
abrir();
const r = lista();
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush(listaCohorte({ meses: 3, n: 27, size: 10 })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']);
expect(root().textContent).toContain('Ventana consultada: 2025-02-01 al 2026-10-20.');
// The next page quotes the cohort the first answer named, with the same window and cut-off.
boton('Siguiente')!.click(); fixture.detectChanges();
const p2 = lista();
expect(parametros(p2)).toEqual({ meses: '3', page: '2', page_size: '10', corte: CORTE, ...CONTEXTO });
p2.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2 })); await asentar();
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
});
it('«Toda la cohorte» pide la ventana 0 citando la cohorte', async () => {
// Fails if the whole cohort is asked for without the revision the server requires for it.
await abierta();
await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO });
r.flush(listaCohorte({ meses: 0, n: 43 })); await asentar();
expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.');
expect(root().querySelector('nav')?.textContent).toContain('43 registros');
});
it('un servidor sin cohorte responde la lista de siempre: sin «Toda la cohorte» y sin citar nada', async () => {
// Fails if a deployment without the cohort provider loses its follow-up list or is sent parameters it does not know.
abrir(); lista().flush(base()); await asentar();
expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
boton('Consultar')!.click(); fixture.detectChanges();
expect(parametros(lista())).not.toHaveProperty('revision');
});
it('si el usuario cambia el corte, la consulta no cita la revisión del corte anterior y adopta la nueva', async () => {
// Fails if a list at another cut-off is asked for with the revision of the previous one.
await abierta();
await escribir('corte', '2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ corte: '2026-09-01', meses: '3' });
expect(parametros(r)).not.toHaveProperty('revision');
r.flush(listaCohorte({ meses: 3, n: 27, corte: '2026-09-01', revision: OTRA })); await asentar();
boton('Consultar')!.click(); fixture.detectChanges();
expect(parametros(lista())).toMatchObject({ corte: '2026-09-01', revision: OTRA });
});
it('si la cohorte cambia bajo la lista (409), repite la misma consulta una vez sin la revisión vieja; un segundo 409 sí se dice', async () => {
// Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops.
await abierta({ size: 10 });
boton('Siguiente')!.click(); fixture.detectChanges();
lista().flush({ error: 'La cohorte cambió' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges();
const r = lista();
expect(parametros(r)).toMatchObject({ page: '2', meses: '3' });
expect(parametros(r)).not.toHaveProperty('revision');
r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, revision: OTRA })); await asentar();
expect(root().querySelector('[role=alert]')).toBeNull();
// A conflict that persists is reported, not retried forever.
boton('Consultar')!.click(); fixture.detectChanges();
lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges();
lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis');
expect(root().querySelector('table')).toBeNull();
});
it('una cohorte sin pacientes al corte lo dice; con filtros o con una ventana de meses, el texto es el de los filtros', async () => {
// Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow window as an empty cohort.
await abierta({ n: 0 });
expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.');
await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 0 })); await asentar();
expect(root().querySelector('tbody')?.textContent).toContain('Sin pacientes para el corte seleccionado.');
expect([...root().querySelectorAll('app-seguimiento-exportar button')].filter(b => b.textContent!.includes('Exportar')).every(b => (b as HTMLButtonElement).disabled)).toBe(true);
await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar();
expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.');
});
it('abrir la ficha y regresar conserva los filtros elegidos, el corte, la página y la lista', async () => {
// Fails if opening the record resets the form, the page or the rows the user was reading.
await abierta({ size: 10 });
await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges();
lista().flush(listaCohorte({ meses: 3, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar();
boton('Siguiente')!.click(); fixture.detectChanges();
const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: CORTE, ...CONTEXTO });
r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar();
const filasAntes = [...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim());
(root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar();
expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE}.`);
([...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar')) as HTMLButtonElement).click(); await asentar();
http.expectNone(() => true);
expect([...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim())).toEqual(filasAntes);
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
const edad = campo('Grupo de edad').querySelector('select') as HTMLSelectElement;
expect(edad.options[edad.selectedIndex].text.trim()).toBe('50 a 59 años');
expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(CORTE);
});
it('con una selección del análisis, «Quitar selección» regresa a la lista habitual: 3 meses, sin filtros ni revisión citada', async () => {
// Fails if leaving the selection keeps its filter, its window or the old revision.
await abierta();
fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 43, contexto: { ...CONTEXTO, revision: REVISION }, id: 1 });
fixture.detectChanges();
lista().flush(listaCohorte({ meses: 0, n: 43, filtros: { birads: 'BIRADS_5' } })); await asentar();
expect(root().querySelector('.seleccion')).not.toBeNull();
boton('Quitar selección')!.click(); fixture.detectChanges();
const r = lista(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE });
r.flush(listaCohorte({ meses: 3, n: 27 })); await asentar();
expect(root().querySelector('.seleccion')).toBeNull();
});
it('la biopsia se escribe con las etiquetas del catálogo y un valor desconocido queda como llegó', async () => {
// Fails if a source code is remapped to a diagnosis the catalog does not name, or the code is lost.
abrir();
const r = listaCohorte({ meses: 3, n: 4 }); const v = ['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'OTRO_VALOR']; r['items'].forEach((i: any, k: number) => { i['biopsia'] = v[k]; });
lista().flush(r); await asentar();
expect([...root().querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.replace(/\s+/g, ' ').trim().split(' Fecha')[0])).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'OTRO_VALOR']);
});
});