237 lines
17 KiB
TypeScript
237 lines
17 KiB
TypeScript
// Covers CaMa's follow-up table: when it asks, what it sends, how it draws the answer and each state (loading,
|
|
// empty, pending, error, retry). The answers are fixtures (fixtures/cama_seguimiento.json and variations of it):
|
|
// synthetic records, used by tests only; the view never reads them in normal use.
|
|
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 { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
|
|
|
|
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
|
|
// The server's page `n` of `tam` items, with the filters applied by it (here, none).
|
|
function pagina(n: number, tam: number, extra: Record<string, any> = {}) {
|
|
const d = base(), todos = d['items'] as unknown[];
|
|
d['items'] = todos.slice((n - 1) * tam, n * tam);
|
|
d['paginacion'] = { page: n, page_size: tam, total_items: todos.length, total_pages: Math.max(1, Math.ceil(todos.length / tam)) };
|
|
return { ...d, ...extra };
|
|
}
|
|
|
|
describe('Seguimiento de CaMa (tabla)', () => {
|
|
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('active', false); fixture.detectChanges();
|
|
});
|
|
afterEach(() => { fixture.destroy(); http.verify(); });
|
|
const root = () => fixture.nativeElement as HTMLElement;
|
|
const solicitud = () => 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)]));
|
|
const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); };
|
|
// ngModel writes its values in a microtask: wait for it before reading or editing the form.
|
|
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
|
|
async function cargado(respuesta: Record<string, any> = pagina(1, 50)) { abrir(); solicitud().flush(respuesta); await asentar(); }
|
|
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
|
|
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
|
|
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();
|
|
}
|
|
// Each cell reads as its text nodes (value, then each detail) joined by one space.
|
|
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(' ')));
|
|
|
|
it('no pide nada hasta que la pestaña está activa, y entonces pide la ventana de 3 meses, página 1 de 50', async () => {
|
|
http.expectNone(() => true);
|
|
abrir();
|
|
const r = solicitud();
|
|
expect(r.request.method).toBe('GET');
|
|
expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' });
|
|
r.flush(pagina(1, 50));
|
|
});
|
|
it('mientras carga lo dice; ya cargado dibuja la tabla con las columnas que declara la respuesta', async () => {
|
|
abrir(); fixture.detectChanges();
|
|
expect(root().querySelector('[role=status]')?.textContent).toContain('Cargando seguimiento');
|
|
expect(boton('Consultar').disabled).toBe(true);
|
|
solicitud().flush(pagina(1, 50)); fixture.detectChanges();
|
|
expect(root().querySelector('[role=status]')).toBeNull();
|
|
expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual([
|
|
'Identificador seudónimo', 'Grupo de edad', 'Estatus de seguimiento', 'Última mastografía', 'Resultado histopatológico', 'Días de mastografía a diagnóstico', 'Prioridad']);
|
|
expect(root().querySelector('caption')?.textContent).toBe('Resultados disponibles por paciente');
|
|
expect(filas()).toHaveLength(27);
|
|
expect(root().textContent).toContain('Ventana consultada: 2026-07-21 al 2026-10-20.');
|
|
});
|
|
it('accepts the simulated contract without a visible demonstration notice', async () => {
|
|
await cargado();
|
|
expect(fixture.componentInstance.data()?.simulado).toBe(true);
|
|
expect(root().querySelector('.simulation')).toBeNull();
|
|
expect(root().textContent).not.toContain('Datos de demostración');
|
|
});
|
|
it('los detalles salen bajo su valor con su etiqueta y un valor nulo se lee «No disponible», sin línea de detalle', async () => {
|
|
await cargado();
|
|
const todas = filas();
|
|
const sinBiopsia = todas.find(f => f[0] === 'M-0081')!;
|
|
expect(sinBiopsia[3]).toBe('BI-RADS 4A Fecha: 2026-07-25');
|
|
expect(sinBiopsia[4]).toBe('No disponible'); expect(sinBiopsia[5]).toBe('No disponible');
|
|
const conBiopsia = todas.find(f => f[4].startsWith('Carcinoma invasor'))!;
|
|
expect(conBiopsia[4]).toMatch(/^Carcinoma invasor Fecha de biopsia: 20\d\d-\d\d-\d\d$/);
|
|
expect(conBiopsia[5]).toMatch(/^[0-9]+$/);
|
|
});
|
|
it('el formulario muestra el corte que devolvió el servidor, la ventana, los cuatro filtros anunciados y el tamaño', async () => {
|
|
await cargado();
|
|
expect((campo('Fecha de corte').querySelector('input') as HTMLInputElement).value).toBe('2026-10-20');
|
|
expect((campo('Ventana de meses').querySelector('select') as HTMLSelectElement).selectedOptions[0].text.trim()).toBe('3 meses');
|
|
expect([...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
|
|
const etiquetas = [...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim());
|
|
expect(etiquetas).toEqual(['Fecha de corte', 'Ventana de meses', 'Estatus de seguimiento', 'Categoría BI-RADS', 'Grupo de edad', 'Prioridad', 'Registros por página']);
|
|
expect([...campo('Estatus de seguimiento').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
|
|
['Todos', 'Pendiente de biopsia', 'Biopsia sin resultado', 'Cáncer confirmado', 'Benigno, regresa a tamizaje', 'Información insuficiente']);
|
|
expect([...campo('Prioridad').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Alta', 'Media', 'Baja']);
|
|
expect((campo('Registros por página').querySelector('input') as HTMLInputElement).value).toBe('50');
|
|
});
|
|
it('Consultar envía la ventana, el corte y solo los filtros elegidos, desde la página 1', async () => {
|
|
await cargado();
|
|
await elegir('Ventana de meses', '6 meses'); await elegir('Estatus de seguimiento', 'CANCER_CONFIRMADO'); await elegir('Categoría BI-RADS', 'BIRADS_5');
|
|
boton('Consultar').click(); fixture.detectChanges();
|
|
const r = solicitud();
|
|
expect(parametros(r)).toEqual({ meses: '6', page: '1', page_size: '50', corte: '2026-10-20', estatus: 'CANCER_CONFIRMADO', birads: 'BIRADS_5' });
|
|
r.flush(pagina(1, 50, { ventana: { meses: 6, desde: '2026-04-21', hasta: '2026-10-20' }, filtros: { estatus: 'CANCER_CONFIRMADO', birads: 'BIRADS_5', grupo_edad: null, prioridad: null } }));
|
|
fixture.detectChanges();
|
|
expect(root().textContent).toContain('Ventana consultada: 2026-04-21 al 2026-10-20.');
|
|
});
|
|
it('«Todos» quita el filtro: no se envía', async () => {
|
|
await cargado();
|
|
await elegir('Prioridad', 'ALTA'); boton('Consultar').click(); fixture.detectChanges();
|
|
solicitud().flush(pagina(1, 50, { filtros: { estatus: null, birads: null, grupo_edad: null, prioridad: 'ALTA' } })); await asentar();
|
|
await elegir('Prioridad', 'Todos'); boton('Consultar').click(); fixture.detectChanges();
|
|
expect(parametros(solicitud())).not.toHaveProperty('prioridad');
|
|
});
|
|
|
|
describe('paginación', () => {
|
|
it('Anterior y Siguiente piden la página vecina con los mismos filtros; en los extremos se desactivan', async () => {
|
|
await cargado(pagina(1, 10, { filtros: { estatus: null, birads: null, grupo_edad: '50-59', prioridad: null } }));
|
|
expect(root().querySelector('nav')?.textContent).toContain('Página 1 de 3, 27 registros');
|
|
expect(boton('Anterior').disabled).toBe(true); expect(boton('Siguiente').disabled).toBe(false);
|
|
boton('Siguiente').click(); fixture.detectChanges();
|
|
const r = solicitud();
|
|
expect(parametros(r)).toEqual({ meses: '3', page: '2', page_size: '10', corte: '2026-10-20', grupo_edad: '50-59' });
|
|
r.flush(pagina(2, 10)); fixture.detectChanges();
|
|
expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3');
|
|
expect(boton('Anterior').disabled).toBe(false);
|
|
boton('Anterior').click(); fixture.detectChanges();
|
|
expect(solicitud().request.params.get('page')).toBe('1');
|
|
});
|
|
it('la última página desactiva Siguiente', async () => {
|
|
await cargado(pagina(3, 10));
|
|
expect(boton('Siguiente').disabled).toBe(true); expect(boton('Anterior').disabled).toBe(false);
|
|
expect(filas()).toHaveLength(7);
|
|
});
|
|
it('cambiar los filtros vuelve a la página 1', async () => {
|
|
await cargado(pagina(2, 10));
|
|
await elegir('Prioridad', 'MEDIA'); boton('Consultar').click(); fixture.detectChanges();
|
|
expect(solicitud().request.params.get('page')).toBe('1');
|
|
});
|
|
it('los botones de página no se pueden pulsar mientras se consulta', async () => {
|
|
await cargado(pagina(1, 10));
|
|
boton('Siguiente').click(); fixture.detectChanges();
|
|
expect(boton('Siguiente').disabled).toBe(true); expect(boton('Anterior').disabled).toBe(true);
|
|
solicitud().flush(pagina(2, 10));
|
|
});
|
|
it('una consulta nueva cancela la anterior y su respuesta tardía no se dibuja', async () => {
|
|
// Fails if a slow answer replaces the table of a later query.
|
|
await cargado(pagina(1, 10));
|
|
boton('Siguiente').click(); fixture.detectChanges();
|
|
const lenta = solicitud();
|
|
await elegir('Prioridad', 'ALTA'); (root().querySelector('form') as HTMLFormElement).dispatchEvent(new Event('submit')); fixture.detectChanges();
|
|
expect(lenta.cancelled).toBe(true);
|
|
const rapida = solicitud();
|
|
rapida.flush(pagina(1, 10, { filtros: { estatus: null, birads: null, grupo_edad: null, prioridad: 'ALTA' } })); fixture.detectChanges();
|
|
expect(() => lenta.flush(pagina(2, 10))).toThrow();
|
|
expect(root().querySelector('nav')?.textContent).toContain('Página 1 de 3');
|
|
});
|
|
});
|
|
|
|
describe('estados', () => {
|
|
it('sin registros para los filtros lo dice y conserva el formulario', async () => {
|
|
const vacia = pagina(1, 50); vacia['items'] = []; vacia['paginacion'] = { page: 1, page_size: 50, total_items: 0, total_pages: 1 };
|
|
await cargado(vacia);
|
|
expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.');
|
|
expect(root().querySelector('tbody td')?.getAttribute('colspan')).toBe('7');
|
|
expect(boton('Consultar')).toBeDefined();
|
|
});
|
|
it('404 en la primera página: la cohorte no está disponible, sin tabla, y el reintento vuelve a pedir', async () => {
|
|
abrir(); solicitud().flush('', { status: 404, statusText: 'Not Found' }); fixture.detectChanges();
|
|
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte no está disponible');
|
|
expect(root().querySelector('table')).toBeNull(); expect(root().querySelector('.simulation')).toBeNull();
|
|
boton('Reintentar seguimiento').click(); fixture.detectChanges();
|
|
solicitud().flush(pagina(1, 50)); fixture.detectChanges();
|
|
expect(root().querySelector('table')).not.toBeNull();
|
|
expect(root().textContent).not.toContain('Funcionalidad pendiente de publicación');
|
|
});
|
|
it('404 en una página posterior es un error, no «pendiente»', async () => {
|
|
await cargado(pagina(1, 10));
|
|
boton('Siguiente').click(); fixture.detectChanges();
|
|
solicitud().flush('', { status: 404, statusText: 'Not Found' }); fixture.detectChanges();
|
|
expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte no está disponible');
|
|
expect(root().textContent).not.toContain('Funcionalidad pendiente');
|
|
});
|
|
it('400 pide revisar la fecha, la ventana y los filtros', async () => {
|
|
await cargado();
|
|
boton('Consultar').click(); fixture.detectChanges();
|
|
solicitud().flush({ error: 'parámetros inválidos' }, { status: 400, statusText: 'Bad Request' }); fixture.detectChanges();
|
|
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha, la ventana y los filtros seleccionados');
|
|
});
|
|
it('un fallo del servidor muestra un mensaje fijo, nunca el cuerpo, y el reintento repite la misma consulta', async () => {
|
|
// Fails if the server's text reaches the page, or if the retry sends another query.
|
|
await cargado(); await elegir('Prioridad', 'BAJA'); boton('Consultar').click(); fixture.detectChanges();
|
|
solicitud().flush('detalle interno', { status: 500, statusText: 'Error' }); fixture.detectChanges();
|
|
expect(root().querySelector('[role=alert]')?.textContent).toBe('No se pudo consultar el seguimiento. Intenta nuevamente.');
|
|
expect(root().textContent).not.toContain('detalle interno');
|
|
boton('Reintentar seguimiento').click(); fixture.detectChanges();
|
|
expect(parametros(solicitud())).toMatchObject({ prioridad: 'BAJA', page: '1' });
|
|
});
|
|
it('una respuesta que no es de demostración o está fuera de contrato no se dibuja', async () => {
|
|
abrir(); const fuera = pagina(1, 50, { simulado: false });
|
|
solicitud().flush(fuera); fixture.detectChanges();
|
|
expect(root().querySelector('[role=alert]')?.textContent).toBe('La respuesta del servicio no tiene el formato esperado.');
|
|
expect(root().querySelector('table')).toBeNull(); expect(root().textContent).not.toContain('M-0081');
|
|
});
|
|
it('un tamaño de página inválido no sale del navegador', async () => {
|
|
await cargado();
|
|
const tam = campo('Registros por página').querySelector('input') as HTMLInputElement;
|
|
tam.value = '500'; tam.dispatchEvent(new Event('input')); fixture.detectChanges();
|
|
boton('Consultar').click(); fixture.detectChanges();
|
|
http.expectNone(() => true);
|
|
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha');
|
|
});
|
|
});
|
|
|
|
describe('listo para otra fuente', () => {
|
|
it('dibuja otras columnas, otros filtros y otros detalles sin cambios en el código', async () => {
|
|
// The view knows no column or filter by name: only the identifier is required.
|
|
abrir();
|
|
solicitud().flush({
|
|
simulado: true, corte: '2026-11-01', ventana: { meses: 1, desde: '2026-10-02', hasta: '2026-11-01' },
|
|
filtros: { zona: null }, filtros_disponibles: [{ clave: 'zona', etiqueta: 'Zona', opciones: [{ codigo: 'N', etiqueta: 'Norte' }, { codigo: 'S', etiqueta: 'Sur' }] }],
|
|
columnas: [{ clave: 'id_seudonimo', etiqueta: 'Folio' }, { clave: 'evento', etiqueta: 'Último evento', detalles: [{ clave: 'evento_fecha', etiqueta: 'Ocurrió' }] }],
|
|
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
|
|
items: [{ id_seudonimo: 'X-1', evento: 'Alta', evento_fecha: '2026-10-05' }, { id_seudonimo: 'X-2', evento: null, evento_fecha: null }],
|
|
});
|
|
await asentar();
|
|
expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual(['Folio', 'Último evento']);
|
|
expect(filas()).toEqual([['X-1', 'Alta Ocurrió: 2026-10-05'], ['X-2', 'No disponible']]);
|
|
expect([...campo('Zona').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Norte', 'Sur']);
|
|
await elegir('Zona', 'S'); boton('Consultar').click(); fixture.detectChanges();
|
|
expect(parametros(solicitud())).toEqual({ meses: '1', page: '1', page_size: '50', corte: '2026-11-01', zona: 'S' });
|
|
});
|
|
it('si la respuesta deja de anunciar un filtro, el formulario lo retira y no lo envía', async () => {
|
|
await cargado(); await elegir('Prioridad', 'ALTA');
|
|
boton('Consultar').click(); fixture.detectChanges();
|
|
const sin = pagina(1, 50); sin['filtros_disponibles'] = sin['filtros_disponibles'].filter((f: any) => f.clave !== 'prioridad'); delete sin['filtros']['prioridad'];
|
|
solicitud().flush(sin); fixture.detectChanges();
|
|
expect(campo('Prioridad')).toBeUndefined();
|
|
boton('Consultar').click(); fixture.detectChanges();
|
|
expect(parametros(solicitud())).not.toHaveProperty('prioridad');
|
|
});
|
|
});
|
|
});
|