import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigureCard } from './indicador-figure-card'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { c2Fixture } from './indicadores-c2-adapter.testing'; import { Indicador, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; import age from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json'; import status from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json'; @Component({selector:'app-plotly-chart',inputs:['figure','label','showNotes'],template:''}) class ChartStub {} const applied:GlobalApplied={tipo:'semestre',selection:{mode:'explicit',periodos:['2025-S2']},revision:1}; const item:Indicador={id:'cacu_eu7',version:'0.2.0',titulo:'Distribución',contrato:'C2',figuras:['fig_c2_barras'],tipos_periodo:['semestre'],filtros:[age,status].map(d=>({estrato:d.estrato,etiqueta:d.estrato,valores:d.valores_estrato.map(valor=>({valor,etiqueta:valor}))}))}; describe('Barras estratificadas: activación y caché',()=>{ let fixture:ReturnType>, http:HttpTestingController; const general=()=>({...c2Fixture(),id:item.id,version:item.version}); beforeEach(()=>{ TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); TestBed.overrideComponent(IndicadorFigureCard,{remove:{imports:[PlotlyChart]},add:{imports:[ChartStub]}}); fixture=TestBed.createComponent(IndicadorFigurePanel); http=TestBed.inject(HttpTestingController); for(const [k,v] of Object.entries({dominio:'cacu',indicador:item,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v); }); afterEach(()=>{fixture.destroy();http.verify();}); const request=()=>http.expectOne(r=>r.url.endsWith('/datos')); it('carga solo general; consulta dimensión elegida, filtra localmente y restaura sin GET',()=>{ fixture.detectChanges(); const base=request(); expect(base.request.params.has('estrato')).toBe(false); base.flush(general()); fixture.componentInstance.changeDimension('grupo_edad'); const q=request(); expect(q.request.params.get('estrato')).toBe('grupo_edad'); expect(q.request.params.get('periodos')).toBe('2025-S2'); q.flush(age); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Suprimido'); for(const selection of [{parent:'Anormal'},{parent:'Anormal',category:'LIEAG'},{}]) {fixture.componentRef.setInput('localSelection',selection);fixture.detectChanges();http.expectNone(()=>true);} fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status); fixture.componentInstance.changeDimension('grupo_edad'); http.expectNone(()=>true); fixture.componentInstance.changeDimension(''); http.expectNone(()=>true); expect(fixture.componentInstance.result().figure?.data[0]['x']).toEqual(general().filas.map(r=>r['n'])); }); it('reemplaza el selector por un toggle accesible y conserva las dimensiones publicadas',()=>{ fixture.detectChanges(); request().flush(general()); fixture.detectChanges(); const toggle = fixture.nativeElement.querySelectorAll('.distribution-toggle [role="radio"]') as NodeListOf; expect(toggle).toHaveLength(2); expect(fixture.nativeElement.querySelector('select')).toBeNull(); expect(toggle[0].textContent).toContain('Distribución general'); expect(toggle[0].getAttribute('aria-checked')).toBe('true'); expect(toggle[1].getAttribute('aria-checked')).toBe('false'); expect(toggle[1].disabled).toBe(false); for(const key of ['Enter', ' ']) { const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); toggle[1].dispatchEvent(event); expect(event.defaultPrevented).toBe(false); } toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges(); expect(fixture.componentInstance.dimension).toBe('grupo_edad'); expect(toggle[1].getAttribute('aria-checked')).toBe('true'); // The dimensions, apart from the counts or percentage toggle that follows them. expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2); expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2); for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); } }); it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{ fixture.componentRef.setInput('applied',{...applied,revision:2,selection:{mode:'todos'}}); fixture.detectChanges(); request().flush(general()); fixture.detectChanges(); const stratified = fixture.nativeElement.querySelectorAll('.distribution-toggle [role="radio"]')[1] as HTMLButtonElement; expect(stratified.disabled).toBe(true); expect(stratified.getAttribute('aria-checked')).toBe('false'); expect(fixture.nativeElement.querySelector('.distribution-note').textContent).toContain('Selecciona un periodo'); expect(fixture.nativeElement.querySelector('.distribution-control').getAttribute('aria-describedby')) .toBe(fixture.nativeElement.querySelector('.distribution-note').id); }); it('no declara ni consulta capacidades ausentes; no acepta ronda',()=>{ fixture.componentRef.setInput('indicador',{...item,filtros:undefined});fixture.detectChanges();request().flush(general());fixture.detectChanges(); expect(fixture.nativeElement.querySelector('select')).toBeNull();fixture.componentInstance.changeDimension('grupo_edad');http.expectNone(()=>true); }); it('aplica categoría solo en su periodo y limpia dependencia sin HTTP al restaurar',()=>{ fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');request().flush(age);fixture.detectChanges(); const all=structuredClone(fixture.componentInstance.result().figure); fixture.componentRef.setInput('localSelection',{parent:'Anormal',category:'LIEAG',period:'2025-S2'});fixture.detectChanges(); expect(fixture.componentInstance.result().figure?.data[0]['y']).toEqual(['LIEAG']); fixture.componentRef.setInput('localSelection',{parent:'Anormal',category:'LIEAG',period:'2026-S1'});fixture.detectChanges(); expect(fixture.componentInstance.result().figure).toEqual(all); fixture.componentRef.setInput('localSelection',{});fixture.detectChanges(); expect(fixture.componentInstance.result().figure).toEqual(all);http.expectNone(()=>true); }); it('cambio de periodo cancela transporte y consulta dimensión con el nuevo periodo',()=>{ fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');const old=request(); fixture.componentRef.setInput('applied',{...applied,revision:2,selection:{mode:'explicit',periodos:['2026-S1']}});fixture.detectChanges();expect(old.cancelled).toBe(true); const q=request();expect(q.request.params.get('periodos')).toBe('2026-S1');const data=structuredClone(age);data.periodos=['2026-S1'];data.filas.forEach(r=>r.periodo='2026-S1');q.flush(data); expect(fixture.componentInstance.result().status).toBe('ready'); }); it('identidades separan dimensión, filtros, versión, revisión, dominio y general',()=>{ const keys=[snapshotKey('cacu',item,applied),snapshotKey('cacu',item,applied,{estrato:'grupo_edad'}),snapshotKey('cacu',item,applied,{estrato:'estatus_seguimiento'}),snapshotKey('cacu',item,{...applied,revision:2}),snapshotKey('cama',item,applied),snapshotKey('cacu',{...item,version:'next'},applied),snapshotKey('cacu',item,applied,{filtros:['grupo_edad:25-34']})];expect(new Set(keys).size).toBe(keys.length); const snapshots=TestBed.inject(IndicadoresSnapshots); snapshots.datos('cacu',item.id,'semestre',['2025-S2'],item.version,{estrato:'grupo_edad',filtros:['grupo_edad:25-34']}).subscribe(); const q=request();expect(q.request.params.get('filtro')).toBe('grupo_edad:25-34');expect(q.request.params.get('estrato')).toBe('grupo_edad');q.flush(age); expect(snapshots.reading('cacu',item,applied)).toBeUndefined(); }); it('error de estrato no sustituye valores del Resumen y permite reintentar',()=>{ fixture.detectChanges();request().flush(general());fixture.componentInstance.changeDimension('grupo_edad');request().flush({}, {status:400,statusText:'Pending'}); expect(fixture.componentInstance.result().status).toBe('error');fixture.componentInstance.requestFigure();request().flush(age);expect(fixture.componentInstance.result().status).toBe('ready'); expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general()); }); }); describe('Barra lateral de estratificación', () => { // Fija: con más de dos estratificadores, la elección de dimensión, los valores visibles y la medida van en una // barra lateral; ocultar y volver a mostrar valores redibuja sin pedir datos. Falla si la barra no aparece, si un // valor oculto sigue en la figura, si se puede ocultar el último o si un cambio local vuelve a consultar. let fixture:ReturnType>, http:HttpTestingController; const tres:Indicador={...item,filtros:[...item.filtros!,{estrato:'estadio',etiqueta:'Estadio clínico',valores:[{valor:'I',etiqueta:'I'}]}]}; const general=()=>({...c2Fixture(),id:item.id,version:item.version}); beforeEach(()=>{ TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); TestBed.overrideComponent(IndicadorFigureCard,{remove:{imports:[PlotlyChart]},add:{imports:[ChartStub]}}); fixture=TestBed.createComponent(IndicadorFigurePanel); http=TestBed.inject(HttpTestingController); for(const [k,v] of Object.entries({dominio:'cama',indicador:tres,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v); }); afterEach(()=>{fixture.destroy();http.verify();}); const request=()=>http.expectOne(r=>r.url.endsWith('/datos')); const aside=()=>fixture.nativeElement.querySelector('.strata-sidebar') as HTMLElement; it('lista los estratificadores y oculta o muestra valores sin consultar',()=>{ fixture.detectChanges(); request().flush(general()); fixture.detectChanges(); expect(aside()).not.toBeNull(); expect(fixture.nativeElement.querySelector('.distribution-toggle')).toBeNull(); const opciones=[...aside().querySelectorAll('[role="radiogroup"] [role="radio"]')] as HTMLButtonElement[]; expect(opciones.map(b=>b.textContent!.trim())).toEqual(['Sin estratificar','Por grupo de edad','Por estatus de seguimiento','Por estadio clínico']); opciones[1].click(); request().flush(age); fixture.detectChanges(); const valores=()=>[...aside().querySelectorAll('.stratum-toggle')] as HTMLButtonElement[]; expect(valores()).toHaveLength(age.valores_estrato.length); valores()[0].click(); fixture.detectChanges(); expect(fixture.componentInstance.result().figure?.data.map(t=>t['name'])).not.toContain('<25'); expect(valores()[0].getAttribute('aria-pressed')).toBe('false'); for(const b of valores().slice(1,-1)) b.click(); fixture.detectChanges(); expect(valores().at(-1)!.disabled).toBe(true); expect(fixture.componentInstance.result().figure?.data).toHaveLength(1); (aside().querySelector('.sidebar-reset') as HTMLButtonElement).click(); fixture.detectChanges(); expect(fixture.componentInstance.result().figure?.data).toHaveLength(age.valores_estrato.length); http.expectNone(()=>true); }); it('cambiar de estratificador muestra de nuevo todos los valores',()=>{ fixture.detectChanges(); request().flush(general()); fixture.componentInstance.changeDimension('grupo_edad'); request().flush(age); fixture.componentInstance.toggleEstrato('<25'); expect(fixture.componentInstance.ocultos.size).toBe(1); fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status); expect(fixture.componentInstance.ocultos.size).toBe(0); expect(fixture.componentInstance.estratos.map(e=>e.valor)).toEqual(status.valores_estrato); }); });