import { periodAvailabilityProvider } from './indicadores-periodos.testing'; 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 { IndicadoresPage } from './indicadores-page'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadoresMemory } from './indicadores-memory'; import { Indicador } from './indicadores.models'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; const items: Indicador[] = ['Edad', 'Evaluación inicial', 'Sexo', 'Seguimiento', 'Evaluación final'].map((titulo, i) => ({ id: 'i' + i, titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'], })); describe('UX-06E.D.3.B fijación temporal', () => { let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; beforeEach(() => { vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); }); TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); load(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function create() { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); } function load(domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function card(id: string) { return cards().find(c => c.indicador.id === id)!; } function ids() { return cards().map(c => c.indicador.id); } function button(id: string): HTMLButtonElement { return card(id).host.nativeElement.querySelector('.pin-toggle')!; } async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); } async function pin(id: string) { button(id).click(); fixture.detectChanges(); await settle(); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); } it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => { const control = button('i3'); expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0); expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false'); expect(control.getAttribute('aria-label')).toContain('Fijar indicador'); for (const key of ['Enter', ' ']) { const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); } await pin('i3'); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); expect(button('i3')).toBe(control); expect(control.getAttribute('aria-pressed')).toBe('true'); expect(control.textContent).toContain('Desfijar indicador'); expect(control.getAttribute('aria-label')).toContain('Desfijar indicador'); await pin('i3'); expect(ids()).toEqual(items.map(i => i.id)); expect(control.getAttribute('aria-pressed')).toBe('false'); http.expectNone(() => true); }); it('varios fijados conservan orden del catálogo, independientemente del orden de clics', async () => { const original = page.catalog(), snapshot = JSON.stringify(original); await pin('i4'); await pin('i2'); await pin('i0'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']); await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']); await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']); expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true); }); it('la selección de indicadores conserva la prioridad de los fijados', async () => { await pin('i3'); await pin('i4'); page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle(); expect(ids()).toEqual(['i3', 'i4', 'i1']); await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']); expect(cards()).toHaveLength(3); http.expectNone(() => true); }); it('Mostrar todos restaura el catálogo con los fijados primero', async () => { await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle(); expect(ids()).toEqual(['i0']); fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true); }); it('un fijado sin seleccionar no se muestra', async () => { await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle(); expect(ids()).toEqual(['i0', 'i1']); http.expectNone(() => true); }); it('memoria independiente por dominio y persistente al recrear la página', async () => { await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id)); // CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins. await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id)); page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1'); page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3'); fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true); }); it('no usa Storage y una nueva memoria reinicia la fijación', async () => { const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem'); await pin('i2'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i2')).toBe(true); expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false); expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true); }); it('mover la tarjeta conserva foco en su botón existente', async () => { const control = button('i4'); control.focus(); await pin('i4'); expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control); await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true); }); it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => { card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle(); card('i3').selectFigure('g'); fixture.detectChanges(); respond(); await settle(); const before = cards(), panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; const host = chart.host.nativeElement, result = panel.result(), applied = page.filters!.applied; const reacts = runtime.react.mock.calls.length, purges = runtime.purge.mock.calls.length; for (const id of ['i3', 'i1', 'i3']) { await pin(id); for (const c of before) expect(card(c.indicador.id)).toBe(c); expect(card('i3').visible).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').visible).toBe(true); expect(card('i1').visible).toBe(false); expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); expect(chart.host.nativeElement).toBe(host); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied); http.expectNone(() => true); } expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).toHaveBeenCalledTimes(purges); }); it('mover un panel cargando conserva su petición sin cancelar ni duplicar', async () => { card('i4').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f')); const panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; await pin('i4'); expect(request.cancelled).toBe(false); expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); http.expectNone(() => true); request.flush({ data: [{ y: [7] }], layout: {} }); await settle(); expect(panel.result().figure.data[0].y).toEqual([7]); }); });