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

519 lines
36 KiB
TypeScript

import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { vi } from 'vitest';
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
import { Indicador, PlotlyFigure } from './indicadores.models';
import { presentationFigure } from './indicadores.presentation';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
import { donutFixture } from './indicadores-donut-drilldown.testing';
import { donutHierarchy, donutLegend } from './indicadores-donut-drilldown';
describe('IndicadorFigureCard', () => {
const selected: Indicador = { id: 'i1', titulo: 'Indicador de prueba', contrato: 'C1', figuras: ['fig_c1_puntos'], tipos_periodo: ['semestre'] };
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigureCard>>;
let react: ReturnType<typeof vi.fn>;
let purge: ReturnType<typeof vi.fn>;
let disconnect: ReturnType<typeof vi.fn>;
let observe: ReturnType<typeof vi.fn>;
beforeEach(() => {
react = vi.fn().mockResolvedValue(undefined);
purge = vi.fn();
disconnect = vi.fn();
observe = vi.fn();
vi.stubGlobal('ResizeObserver', class { observe = observe; disconnect = disconnect; });
TestBed.configureTestingModule({
imports: [IndicadorFigureCard],
providers: [{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({
react, purge, Plots: { resize: vi.fn().mockResolvedValue(undefined) },
addFrames: vi.fn().mockResolvedValue(undefined), deleteFrames: vi.fn().mockResolvedValue(undefined),
}) }],
});
fixture = TestBed.createComponent(IndicadorFigureCard);
fixture.componentRef.setInput('selected', selected);
fixture.componentRef.setInput('figuraId', 'fig_c1_puntos');
fixture.componentRef.setInput('dominio', 'tea');
fixture.componentRef.setInput('tema', 'claro');
fixture.componentRef.setInput('state', { status: 'idle' });
});
afterEach(() => { fixture.destroy(); vi.unstubAllGlobals(); });
function state(value: FigureState) { fixture.componentRef.setInput('state', value); fixture.detectChanges(); }
async function settle() {
await fixture.whenStable();
for (let i = 0; i < 12; i++) await Promise.resolve();
fixture.detectChanges();
}
function ready(original: PlotlyFigure) {
const copy = presentationFigure(original, { indicador: selected.id, figura: 'fig_c1_puntos', tema: 'claro' });
state({ status: 'ready', figure: original, presentationFigure: copy });
return copy;
}
it.each(['bar', 'box', 'scatter'])('%s conserva el dimensionamiento intrínseco de Plotly', async type => {
const automatic: PlotlyFigure = { data: [{ type, x: ['A'], y: [2] }], layout: { autosize: true } };
ready(automatic); await settle();
const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
expect(chart.style.getPropertyValue('--plot-height')).toBe('');
expect(automatic.layout['height']).toBeUndefined();
const tall = { ...automatic, layout: { ...automatic.layout, height: 830 } };
ready(tall); await settle();
expect(chart.style.getPropertyValue('--plot-height')).toBe('');
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart);
expect(tall.layout.height).toBe(830);
});
it('la leyenda de exploración precede al lienzo y conserva su host y altura al expandir', async () => {
const { figure, data } = donutFixture();
state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data)! }); await settle();
const plot = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
const slot = plot.closest('.plot-slot')!;
const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement;
expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
fixture.componentInstance.expandParent('G2'); await settle();
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(plot);
expect(plot.style.getPropertyValue('--plot-height')).toBe('440px');
expect(fixture.nativeElement.querySelector('.figure-card .interpretation')).toBeTruthy();
});
it('C2 expande por Plotly y teclado, vuelve con foco y conserva host; reinicia al cambiar resultado', async () => {
const { figure, data } = donutFixture();
const hierarchy = donutHierarchy(figure, data)!;
state({ status: 'ready', figure, presentationFigure: figure, hierarchy }); await settle();
const host = fixture.nativeElement.querySelector('.plot');
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
expect(chart.figure.data).toHaveLength(1);
expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull();
expect(fixture.nativeElement.textContent).not.toContain('Volver a grupos');
expect(fixture.nativeElement.querySelectorAll('.donut-navigation > button')).toHaveLength(0);
const categories = fixture.nativeElement.querySelector('.donut-children-region') as HTMLElement;
expect(categories.classList.contains('expanded')).toBe(false);
expect(categories.getAttribute('aria-hidden')).toBe('true');
expect(categories.hasAttribute('inert')).toBe(true);
expect(fixture.nativeElement.querySelector('.donut-children-title').textContent).toBe('Categorías');
chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle();
expect(fixture.componentInstance.activeParent).toBe('G2');
expect(categories.classList.contains('expanded')).toBe(true);
expect(categories.hasAttribute('inert')).toBe(false);
expect(categories.getAttribute('aria-hidden')).toBeNull();
expect(chart.figure.data[0]['labels']).toEqual(['B', 'C']);
chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G1' }] }); await settle();
expect(fixture.componentInstance.activeParent).toBe('G1');
expect(chart.figure.data[0]['labels']).toEqual(['A']);
chart.plotClick.emit({ points: [{ curveNumber: 0, label: 'G2' }] }); await settle();
expect(fixture.componentInstance.activeParent).toBe('G1');
chart.plotClick.emit({ points: [{ curveNumber: 1, label: 'G2' }] }); await settle();
state({ status: 'ready', figure, presentationFigure: structuredClone(figure), hierarchy }); await settle();
expect(fixture.componentInstance.activeParent).toBe('G2');
const back = fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement;
expect(back.getAttribute('aria-label')).toBe('Restaurar vista de la gráfica');
expect(back.querySelector('svg')).not.toBeNull();
back.focus(); back.click(); await settle();
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.donut-keyboard button'));
expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.donut-restore')).toBeNull();
const group = fixture.nativeElement.querySelectorAll('.donut-keyboard button')[1] as HTMLButtonElement;
group.click(); await settle(); expect(group.getAttribute('aria-pressed')).toBe('true');
expect(fixture.nativeElement.querySelector('.plot')).toBe(host); expect(purge).not.toHaveBeenCalled();
state({ status: 'loading' }); expect(fixture.componentInstance.activeParent).toBeUndefined();
expect(fixture.nativeElement.querySelector('.donut-navigation')).toBeNull();
state({ status: 'ready', figure: structuredClone(figure), presentationFigure: figure, hierarchy }); await settle();
expect(chart.figure.data).toHaveLength(1); expect(fixture.nativeElement.querySelector('.plot')).toBe(host);
});
it('homologa la dona simple con leyenda HTML superior sin alterar categorías ni valores', async () => {
const { figure } = donutFixture();
figure.data.pop();
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
const copy = presentationFigure(figure, { indicador: selected.id, figura: 'fig_c2_donas', tema: 'claro' });
const legend = donutLegend(copy)!;
state({ status: 'ready', figure, presentationFigure: copy, donutLegend: legend }); await settle();
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
expect(fixture.nativeElement.querySelectorAll('.donut-static-legend__item')).toHaveLength(3);
expect(fixture.nativeElement.querySelector('.donut-static-legend').textContent).toContain('A');
expect(chart.figure.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
expect(chart.figure.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
expect(chart.figure.data[0]['labels']).toEqual(figure.data[0]['labels']);
expect(chart.figure.data[0]['values']).toEqual(figure.data[0]['values']);
const heading = fixture.nativeElement.querySelector('.figure-heading') as HTMLElement;
const legendElement = fixture.nativeElement.querySelector('.figure-legend') as HTMLElement;
const slot = fixture.nativeElement.querySelector('.plot-slot') as HTMLElement;
const notes = fixture.nativeElement.querySelector('.figure-footer') as HTMLElement;
expect(heading.compareDocumentPosition(legendElement) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(legendElement.compareDocumentPosition(slot) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(slot.compareDocumentPosition(notes) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
it.each(['dominio', 'figuraId', 'selected'])('reinicia expansión cuando cambia identidad %s aunque reciba la misma referencia de figura', input => {
const { figure, data } = donutFixture();
state({ status: 'ready', figure, presentationFigure: figure, hierarchy: donutHierarchy(figure, data) });
fixture.componentInstance.expandParent('G2');
fixture.componentRef.setInput(input, input === 'dominio' ? 'cama' : input === 'figuraId' ? 'otra_dona' : { ...selected, id: 'nuevo' });
fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined();
expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1);
});
it.each(['tea', 'cacu', 'cama'])('presenta notas %s como texto seguro dentro de «Cómo leer» y deja visible la fecha de corte', dominio => {
fixture.componentRef.setInput('dominio', dominio);
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} };
const notes = ['Nota de la ficha\nFuente: A & B · Fecha de corte: 2025-08-01\nLeyenda', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes,
minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] });
const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement;
expect(section.getAttribute('aria-label')).toBe('Notas de la figura');
expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes);
expect(section.querySelector('img, script, a')).toBeNull();
const detail = section.closest('.methodology-detail') as HTMLElement;
expect(detail).not.toBeNull(); expect(detail.hidden).toBe(true);
expect(section.previousElementSibling?.textContent).toBe('Notas de la figura');
// Interpretation lines come first; the notes are paragraphs, never list items.
expect(detail.querySelector('ul')!.compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(section.querySelector('li')).toBeNull();
expect(section.closest('.plot-viewport, app-plotly-chart, details, .figure-footer')).toBeNull();
expect(fixture.nativeElement.querySelector('.figure-footer').textContent.trim()).toBe('Fecha de corte: 2025-08-01');
expect(fixture.nativeElement.querySelector('.figure-labels .category-labels')).toBeTruthy();
for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) {
state({ status });
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
}
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] });
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva');
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
});
it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => {
const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} };
state({ status: 'ready', figure: original, presentationFigure: original, minimumPlotWidth: 598 }); await settle();
const chart = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
const host = chart.querySelector('.plot');
expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px');
expect(chart.querySelector('.plot-viewport')!.getAttribute('tabindex')).toBe('0');
state({ status: 'loading' }); await settle();
expect(chart.style.getPropertyValue('--plot-min-width')).toBe('598px');
state({ status: 'ready', figure: original, presentationFigure: original }); await settle();
expect(chart.style.getPropertyValue('--plot-min-width')).toBe('');
expect(chart.querySelector('.plot')).toBe(host); expect(original.data[0]['y']).toEqual([0, null, 20]);
});
it('UX-07C ofrece nombres completos en un details nativo sin rerenderizar Plotly ni ocultar notas', async () => {
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} };
const copy = presentationFigure(original, { indicador: 'i1', figura: 'fig_c1_puntos', tema: 'claro' });
state({ status: 'ready', figure: original, presentationFigure: copy,
categoryLabels: [{ axis: 'x', abbreviated: 'Fármaco…', original: 'Fármaco de riesgo para el neurodesarrollo' }],
footnotes: ['Nota metodológica siempre visible'] }); await settle();
const details = fixture.nativeElement.querySelector('details') as HTMLDetailsElement;
const summary = details.querySelector('summary')!;
expect(summary.textContent).toContain('Nombres completos'); expect(details.open).toBe(false);
expect(details.querySelector('li')!.textContent).toContain('Fármaco de riesgo para el neurodesarrollo');
const plot = fixture.nativeElement.querySelector('.plot'), calls = react.mock.calls.length;
summary.focus(); summary.click(); fixture.detectChanges(); await settle();
expect(details.open).toBe(true); expect(document.activeElement).toBe(summary);
expect(react).toHaveBeenCalledTimes(calls); expect(fixture.nativeElement.querySelector('.plot')).toBe(plot);
expect(fixture.nativeElement.querySelector('.methodological-footnotes').closest('details')).toBeNull();
state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('.category-labels')).toBeNull();
expect(fixture.nativeElement.querySelector('.plot').closest('[hidden]')).not.toBeNull();
});
it('muestra carga, error y emite reintento sin coordinar HTTP', () => {
state({ status: 'loading' });
expect(fixture.nativeElement.querySelector('mat-card').getAttribute('aria-busy')).toBe('true');
expect(fixture.nativeElement.textContent).toContain('Cargando figura');
const retry = vi.fn();
fixture.componentInstance.retry.subscribe(retry);
state({ status: 'error', message: 'La figura o los reportes no están disponibles para esta selección.' });
expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('reportes no están disponibles');
fixture.nativeElement.querySelector('.state button').click();
expect(retry).toHaveBeenCalledTimes(1);
expect(fixture.debugElement.query(By.directive(PlotlyChart))).toBeNull();
});
it('presenta selección incompleta y un indicador sin figuras', () => {
state({ status: 'idle' });
expect(fixture.nativeElement.textContent).toContain('Completa una selección válida');
fixture.componentRef.setInput('selected', { ...selected, figuras: [] });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('El indicador no tiene figuras disponibles');
});
it('presenta título del JSON, nombre amigable y conserva datos incluso si Plotly los muta', async () => {
const original: PlotlyFigure = {
data: [{ type: 'scatter', y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], x: { dtype: 'i1', bdata: 'AAE=' } }],
layout: { title: { text: 'Título publicado', font: { size: 20 } }, annotations: [{ text: 'Nota de supresión' }] },
config: { staticPlot: false }, frames: [], extra: { preserved: true },
};
const snapshot = JSON.stringify(original);
react.mockImplementation(async (_host, data, layout) => {
data[0].y[0] = 0;
layout.annotations[0].text = 'Cambio interno de Plotly';
});
const copy = ready(original);
await settle();
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Título publicado');
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe('Figura: Puntos');
expect(fixture.nativeElement.textContent).not.toContain('fig_c1_puntos');
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.figure).toBe(copy);
expect(JSON.stringify(original)).toBe(snapshot);
expect(copy.data).toEqual(original.data);
expect(copy.layout['annotations']).toEqual(original.layout['annotations']);
});
it('distingue resultado sin puntos del error y mantiene valores binarios indeterminados', async () => {
ready({ data: [{ y: [null] }], layout: {} });
await settle();
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
expect(fixture.debugElement.query(By.directive(PlotlyChart))).not.toBeNull();
ready({ data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' } }], layout: {} });
await settle();
expect(fixture.nativeElement.textContent).not.toContain('No hay valores visibles');
});
it('UX-07B representa pies como texto seguro, sin duplicación ni notas genéricas', async () => {
const figure = { data: [{ y: [42] }], layout: {} };
const note = 'Primera línea\n<img src=x onerror=alert(1)>\nAviso completo';
state({ status: 'ready', figure, presentationFigure: figure, footnotes: [note] }); await settle();
const notes = fixture.nativeElement.querySelector('.methodological-footnotes');
expect(notes.textContent).toBe(note); expect(notes.querySelector('img')).toBeNull();
expect(fixture.nativeElement.querySelectorAll('.methodological-footnotes p')).toHaveLength(1);
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.showNotes).toBe(false);
state({ status: 'loading' });
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
state({ status: 'ready', figure, presentationFigure: figure, footnotes: [] }); await settle();
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
});
it.each(['cacu', 'cama'])('conserva advertencias específicas de %s durante la carga', dominio => {
fixture.componentRef.setInput('dominio', dominio);
state({ status: 'loading' });
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %');
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('suprimidos no representan tasas observadas de 0 %');
});
it('conserva el error y reintento de renderizado dentro de PlotlyChart', async () => {
react.mockRejectedValueOnce(new Error('render'));
ready({ data: [{ y: [42] }], layout: {} });
await settle();
expect(fixture.nativeElement.textContent).toContain('No se pudo representar la figura');
const retry = vi.fn();
fixture.componentInstance.retry.subscribe(retry);
fixture.nativeElement.querySelector('app-plotly-chart button').click();
await settle();
expect(react).toHaveBeenCalledTimes(2);
expect(retry).not.toHaveBeenCalled();
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.status()).toBe('ready');
});
it('D.2 mantiene Plotly oculto entre resultados y purga al destruir la card', async () => {
ready({ data: [{ y: [42] }], layout: {} }); await settle();
const firstHost = fixture.nativeElement.querySelector('.plot');
expect(observe).toHaveBeenCalledWith(firstHost);
state({ status: 'loading' });
expect(firstHost.closest('[hidden]')).toBeTruthy();
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
state({ status: 'incompatible', message: 'Intervalo de tiempo no publicado' });
expect(firstHost.closest('[hidden]')).toBeTruthy();
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Intervalo de tiempo no publicado');
ready({ data: [{ y: [50] }], layout: {} }); await settle();
expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost);
expect(firstHost.closest('[hidden]')).toBeNull();
fixture.destroy();
expect(purge).toHaveBeenCalledWith(firstHost); expect(purge).toHaveBeenCalledTimes(1);
expect(disconnect).toHaveBeenCalledTimes(1);
});
it('UX-06E.P0.2 inicia cerrado y despliega toda la explicación con estado accesible', () => {
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
state({ status: 'idle' });
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
expect(section.textContent).toContain('Cómo leer');
expect(section.querySelector('h2')).toBeNull();
expect(section.classList.contains('expanded')).toBe(false);
expect(section.querySelector('.methodology-detail ul')).not.toBeNull();
expect(section.querySelector('ul')?.closest('[hidden]')).not.toBeNull();
expect(section.querySelectorAll('button')).toHaveLength(1);
expect(section.querySelectorAll('[hidden]')).toHaveLength(1);
const button = section.querySelector('button')!;
const detail = section.querySelector('[id]') as HTMLElement;
expect(button.getAttribute('aria-expanded')).toBe('false');
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false);
expect(button.getAttribute('aria-controls')).toBe(detail.id);
expect(detail.hidden).toBe(true);
expect(button.tagName).toBe('BUTTON');
expect(button.nextElementSibling?.classList.contains('methodology-detail')).toBe(true);
button.focus();
expect(document.activeElement).toBe(button);
expect(detail.textContent).toContain('SIN_DATO');
expect(detail.textContent).toContain('suprimidos no representan porcentajes observados de 0 %');
expect(detail.textContent).toContain('no permite determinar la disponibilidad');
expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation);
button.click(); fixture.detectChanges();
expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true');
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(true);
state({ status: 'loading' });
expect(detail.hidden).toBe(false);
button.click(); fixture.detectChanges();
expect(detail.hidden).toBe(true);
expect(fixture.nativeElement.classList.contains('methodology-expanded')).toBe(false);
expect(section.querySelector('.methodology-detail[hidden]')).toBe(detail);
});
it('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => {
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
state({ status: 'idle' });
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
button.click(); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('conteos por categoría');
fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas');
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('La caja representa Q1');
expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls'))
.toBe(fixture.nativeElement.querySelector('.methodology-detail').id);
});
it('usa instrucciones exactas en orden y conserva caracteres especiales como texto', () => {
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
fixture.componentRef.setInput('figuraId', 'fig_c2_donas');
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_donas', descripcion: 'No repetir', como_leer: [
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
] }] });
state({ status: 'idle' });
const lines = fixture.nativeElement.querySelectorAll('.methodology-detail li');
expect([...lines].map((line: Element) => line.textContent)).toEqual([
'Primera línea <img src=x onerror=alert(1)>', 'Se suprimen datos cuando corresponde.', 'Las categorías pequeñas se describen por separado.', 'Segunda línea & final',
]);
expect(fixture.nativeElement.querySelector('img')).toBeNull();
expect(fixture.componentInstance.interpretation).toEqual([...lines].map((line: Element) => line.textContent));
});
it.each([
['sin coincidencia', [{ figura: 'otra_figura', descripcion: null, como_leer: ['No corresponde.'] }]],
['vacías', [{ figura: 'fig_c2_apiladas', descripcion: 'Sin instrucciones específicas.', como_leer: [] }]],
['nulas', [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: null }]],
])('mantiene fallback local con figuras_detalle %s', (_label, details) => {
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
fixture.componentRef.setInput('metadata', { figuras_detalle: details });
state({ status: 'idle' });
expect(fixture.componentInstance.interpretation).toContain('Las categorías corresponden a la distribución de cada grupo y periodo.');
expect(fixture.componentInstance.interpretation).toContain('SIN_DATO, cuando aparece, es una categoría legítima de la representación.');
});
it('preserva íntegramente, sin filtrado semántico, instrucciones sobre supresión y categorías pequeñas', () => {
const instructions = ['Se ocultan categorías individuales pequeñas.', 'La supresión se determina por grupo.', 'Conclusión.'];
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2' });
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
fixture.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c2_apiladas', descripcion: null, como_leer: instructions }] });
state({ status: 'idle' });
expect(fixture.componentInstance.interpretation).toEqual(instructions);
expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((line: Element) => line.textContent)).toEqual(instructions);
});
it.each([
['fig_c2_barras', 'Barras'],
['fig_c2_donas', 'Donas'],
])('UX-07D.1 identifica %s con el nombre %s en la tarjeta de figura', (id, label) => {
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', figuras: [id] });
fixture.componentRef.setInput('figuraId', id);
ready({ data: [], layout: {} });
expect(fixture.nativeElement.querySelector('.figure-id').textContent).toBe(`Figura: ${label}`);
});
it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => {
fixture.componentRef.setInput('figuraId', figura);
if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' });
state({ status: 'idle' });
expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull();
expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((li: any) => li.textContent))
.toEqual(fixture.componentInstance.interpretation);
});
it.each(['cacu', 'cama'])('UX-06E.P0.2 conserva advertencias C2 de %s en ayuda cerrada', dominio => {
fixture.componentRef.setInput('dominio', dominio);
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
state({ status: 'loading' });
expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull();
const detail = fixture.nativeElement.querySelector('[hidden]') as HTMLElement;
expect(detail.hidden).toBe(true);
expect(detail.textContent).toContain('Las barras muestran conteos por categoría; los porcentajes publicados pueden aparecer como etiquetas. Consulta la unidad y el denominador de cada representación.');
expect(detail.textContent).toContain('SIN_DATO');
expect(detail.textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %');
});
it('UX-06E.P0.2 quita el panel redundante y preserva todas las anotaciones en Plotly', async () => {
const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [
{ text: 'Denominador pequeño<br>Intervalos no disponibles' },
{ text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' },
{ text: 'Supresión: consulta las notas completas' },
] }, frames: [] };
const snapshot = JSON.stringify(figure);
ready(figure); await settle();
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
expect(chart.figure.layout['annotations']).toEqual(figure.layout['annotations']);
expect(chart.notes).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text));
expect(JSON.stringify(figure)).toBe(snapshot);
expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0');
});
it.each(['claro', 'oscuro'] as const)('UX-06E.P0.2 conserva el tema %s sin duplicar anotaciones en HTML', async tema => {
fixture.componentRef.setInput('tema', tema);
const annotation = 'Advertencia metodológica única de la figura.';
const original: PlotlyFigure = { data: [{ y: [1] }], layout: { annotations: [{ text: annotation }] } };
ready(original); await settle();
const card = fixture.nativeElement.querySelector('.figure-card');
expect(card.classList.contains('dark')).toBe(tema === 'oscuro');
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
expect(fixture.nativeElement.textContent).not.toContain(annotation);
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
expect(chart.notes).toEqual([annotation]);
expect(JSON.stringify(original)).toContain(annotation);
});
it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => {
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' });
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
state({ status: 'idle' });
const first = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a' });
fixture.componentRef.setInput('figuraId', 'b--fig_c2_apiladas');
fixture.detectChanges();
const second = fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls');
expect(first).not.toBe(second);
expect(fixture.nativeElement.querySelector('[id]').id).toBe(second);
});
it.each(['tea', 'cacu', 'cama'])('UX-06E.B1 conserva C1 de %s íntegro con condiciones críticas visibles', dominio => {
fixture.componentRef.setInput('dominio', dominio);
state({ status: 'idle' });
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
const button = section.querySelector('button')!;
const detail = section.querySelector('[hidden]') as HTMLElement;
expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button');
// jsdom does not perform native Enter/Space activation; leave both keys
// available to the browser and validate activation in Chrome.
for (const key of ['Enter', ' ']) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
}
expect(button.textContent).toContain('Cómo leer');
expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba, ' + dominio + ', fig_c1_puntos');
expect(button.getAttribute('aria-expanded')).toBe('false');
expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true);
const warnings = detail.querySelector('ul')!;
expect(warnings.closest('[hidden]')).not.toBeNull();
expect(warnings.textContent).toContain('100 % no implica certeza poblacional');
expect(warnings.textContent).toContain('suprimidos no representan tasas observadas de 0 %');
if (dominio === 'tea') {
expect(warnings.textContent).toContain('Wilson al 95 %');
expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan');
expect(warnings.textContent).toContain('tamaño de muestra pequeño');
} else expect(warnings.textContent).toContain('Cuando la figura publica intervalos Wilson al 95 %');
expect([...warnings.querySelectorAll('li')].map(p => p.textContent))
.toEqual(fixture.componentInstance.interpretation);
button.focus(); button.click(); fixture.detectChanges();
expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(false);
expect(button.getAttribute('aria-expanded')).toBe('true');
button.click(); fixture.detectChanges();
expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(true);
});
it('UX-06E.P0.2 mantiene la oración mixta C3r y sus límites en ayuda cerrada', () => {
fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); state({ status: 'idle' });
const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement;
expect(section.querySelector('[hidden]')).not.toBeNull();
expect(section.querySelector('button')).not.toBeNull();
expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
'Los límites de dibujo no representan necesariamente extremos observados.',
'Pueden mostrarse etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
'Los puntos suprimidos no representan tasas observadas de 0 %.',
]);
});
it('UX-06E.P0.2 al alternar ayuda conserva Plotly, JSON y observadores sin react ni purge', async () => {
const original: PlotlyFigure = { data: [{ y: [42, null] }], layout: { annotations: [{ text: 'Advertencia íntegra del servicio' }] } };
const copy = ready(original); await settle();
const snapshot = JSON.stringify(original), copySnapshot = JSON.stringify(copy);
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance;
const host = fixture.nativeElement.querySelector('.plot');
const button = fixture.nativeElement.querySelector('.methodology-toggle');
const calls = react.mock.calls.length, observers = observe.mock.calls.length;
for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); await settle(); }
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart);
expect(fixture.nativeElement.querySelector('.plot')).toBe(host);
expect(fixture.nativeElement.querySelector('.notes')).toBeNull();
expect(react).toHaveBeenCalledTimes(calls); expect(observe).toHaveBeenCalledTimes(observers);
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
});
});