165 lines
12 KiB
TypeScript
165 lines
12 KiB
TypeScript
import { Component, input } 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 { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
|
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 { figuraTiempos, modeloTiempos, PARES_TIEMPOS, parTiempos, TiemposIncompatibles } from './indicadores-tiempos-pareados';
|
|
|
|
@Component({ selector: 'app-plotly-chart', template: '' })
|
|
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
|
|
|
const par = PARES_TIEMPOS.find(p => p.dominio === 'cacu')!;
|
|
const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C3r', version: '1', figuras: ['fig_c3r_caja'], tipos_periodo: ['semestre', 'mes'] });
|
|
const diagnostico = item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico');
|
|
const reporte = item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado');
|
|
const row = (periodo: string, n: number | null, q1: number | null, mediana: number | null, q3: number | null, suprimido = 0) =>
|
|
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
|
|
function datos(id: string, filas: Record<string, unknown>[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos {
|
|
return { id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' };
|
|
}
|
|
const lab = () => datos(reporte.id, [row('2025-S1', 120, 7, 12, 20), row('2025-S2', 98, 6, 10, 18)]);
|
|
const dx = () => datos(diagnostico.id, [row('2025-S1', 3, null, null, null, 1), row('2025-S2', 40, 30, 52, 90)]);
|
|
|
|
describe('Tiempos pareados: modelo y figura', () => {
|
|
it('una caja por indicador y periodo; suprimidos y nulos nunca se dibujan como cero', () => {
|
|
const m = modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre');
|
|
expect(m.periodos).toEqual(['2025-S1', '2025-S2']);
|
|
expect(m.cajas.diagnostico['2025-S1']).toEqual({ estado: 'Suprimido' });
|
|
expect(m.cajas.reporte['2025-S2']).toEqual({ estado: 'Publicado', n: 98, q1: 6, mediana: 10, q3: 18 });
|
|
const f = figuraTiempos(m, par, 'claro');
|
|
expect(f.layout['boxmode']).toBe('group');
|
|
expect(f.data.map(t => t['name'])).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
|
|
expect(f.data.map(t => t['type'])).toEqual(['box', 'box']);
|
|
expect(f.data[0]['marker']).not.toEqual(f.data[1]['marker']);
|
|
expect(f.data[0]['x']).toEqual(['2025-S1', '2025-S2']);
|
|
expect(f.data[1]['x']).toEqual(['2025-S2']);
|
|
expect(f.data[1]).toMatchObject({ q1: [30], median: [52], q3: [90], lowerfence: [30], upperfence: [90] });
|
|
expect(f.data[1]['customdata']).toEqual([['40', '30', '52', '90']]);
|
|
expect(f.data[1]['hovertemplate']).toContain('n = %{customdata[0]} citologías');
|
|
expect(f.data[1]['hovertemplate']).toContain('Mediana: %{customdata[2]} días');
|
|
expect(JSON.stringify(f.data)).not.toContain('null');
|
|
expect(figuraTiempos(m, par, 'oscuro').layout['paper_bgcolor']).toBe('#081839');
|
|
});
|
|
it('cuartiles incompletos o desordenados quedan no disponibles', () => {
|
|
const d = datos(diagnostico.id, [row('2025-S1', 4, 5, 3, 9), row('2025-S2', 0, 0, 0, 0)]);
|
|
const m = modeloTiempos(par, { reporte: lab(), diagnostico: d }, 'semestre');
|
|
expect(m.cajas.diagnostico['2025-S1'].estado).toBe('No disponible');
|
|
expect(m.cajas.diagnostico['2025-S2'].estado).toBe('No disponible');
|
|
});
|
|
it('rechaza datos de otro indicador, contrato, periodo o con dos totales por periodo', () => {
|
|
expect(() => modeloTiempos(par, { reporte: dx(), diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
|
expect(() => modeloTiempos(par, { reporte: { ...lab(), contrato: 'C1' }, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
|
expect(() => modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre', ['2025-S2'])).toThrow(TiemposIncompatibles);
|
|
const twice = datos(reporte.id, [row('2025-S1', 1, 1, 1, 1), row('2025-S1', 2, 2, 2, 2)]);
|
|
expect(() => modeloTiempos(par, { reporte: twice, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
|
});
|
|
it('el par de CaMa existe pero solo CaCu está conectado', () => {
|
|
expect(parTiempos('cacu', 'cacu_dias_toma_diagnostico')).toBe(par);
|
|
expect(parTiempos('cacu', 'cacu_eu_tiempo_reporte')).toBeUndefined();
|
|
expect(PARES_TIEMPOS.some(p => p.dominio === 'cama' && p.diagnostico === 'cama_dias_toma_diagnostico')).toBe(true);
|
|
expect(parTiempos('cama', 'cama_dias_toma_diagnostico')).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('Tiempos pareados: componente', () => {
|
|
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }, revision: 1 };
|
|
let f: ReturnType<typeof TestBed.createComponent<IndicadorTiemposPareados>>;
|
|
let http: HttpTestingController;
|
|
beforeEach(() => {
|
|
TestBed.configureTestingModule({ imports: [IndicadorTiemposPareados, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
|
TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
|
http = TestBed.inject(HttpTestingController);
|
|
f = TestBed.createComponent(IndicadorTiemposPareados);
|
|
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('par', par);
|
|
f.componentRef.setInput('indicador', diagnostico);
|
|
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
|
});
|
|
afterEach(() => { f.destroy(); http.verify(); });
|
|
function flush(a = lab(), b = dx()) {
|
|
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos');
|
|
const d = http.expectOne(req => req.url === '/cacu/indicadores/cacu_dias_toma_diagnostico/datos');
|
|
expect(r.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
|
expect(d.request.params.get('periodos')).toBe(r.request.params.get('periodos'));
|
|
r.flush(a); d.flush(b); f.detectChanges();
|
|
}
|
|
it('carga diferida; dos GET de los mismos periodos; una gráfica y tabla con supresión', () => {
|
|
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');
|
|
const charts = f.debugElement.queryAll(By.directive(ChartStub));
|
|
expect(charts).toHaveLength(1);
|
|
expect((charts[0].componentInstance as ChartStub).figure()).toBe(f.componentInstance.figure);
|
|
const text = f.nativeElement.querySelector('table').textContent as string;
|
|
expect(text).toContain('Suprimido'); expect(text).toContain('mediana 52');
|
|
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
|
expect(f.componentInstance.figure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
|
});
|
|
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
|
f.detectChanges();
|
|
flush(datos(reporte.id, [row('2025-S1', 2, null, null, null, 1)]), datos(diagnostico.id, []));
|
|
expect(f.componentInstance.status()).toBe('empty');
|
|
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
|
expect(f.nativeElement.textContent).toContain('No hay cajas publicadas');
|
|
});
|
|
it('con filtro incompatible u otro indicador no hay GET', () => {
|
|
f.componentRef.setInput('indicador', { ...diagnostico, tipos_periodo: ['mes'] }); f.detectChanges();
|
|
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
|
f.componentRef.setInput('indicador', { ...diagnostico, contrato: 'C1' }); f.detectChanges();
|
|
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
|
});
|
|
it('la pareja oculta del catálogo se pide por id; un 404 se anuncia como error, sin cajas', () => {
|
|
f.detectChanges();
|
|
http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos' && req.params.get('periodos') === '2025-S1,2025-S2').flush({}, { status: 404, statusText: 'Not Found' });
|
|
http.match(req => req.url.includes('cacu_dias_toma_diagnostico'));
|
|
f.detectChanges();
|
|
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
|
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
|
});
|
|
it('error HTTP se anuncia y el reintento vuelve a pedir', () => {
|
|
f.detectChanges();
|
|
http.expectOne(req => req.url.includes('cacu_eu_tiempo_reporte')).flush({}, { status: 500, statusText: 'Error' });
|
|
http.match(req => req.url.includes('cacu_dias_toma_diagnostico'));
|
|
f.detectChanges(); expect(f.componentInstance.status()).toBe('error');
|
|
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
|
});
|
|
it('«Cómo leer» muestra el como_leer de las dos figuras y la advertencia de poblaciones distintas', () => {
|
|
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('Metadatos publicados pendientes');
|
|
http.expectOne('/cacu/indicadores/cacu_eu_tiempo_reporte/metadatos').flush({ ficha: { nota: 'No va' },
|
|
figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: null, como_leer: ['Caja del laboratorio.'] }] });
|
|
f.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: 'Caja de diagnóstico.', como_leer: ['Lee el diagnóstico.'] }] });
|
|
f.detectChanges();
|
|
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
|
expect([...help.querySelectorAll('.reading-guide h3')].map(h => h.textContent)).toEqual(['Días de toma a resultado (laboratorio)', 'Días de toma a diagnóstico']);
|
|
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Caja del laboratorio.', 'Lee el diagnóstico.']);
|
|
expect(help.querySelector('.caveat')!.textContent).toContain('no es el tiempo del tramo intermedio');
|
|
expect(help.textContent).not.toContain('No va'); expect(help.textContent).not.toContain('pendientes');
|
|
});
|
|
it('la tarjeta de CaCu sustituye el diagnóstico por la vista pareada; las demás quedan igual', () => {
|
|
f.componentRef.setInput('visible', false); f.detectChanges();
|
|
const card = TestBed.createComponent(IndicadorCatalogCard);
|
|
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', diagnostico);
|
|
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
|
const view = card.debugElement.query(By.directive(IndicadorTiemposPareados));
|
|
expect(view).not.toBeNull();
|
|
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
|
for (const [domain, indicator] of [['cacu', reporte], ['cama', { ...diagnostico, id: 'cama_dias_toma_diagnostico' }]] as const) {
|
|
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', indicator); card.detectChanges();
|
|
expect(card.debugElement.queryAll(By.directive(IndicadorTiemposPareados))).toHaveLength(0);
|
|
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(1);
|
|
}
|
|
card.destroy(); http.expectNone(() => true);
|
|
});
|
|
});
|