Files
WebApp/src/app/features/indicadores/indicadores-sections.spec.ts
T

151 lines
9.7 KiB
TypeScript

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 { RouterTestingHarness } from '@angular/router/testing';
import { By } from '@angular/platform-browser';
import { routes } from '../../app.routes';
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card';
import { Indicador, DOMINIOS } from './indicadores.models';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const catalog: Indicador[] = [
{ id: 'published', titulo: 'Nombre publicado', contrato: 'C2', figuras: ['fig_c2_barras', 'fig_c2_donas', 'future'], tipos_periodo: ['mes'] },
{ id: 'incomplete', titulo: '', contrato: '', figuras: [], tipos_periodo: ['semestre'] },
];
describe('Secciones compartidas por dominio', () => {
let http: HttpTestingController;
beforeEach(() => {
iniciarSesionVisual();
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
// Domain switching lives in the shell's header (app.html), not on the page.
expect(root.querySelector('nav.domain-nav')).toBeNull();
for (const tab of tabs) {
const panel = root.querySelector<HTMLElement>('#' + tab.getAttribute('aria-controls'))!;
expect(panel.getAttribute('aria-labelledby')).toBe(tab.id);
expect(panel.hidden).toBe(tab.id !== 'tab-resumen');
}
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
tab('seguimiento').click(); harness.detectChanges();
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges();
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
expect(tracking.hidden).toBe(false);
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible');
if (domain === 'cama') {
// An unavailable cohort has no table and offers a retry.
expect(tracking.querySelector('table')).toBeNull();
expect(tracking.querySelector('app-seguimiento-tabla')).not.toBeNull();
expect(Array.from(tracking.querySelectorAll('button')).map(b => b.textContent?.trim())).toContain('Reintentar seguimiento');
} else {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
}
tab('datos').click(); harness.detectChanges();
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
tab('resumen').click(); harness.detectChanges();
expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards);
http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes.
});
it('cambiar de dominio reinicia Resumen tanto por router como por coordinación de página', async () => {
const harness = await RouterTestingHarness.create();
for (const domain of DOMINIOS) {
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
expect(page.activeSection()).toBe('resumen'); page.changeSection('datos'); harness.detectChanges();
}
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
page.changeDominio('tea'); http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges();
expect(page.activeSection()).toBe('resumen'); http.expectNone(() => true);
});
it('teclado mueve foco con flechas, Home y End sin activar una sección ni consultar', async () => {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges();
const tabs = Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.tabIndex)).toEqual([0, -1, -1, -1]);
const focus = tabs.map(tab => vi.spyOn(tab, 'focus'));
function key(index: number, key: string, target: number) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
tabs[index].dispatchEvent(event); expect(event.defaultPrevented).toBe(true);
expect(focus[target]).toHaveBeenCalled(); expect(page.activeSection()).toBe('resumen');
}
key(0, 'ArrowRight', 1); key(0, 'ArrowLeft', 3); key(1, 'Home', 0); key(0, 'End', 3);
tabs[3].click(); harness.detectChanges(); expect(tabs.map(t => t.tabIndex)).toEqual([-1, -1, -1, 0]);
http.expectNone(() => true);
});
it.each(['loading', 'empty', 'error'] as const)('Datos y definiciones comunica catálogo %s sin inventar contenido', async state => {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
const request = http.expectOne('/tea/indicadores');
if (state === 'empty') request.flush([]);
if (state === 'error') request.flush('private', { status: 503, statusText: 'Unavailable' });
page.changeSection('datos'); harness.detectChanges();
const root = harness.routeNativeElement!.querySelector('#panel-datos')!;
expect(root.textContent).toContain(state === 'loading' ? 'Cargando catálogo' : state === 'empty' ? 'No hay indicadores' : 'No se pudo cargar');
expect(root.querySelectorAll('details')).toHaveLength(0);
expect(root.textContent).not.toContain('private');
if (state === 'loading') request.flush([]);
if (state === 'error') {
root.querySelector<HTMLButtonElement>('button')!.click();
http.expectOne('/tea/indicadores').flush(catalog); harness.detectChanges();
expect(page.activeSection()).toBe('datos');
expect(root.querySelectorAll('details')).toHaveLength(2);
}
http.expectNone(() => true);
});
});
describe('Datos y definiciones reutiliza metadatos sin servicios', () => {
it.each(DOMINIOS)('publica sólo información disponible y nombres amigables para %s', domain => {
const fixture = TestBed.createComponent(IndicadoresDefinitions);
fixture.componentRef.setInput('dominio', domain);
fixture.componentRef.setInput('catalog', catalog); fixture.detectChanges();
const root: HTMLElement = fixture.nativeElement;
expect(root.querySelectorAll('details')).toHaveLength(catalog.length);
expect(root.querySelector('summary')?.textContent).toBe('Nombre publicado');
expect(root.textContent).toContain('Barras'); expect(root.textContent).toContain('Donas');
expect(root.textContent).toContain('Representación 3'); expect(root.textContent).not.toContain('fig_c2');
expect(root.textContent).toContain('Mensual'); expect(root.textContent).toContain('Semestral');
expect(root.textContent).toContain('Nombre pendiente de publicación');
expect(root.textContent).toContain('No hay representaciones publicadas');
expect(root.textContent).toContain('La definición metodológica está pendiente de información');
expect(root.textContent).not.toMatch(/WebApp|WebApi|C1|C2|C3r|Origen de la información/);
expect(root.textContent).toContain('La información metodológica ampliada no está disponible');
expect(root.querySelectorAll('details[open]')).toHaveLength(0);
expect(root.textContent).not.toContain('Interpretación y metodología');
fixture.destroy();
});
});