Files
WebApp/src/app/features/indicadores/indicadores-sections.spec.ts
T
rockdrigo e2b307abf5 feat(shell): domain menu in the header, as in the deployed dev version
How: on /indicadores/<domain> routes the App header shows the platform title
and a mat-menu button named after the current domain, listing the other two
(the same markup and styles as the deployed WebApp's app.html). Other routes
(Conectar, Gobernanza) keep the "Análisis de información" breadcrumb. The
indicators page drops its own TEA/CaCu/CaMa links, so there is one switcher.

Implications: domain switching now depends on the App shell; a page embedded
elsewhere has no way to change domain by itself. Specs that asserted the
in-page links now assert their absence, and app.spec covers the menu.
2026-11-09 18:10:58 -06:00

141 lines
9.0 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 { 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(() => {
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(); });
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"]'));
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' || domain === 'cama'
? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.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]);
// The App header switches domains (see app.html); the page has no switcher of its own.
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('El seguimiento aún no está disponible');
// Every domain queries its list; until it is published there is no table, only the form.
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();
});
});