Files
WebApp/src/app/features/indicadores/indicadores-visibility.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

247 lines
19 KiB
TypeScript

import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
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 { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadorPeriodFilters } from './indicador-period-filters';
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';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const items: Indicador[] = Array.from({ length: 5 }, (_, i) => ({
id: 'i' + i, titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'],
}));
// jsdom geometry and browser notifications are explicit, independent inputs.
class IntersectionControl {
static instances: IntersectionControl[] = [];
readonly targets = new Set<Element>();
observe = vi.fn((target: Element) => this.targets.add(target));
unobserve = vi.fn((target: Element) => this.targets.delete(target));
disconnect = vi.fn(() => this.targets.clear());
constructor(readonly callback: IntersectionObserverCallback, readonly options: IntersectionObserverInit) {
IntersectionControl.instances.push(this);
}
emit(target: Element, isIntersecting = true) {
this.callback([{ target, isIntersecting, intersectionRatio: isIntersecting ? 1 : 0 } as IntersectionObserverEntry], this as unknown as IntersectionObserver);
}
}
class ResizeControl {
static instances: ResizeControl[] = [];
readonly targets = new Set<Element>();
observe = vi.fn((target: Element) => this.targets.add(target));
unobserve = vi.fn((target: Element) => this.targets.delete(target));
disconnect = vi.fn(() => this.targets.clear());
constructor(readonly callback: ResizeObserverCallback) { ResizeControl.instances.push(this); }
emit() { this.callback([], this as unknown as ResizeObserver); }
}
describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
let page: IndicadoresPage;
let http: HttpTestingController;
let memory: IndicadoresMemory;
let sticky: HTMLElement;
let geometry: WeakMap<Element, DOMRect>;
let frames: Map<number, FrameRequestCallback>;
let sequence: number;
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
function rect(top: number, left = 0, width = 600, height = 80): DOMRect {
return { x: left, y: top, top, left, width, height, right: left + width, bottom: top + height, toJSON: () => ({}) } as DOMRect;
}
beforeEach(() => {
IntersectionControl.instances = []; ResizeControl.instances = [];
geometry = new WeakMap(); frames = new Map(); sequence = 0;
vi.stubGlobal('IntersectionObserver', IntersectionControl); vi.stubGlobal('ResizeObserver', ResizeControl);
vi.stubGlobal('innerWidth', 1440); vi.stubGlobal('innerHeight', 800);
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { frames.set(++sequence, callback); return sequence; });
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => { frames.delete(id); });
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function(this: Element) { return geometry.get(this) ?? rect(0, 0, 0, 0); });
sticky = document.createElement('header'); sticky.className = 'institutional-header'; document.body.append(sticky);
geometry.set(sticky, rect(0, 0, 1440, 100));
runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined);
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
create();
});
function create() {
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
http = TestBed.inject(HttpTestingController); memory = TestBed.inject(IndicadoresMemory);
}
afterEach(() => { fixture.destroy(); sticky.remove(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
async function render() { fixture.detectChanges(); await fixture.whenStable(); }
async function load(catalog = items, domain = 'tea') {
http.expectOne('/' + domain + '/indicadores').flush(catalog); await render();
positions(cards().map((_, i) => [1000 + i * 200, 0]));
}
function positions(values: number[][]) {
cards().forEach((card, i) => {
geometry.set(card.host.nativeElement, rect(values[i][0], values[i][1]));
geometry.set(card.visibilityRegion!.nativeElement, rect(values[i][0], values[i][1], 600, 620));
});
}
function observer() { return IntersectionControl.instances.at(-1)!; }
async function frame() {
const callbacks = [...frames.values()]; frames.clear(); callbacks.forEach(callback => callback(0)); await render();
}
async function confirm() { await frame(); await frame(); }
function notify(index = 0, intersects = true) { observer().emit(cards()[index].visibilityRegion!.nativeElement, intersects); }
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); }
async function idle() {
for (let i = 0; i < 6 && frames.size; i++) await frame();
expect(frames.size).toBe(0);
}
it.each([{ domain: 'tea', count: 18 }, { domain: 'cacu', count: 8 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => {
if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); }
await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'i' + i })), domain);
await idle(); expect(cards()).toHaveLength(count); expect(panels()).toHaveLength(count);
expect(panels().every(p => p.result().status === 'deferred')).toBe(true); http.expectNone(() => true);
expect(fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button')).toHaveLength(0);
expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(count);
positions(cards().map((_, i) => [i < 2 ? 200 : 1200 + i * 1000, i === 1 ? 650 : 0])); notify(); await confirm();
const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2);
requests.forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); await render(); await idle(); http.expectNone(() => true);
});
it('observa regiones gráficas permanentemente con margen de anticipación y sticky', async () => {
await load(); await idle();
expect(observer().options).toEqual({ root: null, threshold: 0, rootMargin: '-100px 0px 200px 0px' });
expect([...observer().targets]).toEqual(cards().map(c => c.visibilityRegion!.nativeElement));
positions([[900, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render();
expect(observer().targets.size).toBe(5); expect(panels()[0].result().status).toBe('ready');
expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(4);
});
it('salir y volver conserva panel, resultado y selección sin HTTP redundante', async () => {
await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render();
const panel = panels()[0], result = panel.result();
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(0, false); await idle();
expect(cards()[0].visible).toBe(false); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result);
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await idle();
expect(panel.result()).toBe(result); http.expectNone(() => true);
});
it('pestañas ocultan regiones sin activar tarjetas diferidas ni recargar las ya consultadas', async () => {
await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]);
notify(); await confirm(); respond(); await render();
const before = cards(), panel = panels()[0], result = panel.result();
for (const section of ['seguimiento', 'datos'] as const) {
page.changeSection(section); await render();
// TEA's Seguimiento loads its patient list; that request is unrelated to the cards.
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
// Even stale geometry/observer notifications cannot activate hidden cards.
positions(cards().map(() => [200, 0])); notify(1); await idle();
expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true);
}
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]);
page.changeSection('resumen'); await idle();
expect(cards()).toEqual(before); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result);
expect(cards().map(card => card.visible)).toEqual([true, false, false, false, false]);
http.expectNone(() => true);
});
it('filtro fuera de vista conserva host y consulta únicamente el último aplicado al regresar', async () => {
await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render();
const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart');
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle();
const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render();
filters.year = '2025'; filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle();
expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred');
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true);
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
const request = http.expectOne(r => r.url.includes('/i0/figuras/'));
expect(request.request.params.get('periodos')).toBe('2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro');
request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true);
});
it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => {
await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm();
const old = http.expectOne(r => r.url.includes('/i0/figuras/'));
positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll'));
page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] }; page.applyFilters(); await render();
expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('deferred'); http.expectNone(() => true);
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); await idle();
});
it('cambio rápido de representación cancela saliente y fuera de vista difiere seleccionada', async () => {
await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm();
const old = http.expectOne(r => r.url.endsWith('/figuras/f')); cards()[0].selectFigure('g'); await render();
expect(old.cancelled).toBe(true); const next = http.expectOne(r => r.url.endsWith('/figuras/g'));
cards()[0].selectFigure('h'); await render(); expect(next.cancelled).toBe(true);
http.expectOne(r => r.url.endsWith('/figuras/h')).flush({ data: [], layout: {} }); await render();
expect(panels()).toHaveLength(1); positions([[-1000, 0]]); notify(0, false); await idle();
cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred');
positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} });
});
it('fijación y selección conservan componentes y descartan callbacks con geometría antigua', async () => {
await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]);
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
observer().emit(target); await idle(); http.expectNone(() => true);
// Pins no longer reorder; the selected indicators keep catalog order and their components.
expect(cards()).toEqual([before[3], before[4]]);
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
expect(cards()[0].selectedFigure).toBe('f');
});
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
http.expectOne(r => r.url.includes('/figuras/')).flush(figure); await render();
expect(panels()[0].result().status).toBe('ready'); expect(panels()[0].result().figure).toEqual(figure);
expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull(); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
if (figure.layout.annotations) expect(panels()[0].result().figure?.layout['annotations']).toEqual(figure.layout.annotations);
});
it('error HTTP termina skeleton y reintenta sólo la figura visible', async () => {
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
http.expectOne(r => r.url.includes('/figuras/')).flush('private', { status: 503, statusText: 'Unavailable' }); await render();
expect(panels()[0].result().status).toBe('error'); expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull();
panels()[0].requestFigure(); respond(); await render(); expect(panels()[0].result().status).toBe('ready');
});
it('fallback sin IntersectionObserver muestra las figuras sin interacción manual', async () => {
http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); create();
await load([items[0]]); respond(); await render(); expect(panels()[0].result().status).toBe('ready');
expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull(); http.expectNone(() => true);
});
it('dominio cancela solicitudes, desobserva tarjetas retiradas e ignora callback antiguo', async () => {
await load(); const oldObserver = observer(), retired = cards()[0].visibilityRegion!.nativeElement;
page.catalog.set(items.slice(1)); await render(); expect(oldObserver.unobserve).toHaveBeenCalledWith(retired);
oldObserver.emit(retired); await idle(); http.expectNone(() => true);
positions([[200, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await confirm();
const request = http.expectOne(r => r.url.includes('/figuras/'));
page.changeDominio('cama'); await load([items[0]], 'cama'); expect(request.cancelled).toBe(true);
expect(oldObserver.disconnect).toHaveBeenCalled(); oldObserver.emit(retired); await idle(); http.expectNone(() => true);
});
it('destrucción desconecta observers, cancela frame y vuelve inocuos callbacks tardíos', async () => {
await load(); const active = observer(), target = cards()[0].visibilityRegion!.nativeElement;
notify(); const pending = [...frames.keys()]; fixture.destroy();
expect(active.disconnect).toHaveBeenCalled(); expect(ResizeControl.instances.some(o => o.disconnect.mock.calls.length)).toBe(true);
expect(pending.some(id => vi.mocked(window.cancelAnimationFrame).mock.calls.some(call => call[0] === id))).toBe(true);
const remaining = frames.size; active.emit(target); window.dispatchEvent(new Event('scroll')); expect(frames.size).toBe(remaining);
});
it('hosts Plotly permanecen montados fuera de vista y se purgan al destruir', async () => {
http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule();
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create();
await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); await render();
for (let i = 0; i < 12; i++) await Promise.resolve(); await render();
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart, host = chart.host.nativeElement;
expect(runtime.react).toHaveBeenCalledTimes(1); positions([[-1000, 0]]); notify(0, false); await idle();
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
page.changeSection(section); await idle();
for (const req of http.match(r => r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled();
expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true);
}
positions([[200, 0]]); notify(); await idle(); expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true);
fixture.destroy(); expect(runtime.purge).toHaveBeenCalledWith(host);
});
});