// What this module covers: the screening route component: when it loads, the seven requests it makes, what it draws for // each view and period, and its empty, error and incompatible states. The model and the figure have their own spec // (`screening-route.spec.ts`). // Fixtures: `payload`, synthetic C3r /datos shaped like /cacu/indicadores//datos; `ChartStub` stands for the chart. import { Component, input } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { By } from '@angular/platform-browser'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadorScreeningRoute } from './indicador-screening-route'; import { IndicadorDatos } from './indicadores.models'; import { ROUTE_IDS } from './screening-route'; @Component({ selector: 'app-plotly-chart', template: '' }) class ChartStub { figure = input(); label = input(); showNotes = input(); } const row = (periodo: string, n: number, q1: number, mediana: number, q3: number, suprimido = 0) => ({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' }); const MEDIANAS: Record = { cacu_eu_tiempo_reporte: 7.9, cacu_dias_toma_colposcopia: 35.7, cacu_dias_resultado_colposcopia: 27.8, cacu_dias_toma_biopsia: 52.1, cacu_dias_colposcopia_biopsia: 16.4, cacu_dias_toma_diagnostico: 18.4, cacu_dias_biopsia_diagnostico: 12.8, }; const payload = (id: string, suprimido = 0): IndicadorDatos => ({ id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], version: '1', filas: [row('2025-S1', 100, 3, MEDIANAS[id] + 1, MEDIANAS[id] + 9, suprimido), row('2025-S2', 120, 4, MEDIANAS[id], MEDIANAS[id] + 8, suprimido)], }); describe('Ruta del tamizaje: componente', () => { let f: ReturnType>; let http: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadorScreeningRoute], providers: [provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadorScreeningRoute, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); f = TestBed.createComponent(IndicadorScreeningRoute); f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('tema', 'claro'); }); afterEach(() => { f.destroy(); http.match(() => true); http.verify(); }); // The shared request queue runs a few at a time: answer in waves until nothing is left. function responder(entrega: (id: string) => IndicadorDatos = id => payload(id)) { const vistos: string[] = []; for (;;) { const pendientes = http.match(r => r.url.endsWith('/datos')); if (!pendientes.length) return vistos; for (const r of pendientes) { const id = r.request.url.split('/').at(-2)!; vistos.push(id); r.flush(entrega(id)); } f.detectChanges(); } } const charts = () => f.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); it('carga diferida; pide las siete medidas; dibuja una gráfica y cambia de vista y de periodo sin otra petición', () => { // Pins down: nothing is requested while hidden, each of the seven measures is requested once, the view and the period // are chosen without new requests, and the theme redraws the same data. Fails if the region loads before it is // visible, a measure is missing or repeated, or a control triggers a request. f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); expect(responder().sort()).toEqual([...ROUTE_IDS].sort()); expect(f.componentInstance.status()).toBe('ready'); expect(charts()).toHaveLength(1); expect(charts()[0].figure()).toBe(f.componentInstance.figure()); expect((f.componentInstance.figure()!.data[0] as Record)['base']).toBeUndefined(); f.componentInstance.selectView('steps'); f.detectChanges(); expect((f.componentInstance.figure()!.data[0] as Record)['base']).toBeDefined(); // the period follows the page's filter, with no request of its own f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges(); expect(f.componentInstance.model()!.period).toBe('2025-S1'); expect(f.nativeElement.querySelector('mat-select')).toBeNull(); f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); }); it('la tabla de valores publicados dice la mediana de cada evento y el estado si no hay caja', () => { // Fails if the table drops an event or shows a suppressed box as a number. f.detectChanges(); responder(id => (id === 'cacu_dias_toma_biopsia' ? payload(id, 1) : payload(id))); const text = f.nativeElement.querySelector('table').textContent as string; expect(text).toContain('Resultado de citología'); expect(text).toContain('mediana 35.7'); expect(text).toContain('Suprimido'); }); it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => { // Fails if the reading note goes back to an open paragraph under the chart. f.detectChanges(); responder(id => payload(id)); const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement; expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer'); expect(guia.open).toBe(false); expect(guia.textContent).toContain('bigote: Q1 a Q3'); expect(f.nativeElement.querySelector('section > p.note')).toBeNull(); }); it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => { // Fails if an empty route draws a chart or hides the reason. f.detectChanges(); responder(id => payload(id, 1)); expect(f.componentInstance.status()).toBe('empty'); expect(charts()).toHaveLength(0); expect(f.nativeElement.textContent).toContain('No hay tiempos publicados'); }); it('un fallo del servicio se anuncia como error y reintentar vuelve a pedir', () => { // Fails if an error leaves a stale chart, hides the alert, or retry does not request again. f.detectChanges(); http.match(r => r.url.endsWith('/datos'))[0].flush({}, { status: 500, statusText: 'Server Error' }); f.detectChanges(); expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); expect(charts()).toHaveLength(0); http.match(() => true); // the other requests of the first try were cancelled with it f.componentInstance.retry(); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); expect(responder().length).toBe(ROUTE_IDS.length); expect(f.componentInstance.status()).toBe('ready'); }); it('datos de otro contrato quedan incompatibles y no se dibujan', () => { // Fails if a payload that is not a duration is drawn as one. f.detectChanges(); responder(id => (id === 'cacu_dias_toma_biopsia' ? { ...payload(id), contrato: 'C1' } : payload(id))); expect(f.componentInstance.status()).toBe('incompatible'); expect(charts()).toHaveLength(0); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); }); });