Files
WebApp/src/app/features/indicadores/indicadores-pinning.spec.ts
T
Manuel Aurrecoechea Castillo c32d2b6012 feat(indicadores): show full domain names and share CaMa's summary
CaCu and TEA use the same menu labels and compact summary layout as cáncer de mama.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 19:28:27 -06:00

131 lines
8.9 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); }
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
async function pin(id: string) { page.togglePinned(card(id).indicador); fixture.detectChanges(); await settle(); }
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); }
it('no muestra el control de fijar y la memoria no reordena las tarjetas', async () => {
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
await pin('i3');
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
expect(ids()).toEqual(items.map(i => i.id));
await pin('i3');
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(false);
expect(ids()).toEqual(items.map(i => i.id));
http.expectNone(() => true);
});
it('varios fijados no alteran el orden del catálogo', async () => {
const original = page.catalog(), snapshot = JSON.stringify(original);
await pin('i4'); await pin('i2'); await pin('i0');
expect(ids()).toEqual(items.map(i => i.id));
await pin('i2'); expect(ids()).toEqual(items.map(i => i.id));
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
});
it('la selección de indicadores conserva el orden del catálogo', async () => {
await pin('i3'); await pin('i4');
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i1', 'i3', 'i4']);
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
expect(cards()).toHaveLength(3); http.expectNone(() => true);
});
it('Mostrar todos restaura el catálogo en su orden', async () => {
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i0']);
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
page.showAllIndicators(); fixture.detectChanges(); await settle();
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(items.map(i => i.id)); 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));
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
const memory = TestBed.inject(IndicadoresMemory);
expect(memory.isPinned('cacu', 'i1')).toBe(true);
expect(memory.isPinned('tea', 'i3')).toBe(true);
expect(memory.isPinned('cama', 'i1')).toBe(false);
page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
page.changeDominio('tea'); load(); expect(ids()).toEqual(items.map(i => i.id));
fixture.destroy(); create(); load();
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
expect(ids()).toEqual(items.map(i => i.id)); 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('fijar no mueve la tarjeta ni pide figuras', async () => {
const before = cards();
await pin('i4');
expect(cards()).toEqual(before);
await pin('i4');
expect(cards()).toEqual(before); 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]);
});
});