Files
WebApp/src/app/features/indicadores/indicadores-sections.spec.ts
T
rockdrigo 6009aea83e feat(cama): «Análisis» tab with exploratory outcomes of the BI-RADS 4+ cohort
Breast cancer gets a tab between Histórico and Seguimiento that answers "how
often, and how fast, does a BI-RADS 4+ patient reach the event", by a
pre-specified stratum, with every number computed by the server and labelled
as descriptive.

How:
- AnalisisService reads GET /<domain>/analisis (scenarios, estimators, strata,
  filters, blocked analyses with their reasons) and
  GET /<domain>/analisis/resultados (C9b curves, risk table, log-rank with
  Holm pairs, RMST, C12 hazard ratios, C13 validation report).
- The guards accept demonstration data only, reject any key that only a
  patient row would carry (at any depth), a suppressed group with counts, and
  a published curve point with fewer at risk than the threshold.
- curvasFigura draws each published group as a step line with its 95 % band;
  forestFigura draws the HRs on a log axis, with an open marker when the
  proportional-hazards check fails. Both are pure functions of the answer.
- Clicking a curve keeps that group as a filter and stratifies by the other
  dimension (pedidoAlElegir); it only changes the request.
- Too few events, a 404 catalog and blocked analyses (recurrence, survival by
  stage, subtype and St. Gallen strata) are shown with their reason instead
  of an empty chart.
- CON_ANALISIS lists the domains with the tab: cama only.

Implications:
- The backend has neither endpoint yet: the tab shows "Funcionalidad
  pendiente de publicación" against the real WebApi. The contracts C9b, C12
  and C13 are drafts and need grooming before the kit implements them.
- No row-level data reaches the browser; suppression is the server's job and
  the client only double-checks it.
- Death as a competing event needs a vital status the schema doesn't have.
2026-11-12 12:42:49 -06:00

142 lines
9.2 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"]'));
// Breast cancer adds the exploratory analysis of its BI-RADS 4+ cohort after its history.
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis', 'Seguimiento', 'Datos y definiciones']
: domain === 'tea' ? ['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();
});
});