128 lines
10 KiB
TypeScript
128 lines
10 KiB
TypeScript
import { Component } from '@angular/core';
|
|
import { TestBed } from '@angular/core/testing';
|
|
import { By } from '@angular/platform-browser';
|
|
import { provideHttpClient } from '@angular/common/http';
|
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
|
import { IndicadorFigureCard } from './indicador-figure-card';
|
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
|
import { c2Figure } from './indicadores-c2-adapter';
|
|
import { DonutSelection } from './indicadores-donut-drilldown';
|
|
import { FigureSelection, PlotlyFigure } from './indicadores.models';
|
|
import { BASE_VISUAL_PROFILE } from './indicadores-visual-profile';
|
|
|
|
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
|
class ChartStub {}
|
|
const applied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
|
const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] };
|
|
describe('barras generales conectadas con la selección compartida de la dona', () => {
|
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>, http: HttpTestingController;
|
|
const panel = () => fixture.componentInstance;
|
|
const select = (local: DonutSelection) => { fixture.componentRef.setInput('localSelection', local); fixture.detectChanges(); };
|
|
const request = () => http.expectOne(r => r.url.endsWith('/datos'));
|
|
const displayed = () => panel().result().presentationFigure!;
|
|
beforeEach(() => {
|
|
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
|
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
|
fixture = TestBed.createComponent(IndicadorFigurePanel); http = TestBed.inject(HttpTestingController);
|
|
for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_barras', tema: 'claro', applied })) fixture.componentRef.setInput(k, v);
|
|
});
|
|
afterEach(() => { fixture.destroy(); http.verify(); });
|
|
function load() { fixture.detectChanges(); request().flush(c2Fixture()); fixture.detectChanges(); }
|
|
it('grupo → categoría → restaurar actualiza sólo la presentación, sin GET ni cambio de filtro', () => {
|
|
load(); const original = panel().result().figure, before = structuredClone(original), all = structuredClone(displayed());
|
|
const filter = structuredClone(panel().applied), host = fixture.nativeElement.querySelector('app-plotly-chart');
|
|
expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']);
|
|
select({ parent: 'G2', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B', 'C']);
|
|
select({ parent: 'G2', category: 'B', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B']);
|
|
expect(panel().result().figure).toBe(original); expect(original).toEqual(before);
|
|
expect(fixture.nativeElement.querySelector('.selection-status').getAttribute('aria-label')).toContain('G2, B, 2025-S2');
|
|
select({}); expect(displayed()).toEqual(all); expect(panel().generalSelectionContext).toBeUndefined();
|
|
expect(panel().applied).toEqual(filter); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true);
|
|
});
|
|
it('mantiene el mismo estado compacto antes, durante y después de seleccionar, fuera del lienzo', () => {
|
|
load();
|
|
const status = fixture.nativeElement.querySelector('.selection-status') as HTMLElement;
|
|
const plot = fixture.nativeElement.querySelector('app-plotly-chart') as HTMLElement;
|
|
const height = plot.style.getPropertyValue('--plot-height');
|
|
expect(status.textContent).toContain('Distribución completa');
|
|
expect(status.closest('.panel-controls')).toBeTruthy();
|
|
select({ parent: 'G2', period: '2025-S2' });
|
|
expect(fixture.nativeElement.querySelector('.selection-status')).toBe(status);
|
|
expect(status.textContent).toContain('Selección activa');
|
|
expect(status.getAttribute('aria-label')).toContain('denominador de la distribución completa');
|
|
expect(fixture.nativeElement.querySelectorAll('.distribution-note')).toHaveLength(0);
|
|
expect(plot.style.getPropertyValue('--plot-height')).toBe(height);
|
|
select({});
|
|
expect(status.textContent).toContain('Distribución completa');
|
|
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(plot);
|
|
http.expectNone(() => true);
|
|
});
|
|
it('el estado compacto general no describe una distribución estratificada ni oculta su error', () => {
|
|
fixture.componentRef.setInput('indicador', { ...item, filtros: [
|
|
{ estrato: 'grupo_edad', etiqueta: 'Edad', valores: [{ valor: 'adulto', etiqueta: 'Adulto' }] },
|
|
] });
|
|
load(); select({ parent: 'G2', period: '2025-S2' });
|
|
panel().chooseStratified(); request().flush({}, { status: 500, statusText: 'Failure' }); fixture.detectChanges();
|
|
expect(fixture.nativeElement.querySelector('.selection-status')).toBeNull();
|
|
expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy();
|
|
expect(panel().result().status).toBe('error');
|
|
http.expectNone(() => true);
|
|
});
|
|
it('una selección recibida mientras carga se aplica al terminar sin otro GET', () => {
|
|
fixture.detectChanges(); const pending = request(); select({ parent: 'G2', period: '2025-S2' });
|
|
pending.flush(c2Fixture()); fixture.detectChanges(); expect(displayed().data[0]['y']).toEqual(['B', 'C']); http.expectNone(() => true);
|
|
});
|
|
it('ancho y perfil conservan selección y notas desde el original', () => {
|
|
load(); select({ parent: 'G2', period: '2025-S2' }); panel().updatePlotWidth(320);
|
|
fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges();
|
|
expect(displayed().data[0]['y']).toEqual(['B', 'C']); expect(panel().result().footnotes).toEqual(c2Fixture().notas);
|
|
select({}); expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true);
|
|
});
|
|
it.each(['unknown', 'wrong-parent', 'wrong-period', 'missing-period'])('%s restaura la presentación completa', kind => {
|
|
load(); const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' });
|
|
select({ parent: kind === 'unknown' ? 'desconocido' : kind === 'wrong-parent' ? 'G1' : 'G2', category: 'B', period: kind === 'missing-period' ? undefined : kind === 'wrong-period' ? '2026-S1' : '2025-S2' });
|
|
expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true);
|
|
});
|
|
it.each(['null', 'suppressed', 'simple'])('%s mantiene la figura completa sin nuevas peticiones', kind => {
|
|
const data = c2Fixture();
|
|
if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(data['categorias'] as Record<string, Record<string, unknown>>).forEach(c => c['grupo'] = null); }
|
|
else { data.filas[0]['n'] = null; if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; }
|
|
fixture.detectChanges(); request().flush(data);
|
|
if (kind !== 'simple') http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ type: 'bar', orientation: 'h', name: '2025-S2', x: [null, 3, 1], y: ['A', 'B', 'C'] }], layout: {} });
|
|
const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' });
|
|
expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true);
|
|
});
|
|
it('un cambio de filtro invalida el periodo anterior aunque conserve las mismas etiquetas', () => {
|
|
load(); select({ parent: 'G2', category: 'B', period: '2025-S2' });
|
|
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges();
|
|
expect(panel().generalSelectionContext).toBeUndefined();
|
|
const data = c2Fixture(); data.periodos = ['2026-S1']; data.filas.forEach(r => r['periodo'] = '2026-S1'); request().flush(data);
|
|
expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true);
|
|
});
|
|
it('la dona hermana aporta el periodo, navegar restaura todas las series y no cambia el filtro global', () => {
|
|
const periods = ['2025-S2', '2025-S1'], data = c2Fixture();
|
|
data.periodos = periods; data.filas.push(...data.filas.map(r => ({ ...r, periodo: periods[1], n: Number(r['n']) * 2 })));
|
|
const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tipoPeriodo: 'semestre', tema: 'claro', periodos: [periods[0]] };
|
|
const single = c2Figure(c2Fixture(), selection); if (single.status !== 'supported') throw new Error(single.reason);
|
|
const original: PlotlyFigure = { data: [single.figure.data[0], { ...structuredClone(single.figure.data[0]), name: periods[1], x: [12, 6, 2], text: ['60%', '30%', '10%'] }], layout: single.figure.layout };
|
|
delete original.layout['meta'];
|
|
fixture.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } });
|
|
fixture.detectChanges(); request().flush(data); http.expectOne(r => r.url.includes('/figuras/')).flush(original); fixture.detectChanges();
|
|
const full = structuredClone(displayed()), donut = TestBed.createComponent(IndicadorFigurePanel);
|
|
for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied: panel().applied })) donut.componentRef.setInput(k, v);
|
|
donut.componentInstance.hierarchySelected.subscribe(s => fixture.componentRef.setInput('localSelection', s));
|
|
donut.detectChanges(); http.expectNone(() => true);
|
|
const card = () => donut.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
|
|
card().expandParent('G2'); fixture.detectChanges(); expect(displayed().data).toHaveLength(1); expect(displayed().data[0]['name']).toBe(periods[0]);
|
|
donut.componentInstance.changeDonutPeriod(1); donut.detectChanges(); fixture.detectChanges();
|
|
expect(displayed()).toEqual(full); expect(donut.componentInstance.donutPeriodIndex).toBe(1);
|
|
card().expandParent('G2'); card().selectCategory('B'); fixture.detectChanges();
|
|
expect(displayed().data[0]).toMatchObject({ name: periods[1], x: [6], y: ['B'], text: ['30%'] });
|
|
expect(panel().applied.selection).toEqual({ mode: 'explicit', periodos: periods }); expect(panel().result().figure).toEqual(original);
|
|
card().returnToParents(); fixture.detectChanges(); expect(displayed()).toEqual(full);
|
|
http.expectNone(() => true); donut.destroy();
|
|
});
|
|
});
|