Files
WebApp/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts
T
Roberto Treviño Cervantes e6e6fb7210 preliminary release
2026-10-29 12:12:15 -06:00

226 lines
17 KiB
TypeScript

import { Component, input, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { GlobalApplied } from './indicadores-memory';
import { Indicador, IndicadorDatos } from './indicadores.models';
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
// valores_estrato as texts. Counts per cytology: NORMAL, LIEBG, LIEAG, CIS, CARCINOMA,
// SIN_BIOPSIA (no biopsy yet), SIN_DATO (biopsy without grade), CIN2.
const CATEGORIAS = [...GRADOS, 'SIN_BIOPSIA', 'SIN_DATO', 'CIN2'];
const CONTEOS: Record<string, number[]> = {
'ASC-H': [16, 11, 9, 1, 1, 20, 2, 0], LIEAG: [6, 10, 31, 8, 2, 22, 2, 1], CIS: [0, 1, 4, 4, 3, 11, 2, 0],
};
function respuesta(periodos = ['2026-S2'], conteos = CONTEOS): IndicadorDatos {
const filas = periodos.flatMap(periodo => Object.entries(conteos).flatMap(([estrato, ns]) =>
CATEGORIAS.map((categoria, orden) => ({ periodo, grupo: 'TOTAL', estrato, categoria, n: ns[orden], orden, suprimido: 0 }))));
const color = ['#9DBFE3', '#E8C28E', '#D98E4A', '#B55A1F', '#7A2E0E'];
const estratos = Object.keys(conteos);
return {
id: 'cacu_confirmacion_citologia', contrato: 'C2', tipo_periodo: 'semestre', periodos, filas, version: '1',
estrato: 'citologia_alto_grado', valores_estrato: estratos,
etiquetas_estrato: Object.fromEntries(estratos.map(e => [e, e === 'CIS' ? 'Carcinoma in situ' : e])),
totales_estrato: periodos.flatMap(periodo => estratos.map(estrato => ({ periodo, grupo: 'TOTAL', estrato,
n: conteos[estrato].reduce((a, b) => a + b, 0), suprimido: 0 }))),
categorias: {
...Object.fromEntries(GRADOS.map((id, i) => [id, { etiqueta: id === 'CIS' ? 'Carcinoma in situ' : id, color: color[i],
grupo: i < 2 ? 'NO_ANORMAL' : 'ANORMAL', gravedad: i + 1 }])),
SIN_BIOPSIA: { etiqueta: 'Sin biopsia aún', color: '#C9CDD2', grupo: null, gravedad: null },
SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: 'SIN_DATO', gravedad: null },
CIN2: { etiqueta: 'CIN2', color: null, grupo: 'NO_ANORMAL', gravedad: null },
},
grupos_de_categoria: { NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Sin dato' },
};
}
describe('Confirmación histopatológica: modelo', () => {
it('denominador: mujeres con biopsia y grado; SIN_BIOPSIA y SIN_DATO van aparte; CIN2 cuenta en su grupo', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2');
expect(m.filas.map(f => f.id)).toEqual(['CIS', 'LIEAG', 'ASC-H']);
expect(m.filas.map(f => f.etiqueta)).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
expect(m.filas.map(f => f.den)).toEqual([12, 58, 38]);
expect(m.aparte).toEqual([{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' }, { id: 'SIN_DATO', etiqueta: 'Sin dato' }]);
expect(m.filas.map(f => [f.aparte['SIN_BIOPSIA'].n, f.aparte['SIN_DATO'].n])).toEqual([[11, 2], [22, 2], [20, 2]]);
expect(m.grados.map(g => g.id)).toEqual([...GRADOS, 'CIN2']);
expect(m.grados.find(g => g.id === 'CIN2')).toMatchObject({ grupo: 'NO_ANORMAL', color: '#8A9199' });
expect(m.grupos.find(g => g.id === 'NO_ANORMAL')!.grados).toEqual(['NORMAL', 'LIEBG', 'CIN2']);
expect(m.conBiopsia).toBe(108); expect(m.base).toBe('ANORMAL');
});
it('estratos ausentes de valores_estrato dicen «Sin mujeres con biopsia»; total suprimido suprime la fila', () => {
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
const m = modeloConfirmacion(d, '2026-S2');
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
expect(tasas(m, seleccionBase(m)).map(estadoTasa)).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
const s = modeloConfirmacion(d, '2026-S2');
expect([s.filas[1].den, s.filas[1].estado]).toEqual([null, 'Suprimido']);
expect(s.conBiopsia).toBeNull();
expect((figuraTasas(s, seleccionBase(s), 'claro').layout['annotations'] as { text: string }[])[1].text).toBe('Suprimido');
});
it('Wilson al 95 % con la fórmula del kit y extremos 0 y n', () => {
const [bajo, alto] = wilson(11, 12);
expect(bajo).toBeCloseTo(64.61, 1); expect(alto).toBeCloseTo(98.51, 1);
expect(wilson(0, 10)[0]).toBe(0); expect(wilson(10, 10)[1]).toBe(100);
});
it('vista base LIEAG o más; grupo, grado, segundo clic al grupo y centro a la base', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2');
const base = seleccionBase(m);
expect(tasas(m, base).map(t => [t.k, t.fila.den])).toEqual([[11, 12], [41, 58], [11, 38]]);
expect(lectura(m, base)).toBe('Verdaderos positivos (valor predictivo positivo)');
const menor = clicConfirmacion(m, base, 'grupos', m.grupos.findIndex(g => g.id === 'NO_ANORMAL'));
expect(menor).toEqual({ grupo: 'NO_ANORMAL' }); expect(lectura(m, menor)).toBe('Sin confirmación de alto grado');
const normal = clicConfirmacion(m, menor, 'categorias', 0);
expect(normal).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
expect(lectura(m, normal)).toBe('Falsos positivos: la biopsia no confirmó lesión');
expect(tasas(m, normal).map(t => t.k)).toEqual([0, 6, 16]);
expect(clicConfirmacion(m, normal, 'categorias', 0)).toEqual({ grupo: 'NO_ANORMAL' });
const cis = clicConfirmacion(m, normal, 'categorias', 3);
expect(lectura(m, cis)).toBe('Proporción con biopsia Carcinoma in situ');
expect(clicConfirmacion(m, cis, 'centro', 0)).toEqual(base);
});
it('figura de tasas: una traza siempre, etiquetas «xx.x %» y «k/n», eje acotado a múltiplos de 5', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
const f = figuraTasas(m, base, 'claro');
expect(f.data).toHaveLength(1); expect(f.data[0]['type']).toBe('scatter');
expect(f.data[0]['y']).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray).toEqual(['ASC-H', 'LIEAG', 'Carcinoma in situ']);
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text))
.toEqual(['<b>91.7 %</b><br>11/12', '<b>70.7 %</b><br>41/58', '<b>28.9 %</b><br>11/38']);
const range = (f.layout['xaxis'] as { range: number[] }).range;
expect(range).toEqual(rangoTasas(tasas(m, base)));
expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); expect(range[0]).toBeGreaterThanOrEqual(0); expect(range[1]).toBeLessThanOrEqual(100);
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Verdaderos positivos (valor predictivo positivo)');
const otra = figuraTasas(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'oscuro');
expect(otra.data).toHaveLength(1); expect(otra.layout['paper_bgcolor']).toBe('#081839');
});
it('fila suprimida o nula dice Suprimido o No disponible, nunca 0, y la dona no suma un total parcial', () => {
const d = respuesta();
Object.assign(d.filas.find(f => f['estrato'] === 'CIS' && f['categoria'] === 'LIEAG')!, { n: null, suprimido: 1 });
d.filas = d.filas.filter(f => !(f['estrato'] === 'ASC-H' && f['categoria'] === 'NORMAL'));
const m = modeloConfirmacion(d, '2026-S2'), base = seleccionBase(m);
expect(m.filas.map(f => [f.den, f.estado])).toEqual([[null, 'Suprimido'], [58, 'Publicado'], [null, 'No disponible']]);
const f = figuraTasas(m, base, 'claro');
expect(f.data[0]['x']).toEqual([null, 100 * 41 / 58, null]);
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(['Suprimido', '<b>70.7 %</b><br>41/58', 'No disponible']);
expect(JSON.stringify(f.layout['annotations'])).not.toContain('0/');
expect(m.conBiopsia).toBeNull(); expect(donaConfirmacion(m, base, 'claro').data).toHaveLength(0);
});
it('dona de dos anillos; la selección atenúa sin cambiar valores y el centro dice «k de N con biopsia»', () => {
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
const d = donaConfirmacion(m, base, 'claro');
expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
expect(d.data[1]['values']).toEqual([45, 63]);
expect(d.data[2]['values']).toEqual([22, 22, 44, 13, 6, 1]);
expect(d.data[0]['text']).toEqual(['<b>63</b><br>de 108 con biopsia']);
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/);
});
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
expect(() => periodosConfirmacion({ ...respuesta(), estrato: 'estatus_seguimiento' }, 'semestre')).toThrow(ConfirmacionIncompatible);
expect(() => periodosConfirmacion(respuesta(), 'semestre', ['2026-S1'])).toThrow(ConfirmacionIncompatible);
const dup = respuesta(); dup.filas.push({ ...dup.filas[0] });
expect(() => modeloConfirmacion(dup, '2026-S2')).toThrow(ConfirmacionIncompatible);
});
});
describe('Confirmación histopatológica: componente', () => {
const indicador: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1',
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] };
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2026-S1', '2026-S2'] }, revision: 1 };
let f: ReturnType<typeof TestBed.createComponent<IndicadorConfirmacionCitologia>>;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadorConfirmacionCitologia, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorConfirmacionCitologia, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
f = TestBed.createComponent(IndicadorConfirmacionCitologia);
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
});
afterEach(() => { f.destroy(); http.verify(); });
function flush(body: unknown = respuesta(['2026-S1', '2026-S2'])) {
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_confirmacion_citologia/datos');
expect(r.request.params.get('estrato')).toBe('citologia_alto_grado');
expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2');
r.flush(body as Record<string, unknown>); f.detectChanges();
}
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible, periodos y tabla', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.status()).toBe('ready');
expect(f.componentInstance.model!.periodo).toBe('2026-S2');
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
const normal = [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
normal.click(); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
expect(normal.getAttribute('aria-pressed')).toBe('true');
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos');
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']);
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].slice(-3).map(td => td.textContent))).toEqual([['12', '11', '2'], ['58', '22', '2'], ['38', '20', '2']]);
f.componentInstance.changePeriod(-1); f.detectChanges();
expect(f.componentInstance.model!.periodo).toBe('2026-S1'); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
});
it('error se anuncia y el reintento recupera; respuesta incompatible no dibuja', () => {
f.detectChanges();
http.expectOne(req => req.url.endsWith('/datos')).flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
f.componentInstance.retry(); flush({ ...respuesta(['2026-S1', '2026-S2']), estrato: 'otro' });
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
});
it('filtro general incompatible no pide datos', () => {
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
});
it('«Cómo leer» muestra solo descripción y como_leer de fig_c2_donas y fig_c2_barras', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
expect(requested).toHaveBeenCalledTimes(1);
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('pendientes');
f.componentRef.setInput('metadata', { descripcion: 'No va', ficha: { nota: 'Tampoco' }, figuras_detalle: [
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] },
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] },
{ figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges();
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.', 'Lee las tasas.']);
for (const absent of ['No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent);
});
it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const card = TestBed.createComponent(IndicadorCatalogCard);
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(1);
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['cama', 'cacu_confirmacion_citologia']] as const) {
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(0);
}
card.destroy(); http.expectNone(() => true);
});
});