103 lines
7.6 KiB
TypeScript
103 lines
7.6 KiB
TypeScript
import { kpiQueriesProvider, 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 { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
|
|
|
describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => {
|
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
|
let http: HttpTestingController;
|
|
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
|
|
const disconnects: ReturnType<typeof vi.fn>[] = [];
|
|
beforeEach(() => {
|
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
|
vi.resetAllMocks(); disconnects.length = 0;
|
|
runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined);
|
|
vi.stubGlobal('ResizeObserver', class {
|
|
disconnect = vi.fn(); unobserve = vi.fn();
|
|
// Material outline labels also observe size; track only Plotly hosts here.
|
|
observe = vi.fn((target: Element) => { if (target.classList.contains('plot')) disconnects.push(this.disconnect); });
|
|
});
|
|
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider,
|
|
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
|
fixture = TestBed.createComponent(IndicadoresPage);
|
|
vi.spyOn(fixture.componentInstance as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController);
|
|
http.expectOne('/tea/indicadores').flush([{ id: 'M23_pacientes_evaluados', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'M24_confirmacion_diagnostico', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]);
|
|
fixture.detectChanges();
|
|
for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).setVisible(true);
|
|
fixture.detectChanges();
|
|
});
|
|
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
|
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
|
|
function respond() {
|
|
http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: { annotations: [{ text: 'Nota' }] } }));
|
|
fixture.detectChanges();
|
|
}
|
|
it('dos gráficos poseen hosts y etiquetas independientes y purgan al contraer', async () => {
|
|
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
|
expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2);
|
|
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
|
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea, M23_pacientes_evaluados, f');
|
|
expect(hosts[1].getAttribute('aria-label')).toBe('tea, M24_confirmacion_diagnostico, g');
|
|
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
|
fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges();
|
|
expect(runtime.purge).toHaveBeenCalledWith(hosts[0]);
|
|
expect(runtime.purge).not.toHaveBeenCalledWith(hosts[1]);
|
|
expect(disconnects[0]).toHaveBeenCalledTimes(1); expect(disconnects[1]).not.toHaveBeenCalled();
|
|
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart))).toHaveLength(1);
|
|
});
|
|
it('cambiar representación purga el host saliente y conserva el host del otro indicador', async () => {
|
|
respond(); await settle();
|
|
const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
|
const outgoing = charts[0].componentInstance.host.nativeElement;
|
|
const other = charts[1].componentInstance.host.nativeElement;
|
|
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
|
card.selectFigure('g'); fixture.detectChanges();
|
|
expect(runtime.purge).toHaveBeenCalledWith(outgoing); expect(runtime.purge).not.toHaveBeenCalledWith(other);
|
|
http.expectOne(r => r.url.endsWith('/M23_pacientes_evaluados/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
|
const current = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
|
expect(current[0].componentInstance.host.nativeElement).not.toBe(outgoing);
|
|
expect(current[1].componentInstance.host.nativeElement).toBe(other);
|
|
expect(runtime.react.mock.calls.filter(c => c[0] === other)).toHaveLength(1);
|
|
});
|
|
it('un error de renderizado y su reintento no afectan la otra instancia', async () => {
|
|
runtime.react.mockRejectedValueOnce(new Error('render'));
|
|
respond(); await settle(); const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
|
expect(charts[0].componentInstance.status()).toBe('error'); expect(charts[1].componentInstance.status()).toBe('ready');
|
|
const otherHost = charts[1].componentInstance.host.nativeElement;
|
|
charts[0].componentInstance.retry(); await settle();
|
|
expect(charts[0].componentInstance.status()).toBe('ready'); expect(charts[1].componentInstance.status()).toBe('ready');
|
|
expect(runtime.react.mock.calls.filter(c => c[0] === otherHost)).toHaveLength(1); http.expectNone(() => true);
|
|
});
|
|
it('destruir la página desconecta y purga todas las instancias salientes', async () => {
|
|
respond(); await settle(); fixture.destroy();
|
|
expect(runtime.purge).toHaveBeenCalledTimes(2); expect(disconnects).toHaveLength(2);
|
|
for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1);
|
|
});
|
|
it('D.2 conserva hosts reales ocultando resultados anteriores durante carga e incompatibilidad', async () => {
|
|
respond(); await settle();
|
|
const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
|
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
|
const page = fixture.componentInstance;
|
|
page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] };
|
|
page.applyFilters(); fixture.detectChanges();
|
|
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance)).toEqual(charts.map(c => c.componentInstance));
|
|
for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy();
|
|
expect(runtime.purge).not.toHaveBeenCalled();
|
|
respond(); await settle();
|
|
for (const host of hosts) expect(host.closest('[hidden]')).toBeNull();
|
|
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance.host.nativeElement)).toEqual(hosts);
|
|
// Published capability change is evaluated by each existing consumer.
|
|
const current = page.catalog()[0];
|
|
page.catalog.set(page.catalog().map(item => ({ ...item, tipos_periodo: ['mes'] }))); fixture.detectChanges(); await settle();
|
|
for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy();
|
|
expect(fixture.nativeElement.querySelectorAll('.incompatible')).toHaveLength(2);
|
|
expect(runtime.purge).not.toHaveBeenCalled(); http.expectNone(() => true);
|
|
});
|
|
});
|