Files
WebApp/src/app/features/indicadores/indicadores-pinning.spec.ts
T
Angel Capetillo Zavala d159067efd feat(indicadores): CaMa clinical section heading and counter, without search, pins, navigation or representation selector
CaMa's graphic section reads «Indicadores clínicos» and counts the indicators it draws. The search box, pins, floating navigation, representation selector and figure count are not drawn for CaMa; CaCu and TEA keep them.

(cherry picked from commit e54ee5a55aa3722f6895300fa7e8cefb28f12ebb)
2026-11-12 00:29:14 -06:00

133 lines
10 KiB
TypeScript

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<typeof TestBed.createComponent<IndicadoresPage>>;
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('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => {
await pin('i3'); await pin('i4');
page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']);
expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true);
await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']);
expect(cards()).toHaveLength(items.length); http.expectNone(() => true);
});
it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => {
await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle();
expect(ids()[0]).toBe('i0');
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true);
});
it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => {
await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0);
expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); 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]);
});
});