import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { provideRouter } from '@angular/router'; import { By } from '@angular/platform-browser'; import { applyGlobal, GlobalFilterState, IndicadoresMemory } from './indicadores-memory'; import { PlotlyFigure } from './indicadores.models'; import { Component } from '@angular/core'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorFigureCard } from './indicador-figure-card'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { BASE_VISUAL_PROFILE, DEMO_VISUAL_PROFILE, READABLE_VISUAL_PROFILE } from './indicadores-visual-profile'; import { donutFixture } from './indicadores-donut-drilldown.testing'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub { figure?: PlotlyFigure; } const catalog = [ { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }, { id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] }, { id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] }, ]; describe('IndicadorFigurePanel', () => { let page: IndicadorFigurePanel; let state: GlobalFilterState; let editor: IndicadorPeriodFilters; let http: HttpTestingController; let fixture: ReturnType>; beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadorFigurePanel, IndicadorPeriodFilters], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadorFigurePanel); fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]); fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro'); state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']); fixture.componentRef.setInput('applied', state.applied); editor = new IndicadorPeriodFilters(); editor.state = state; editor.types = ['semestre']; page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); }); afterEach(() => { fixture.destroy(); http.verify(); }); function filters() { fixture.detectChanges(); return editor; } function apply() { if (applyGlobal(state, ['semestre'])) { fixture.componentRef.setInput('applied', state.applied); fixture.detectChanges(); } } function load() { fixture.detectChanges(); } function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); } function candidate() { // An unknown representation retains the legacy server-first hierarchy path. fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: 'C2', figuras: ['future_donut', 'f2'] }); fixture.componentRef.setInput('figuraId', 'future_donut'); load(); const sample = donutFixture(); figure().flush(sample.figure); return sample; } it('C2 carga metadatos una vez; explorar, volver y adaptar ancho no consulta HTTP', () => { const sample = candidate(); const data = http.expectOne(r => r.url === '/tea/indicadores/i1/datos' && r.params.get('periodos') === '2025-S2'); data.flush(sample.data); fixture.detectChanges(); const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard; expect(page.result().hierarchy?.parents).toEqual(['G1', 'G2']); card.expandParent('G2'); expect(card.chartFigure?.data[0]['labels']).toEqual(['B','C']); page.updatePlotWidth(400); fixture.detectChanges(); expect(card.activeParent).toBe('G2'); card.returnToParents(); http.expectNone(() => true); fixture.componentRef.setInput('figuraId', 'f2'); fixture.detectChanges(); expect(card.activeParent).toBeUndefined(); figure().flush({ data: [], layout: {} }); fixture.detectChanges(); expect(page.result().hierarchy).toBeUndefined(); http.expectNone(() => true); }); it('descubre una representación futura de un anillo sin IDs codificados y restaura desde la UI sin HTTP', () => { fixture.componentRef.setInput('indicador', { ...catalog[0], id: 'future_item', contrato: 'C2', figuras: ['future_donut'] }); fixture.componentRef.setInput('figuraId', 'future_donut'); load(); const sample = donutFixture(); sample.figure.data.pop(); sample.data.id = 'future_item'; figure().flush(sample.figure); http.expectOne(r => r.url.endsWith('/future_item/datos')).flush(sample.data); fixture.detectChanges(); const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard; expect(card.state.hierarchy?.parents).toEqual(['G1','G2']); const chart = fixture.debugElement.query(By.directive(ChartStub)); chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 0, label: 'G2' }] }); fixture.detectChanges(); expect(card.activeParent).toBe('G2'); chart.triggerEventHandler('plotClick', { points: [{ curveNumber: 1, label: 'G1' }] }); fixture.detectChanges(); expect(card.activeParent).toBe('G1'); (fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges(); expect(card.activeParent).toBeUndefined(); http.expectNone(() => true); expect(page.result().figure).toEqual(sample.figure); }); it.each(['http', 'suppression', 'mismatch'])('C2 conserva la figura publicada cuando %s impide la jerarquía', reason => { const sample = candidate(), request = http.expectOne(r => r.url.endsWith('/datos')); if (reason === 'http') request.flush({}, { status: 503, statusText: 'Unavailable' }); else { if (reason === 'suppression') sample.data.filas[0]['suprimido'] = 1; else sample.data.filas[0]['n'] = 999; request.flush(sample.data); } fixture.detectChanges(); expect(page.result().status).toBe('ready'); expect(page.result().hierarchy).toBeUndefined(); expect(page.result().figure).toEqual(sample.figure); }); it('C2 cancela metadatos pendientes al cambiar tema y no presenta resultados obsoletos', () => { candidate(); const old = http.expectOne(r => r.url.endsWith('/datos')); fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); expect(old.cancelled).toBe(true); expect(page.result().status).toBe('loading'); figure().flush({ data: [], layout: {} }); expect(page.result().hierarchy).toBeUndefined(); }); it('UX-07D.2 conserva notas al cambiar perfil/ancho y elimina resultados obsoletos durante carga', () => { fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('indicador', { ...catalog[0], figuras: ['fig_c2_barras'], contrato: 'C2' }); fixture.componentRef.setInput('figuraId', 'fig_c2_barras'); const request = () => http.expectOne(req => req.url.includes('/cama/indicadores/') && req.url.includes('/figuras/')); const response = (text: string): PlotlyFigure => ({ data: [{ type: 'bar', x: ['A'], y: [0] }], layout: { annotations: [{ text, xref: 'paper', yref: 'paper', x: 0, y: -0.22, xanchor: 'left', yanchor: 'top', align: 'left', showarrow: false, font: { size: 11 } }] } }); load(); http.expectOne(r => r.url.endsWith('/datos')).flush({ id: 'i1', contrato: 'C2', tipo_periodo: 'semestre', periodos: [], filas: [] }); request().flush(response('Nota vigente')); fixture.detectChanges(); for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE]) { fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); for (const width of [230, 320, 768, 1440]) page.updatePlotWidth(width); expect(page.result().footnotes).toEqual(['Nota vigente']); http.expectNone(() => true); } page.requestFigure(); const old = request(); fixture.detectChanges(); expect(page.result().footnotes).toBeUndefined(); expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull(); fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); expect(old.cancelled).toBe(true); const current = request(); current.flush(response('Nota del periodo actual')); fixture.detectChanges(); expect(page.result().footnotes).toEqual(['Nota del periodo actual']); expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota del periodo actual'); http.expectNone(() => true); }); it('UX-07C alterna etiquetas desde el original sin HTTP, conserva el host y restaura hover/categorías', () => { const label = 'Fármaco de riesgo para el neurodesarrollo'; const received: PlotlyFigure = { data: [{ type: 'bar', x: [label], y: [0], customdata: [null], hovertemplate: '%{x}
%{y:.1f}%' }], layout: { xaxis: { type: 'category' } } }; load(); figure().flush(received); fixture.detectChanges(); const before = structuredClone(received), host = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; expect(page.result().categoryLabels?.[0].original).toBe(label); expect(fixture.nativeElement.querySelector('.category-labels')).not.toBeNull(); page.updatePlotWidth(1400); fixture.detectChanges(); expect(page.result().categoryLabels).toEqual([]); const unchanged = page.result(); for (const width of [1400.7, 1399, 1350, 0, NaN]) page.updatePlotWidth(width); expect(page.result()).toBe(unchanged); page.updatePlotWidth(320); fixture.detectChanges(); expect(page.result().categoryLabels).toHaveLength(1); http.expectNone(() => true); for (const profile of [BASE_VISUAL_PROFILE, READABLE_VISUAL_PROFILE, BASE_VISUAL_PROFILE]) { fixture.componentRef.setInput('visualProfile', profile); fixture.detectChanges(); http.expectNone(() => true); expect(page.result().figure).toEqual(before); expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(host); if (profile === BASE_VISUAL_PROFILE) { expect(page.result().presentationFigure?.data).toEqual(before.data); expect(page.result().categoryLabels).toEqual([]); } else expect(page.result().categoryLabels).toHaveLength(1); } expect(received).toEqual(before); }); it.each([ ['C1', ['proporción observada', 'Wilson al 95 %', 'tamaño de muestra pequeño', '100 % no implica certeza poblacional']], ['C2', ['conteos por categoría', 'distribución de cada grupo y periodo', 'SIN_DATO']], ['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']], ['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']], ['toString', ['No hay una explicación específica']], ])('explica el contrato %s y la distinción entre reporte y valores representables', (contract, expected) => { fixture.componentRef.setInput('indicador', { ...catalog[0], contrato: contract, figuras: ['f1'] }); load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges(); const help = fixture.nativeElement.querySelector('.interpretation').textContent; for (const text of expected) expect(help).toContain(text); if (contract === 'C3r') { expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados'); expect(help).not.toMatch(/serving|corrección|fase independiente/i); } expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables'); }); it('oculta sólo visualmente el encabezado y conserva identidad, lectura y títulos sin HTTP adicional', () => { load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges(); const id = page.titleId; const heading = fixture.nativeElement.querySelector('h3') as HTMLElement; const section = fixture.nativeElement.querySelector('section') as HTMLElement; expect(heading.id).toBe(id); expect(id).not.toBe(''); expect(section.getAttribute('aria-labelledby')).toBe(id); expect(section.firstElementChild).toBe(heading); expect(heading.textContent).toBe('tea, i1, Uno, f1'); expect(heading.hasAttribute('aria-hidden')).toBe(false); expect(heading.hidden).toBe(false); const style = getComputedStyle(heading); expect(style.display).not.toBe('none'); expect(style.visibility).not.toBe('hidden'); expect(style.position).toBe('absolute'); expect(style.width).toBe('1px'); expect(style.height).toBe('1px'); expect(style.clipPath).toBe('inset(50%)'); expect(style.overflow).toBe('hidden'); expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno'); expect(fixture.nativeElement.querySelector('app-indicador-period-filters')).toBeNull(); const result = page.result(), savedState = state; fixture.detectChanges(); expect(page.titleId).toBe(id); expect(state).toBe(savedState); expect(page.result()).toBe(result); expect(fixture.nativeElement.querySelector('h3')).toBe(heading); http.expectNone(() => true); }); it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => { load(); const received: PlotlyFigure = { data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }], layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true }, config: { staticPlot: false }, frames: [], extra: { preserved: true }, }; const original = JSON.stringify(received); figure().flush(received); fixture.detectChanges(); expect(JSON.stringify(received)).toBe(original); expect(page.result().figure).toEqual(received); const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub; expect(chart.figure).toBe(page.result().presentationFigure); expect(chart.figure).not.toBe(page.result().figure); expect(chart.figure?.data).toEqual(received.data); expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } }); expect(JSON.stringify(page.result().figure)).toBe(original); expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno'); }); it('edita sin HTTP, bloquea vacío y aplica una consulta explícita', () => { load(); figure().flush({ data: [], layout: {} }); const control = filters(); control.select([]); expect(control.canApply).toBe(false); apply(); http.expectNone(req => req.url.includes('/figuras/')); control.year = '2025'; control.unit = 'S1'; control.add(); control.unit = 'S2'; control.add(); http.expectNone(req => req.url.includes('/figuras/')); expect(state?.applied?.selection.mode).toBe('todos'); apply(); const manual = figure(); expect(manual.request.params.get('periodos')).toBe('2025-S2'); control.select([]); expect(manual.cancelled).toBe(false); expect(control.canApply).toBe(false); apply(); http.expectNone(req => req.url.includes('/figuras/')); manual.flush({ data: [], layout: {} }); }); it('UX-07B cambia perfil y restaura desde el original sin HTTP ni pérdida de host o revisión', () => { load(); const received = { data: [{ y: [0, null], marker: { color: 'gray' } }], layout: { paper_bgcolor: 'white' }, future: 42 }; figure().flush(received); fixture.detectChanges(); const base = structuredClone(page.result().presentationFigure); const original = page.result().figure; const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; const applied = page.applied; fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); expect(page.result().figure).toBe(original); expect(page.applied).toBe(applied); expect(page.result().presentationFigure?.data).toEqual(received.data); expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); http.expectNone(() => true); fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges(); expect(page.result().presentationFigure).toEqual(base); expect(page.result().figure).toEqual(received); http.expectNone(() => true); }); it('UX-07B cambiar perfil durante carga no cancela ni inicia solicitudes', () => { load(); const pending = figure(); fixture.componentRef.setInput('visualProfile', DEMO_VISUAL_PROFILE); fixture.detectChanges(); expect(pending.cancelled).toBe(false); http.expectNone(() => true); pending.flush({ data: [], layout: {} }); fixture.detectChanges(); expect(page.result().presentationFigure?.layout['paper_bgcolor']).toBe('#f2f7fc'); http.expectNone(() => true); }); it('cancela figuras al cambiar tema rápidamente', () => { load(); const old = figure(); fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); const dark = figure(); expect(old.cancelled).toBe(true); expect(dark.request.params.get('tema')).toBe('oscuro'); fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges(); expect(dark.cancelled).toBe(true); figure().flush({ data: [], layout: {} }); }); it.each([ [400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'], ])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => { load(); figure().flush('error privado', { status: status as number, statusText: 'Error' }); expect(page.result().status).toBe('error'); expect(page.result().message).toContain(message); fixture.detectChanges(); expect(fixture.nativeElement.textContent).not.toContain('error privado'); fixture.nativeElement.querySelector('app-indicador-figure-card .state button').click(); figure().flush({ data: [], layout: {} }); expect(page.result().status).toBe('ready'); }); it('distingue conexión fallida y cancela HTTP al destruirse', () => { load(); figure().error(new ProgressEvent('error')); expect(page.result().message).toContain('conectar'); page.requestFigure(); const pending = figure(); fixture.destroy(); expect(pending.cancelled).toBe(true); }); it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => { load(); figure().flush({ data: [{ y: [0, null] }], layout: {} }); const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add(); fixture.detectChanges(); expect(page.result().figure?.data[0]['y']).toEqual([0, null]); expect(editor.hasPending).toBe(true); expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte'); http.expectNone(r => r.url.includes('/figuras/')); }); it.each([{ periodos: ['2025-S1'] }])('404 de un periodo conserva borrador y reintenta la última aplicación', ({ periodos }) => { load(); figure().flush({ data: [{ y: [42] }], layout: {} }); const control = filters(); control.select([]); control.year = '2025'; for (const period of periodos) { control.unit = period.slice(-2); control.add(); } apply(); const req = figure(); expect(page.result().figure).toBeUndefined(); req.flush('private', { status: 404, statusText: 'Not Found' }); expect(page.result().status).toBe('error'); expect(page.result().figure).toBeUndefined(); expect(page.result().message).toContain('esta selección'); expect(page.result().message).not.toContain('2025'); expect(control.selectedPeriods).toEqual(periodos); control.select([]); page.requestFigure(); const retry = figure(); expect(retry.request.params.get('periodos')).toBe(periodos.join(',')); retry.flush({ data: [{ y: [null] }], layout: {} }); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); expect(control.entry.draft.mode).toBe('empty'); }); it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => { load(); figure().flush({ data: [], layout: {} }); const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add(); apply(); figure().flush({ data: [{ y: [20] }], layout: {} }); control.unit = 'S2'; control.add(); fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges(); const themed = figure(); expect(themed.request.params.get('periodos')).toBe('2025-S1'); expect(themed.request.params.get('tema')).toBe('oscuro'); themed.flush('error', { status: 500, statusText: 'Server Error' }); page.requestFigure(); const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1'); retry.flush({ data: [], layout: {} }); expect(control.selectedPeriods).toEqual(['2025-S2']); }); it('descarta respuestas obsoletas de aplicaciones sucesivas', () => { load(); figure().flush({ data: [], layout: {} }); const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add(); apply(); const old = figure(); control.unit = 'S2'; control.add(); expect(old.cancelled).toBe(false); apply(); const current = figure(); expect(old.cancelled).toBe(true); expect(current.request.params.get('periodos')).toBe('2025-S2'); current.flush({ data: [{ y: [12] }], layout: {} }); expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); expect(page.result().figure?.data[0]['y']).toEqual([12]); }); it('UX-06E.B1 alterna ayuda sin HTTP y conserva filtros, borrador, memoria y panel', () => { load(); figure().flush({ data: [{ y: [42] }], layout: {} }); const control = filters(); control.select([]); control.year = '2025'; control.unit = 'S1'; control.add(); fixture.detectChanges(); const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState); const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance; const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance; const button = fixture.nativeElement.querySelector('.methodology-toggle'); for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); } http.expectNone(() => true); expect(page.result()).toBe(result); expect(state).toBe(filterState); expect(JSON.stringify(state)).toBe(snapshot); expect(filters()).toBe(control); expect(fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance).toBe(card); expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart); fixture.destroy(); fixture = TestBed.createComponent(IndicadorFigurePanel); fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]); fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', state.applied); page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} }); expect(JSON.stringify(state)).toBe(snapshot); expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-expanded')).toBe('false'); }); });