209 lines
13 KiB
TypeScript
209 lines
13 KiB
TypeScript
import { TestBed } from '@angular/core/testing';
|
|
import { provideHttpClient } from '@angular/common/http';
|
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
|
import { Dominio } from './indicadores.models';
|
|
import { syntheticCatalogs, syntheticFigures } from './indicadores.synthetic-fixtures';
|
|
import { IndicadoresService } from './indicadores.service';
|
|
|
|
describe('IndicadoresService HTTP', () => {
|
|
let service: IndicadoresService;
|
|
let http: HttpTestingController;
|
|
beforeEach(() => {
|
|
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
|
service = TestBed.inject(IndicadoresService);
|
|
http = TestBed.inject(HttpTestingController);
|
|
});
|
|
afterEach(() => http.verify());
|
|
|
|
it('acepta metadatos de figura y conserva payloads anteriores sin figuras_detalle', () => {
|
|
let legacy: unknown, nullDetails: unknown, current: unknown;
|
|
service.metadatos('cacu', 'old').subscribe(value => legacy = value);
|
|
http.expectOne('/cacu/indicadores/old/metadatos').flush({ descripcion: 'Anterior', ficha: null, referencias: null, poblaciones: null });
|
|
service.metadatos('cacu', 'empty').subscribe(value => nullDetails = value);
|
|
http.expectOne('/cacu/indicadores/empty/metadatos').flush({ figuras_detalle: null });
|
|
service.metadatos('cacu', 'new').subscribe(value => current = value);
|
|
http.expectOne('/cacu/indicadores/new/metadatos').flush({ figuras_detalle: [
|
|
{ figura: 'fig_a', descripcion: null, como_leer: ['Una instrucción.', 'Otra instrucción.'] },
|
|
{ figura: 'fig_b', descripcion: 'Descripción sin instrucciones.', como_leer: [] },
|
|
{ figura: 'fig_c', descripcion: null, como_leer: null },
|
|
] });
|
|
expect(legacy).toMatchObject({ descripcion: 'Anterior' });
|
|
expect(nullDetails).toMatchObject({ figuras_detalle: null });
|
|
expect(current).toMatchObject({ figuras_detalle: [
|
|
{ figura: 'fig_a', como_leer: ['Una instrucción.', 'Otra instrucción.'] },
|
|
{ figura: 'fig_b', descripcion: 'Descripción sin instrucciones.', como_leer: [] },
|
|
{ figura: 'fig_c', como_leer: null },
|
|
] });
|
|
});
|
|
it.each([
|
|
{ figuras_detalle: 'incorrecto' },
|
|
{ figuras_detalle: [{ figura: '', descripcion: null, como_leer: [] }] },
|
|
{ figuras_detalle: [{ figura: 'fig', descripcion: null, como_leer: [] }, { figura: 'fig', descripcion: null, como_leer: ['ambiguo'] }] },
|
|
{ figuras_detalle: [{ figura: 'fig', descripcion: 1, como_leer: [] }] },
|
|
{ figuras_detalle: [{ figura: 'fig', descripcion: null, como_leer: ['válida', 1] }] },
|
|
])('rechaza elementos de figuras_detalle mal formados $figuras_detalle', payload => {
|
|
let error: unknown;
|
|
service.metadatos('cacu', 'i').subscribe({ error: value => error = value });
|
|
http.expectOne('/cacu/indicadores/i/metadatos').flush(payload);
|
|
expect(error).toBeInstanceOf(Error);
|
|
});
|
|
|
|
it('ignora parametros: ni los valida ni bloquea los metadatos aunque vengan mal formados', () => {
|
|
let value: unknown;
|
|
service.metadatos('cacu', 'p').subscribe(v => value = v);
|
|
http.expectOne('/cacu/indicadores/p/metadatos').flush({ descripcion: 'Descripción', parametros: 'incorrecto' });
|
|
expect(value).toMatchObject({ descripcion: 'Descripción' });
|
|
});
|
|
|
|
it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => {
|
|
service.catalogo(dominio).subscribe(items => {
|
|
expect(items).toEqual(syntheticCatalogs[dominio]);
|
|
expect(items.length).toBe(dominio === 'tea' ? 18 : 1);
|
|
expect(items[0].tipos_periodo).toEqual(dominio === 'tea' ? ['semestre'] : ['semestre', 'mes']);
|
|
});
|
|
http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]);
|
|
});
|
|
it.each(['tea', 'cacu', 'cama'] as const)('usa la URL de figura del dominio %s', dominio => {
|
|
service.figura({ dominio, indicador: 'i', figura: 'f', tema: 'oscuro', tipoPeriodo: dominio === 'tea' ? 'semestre' : 'mes', periodos: [dominio === 'tea' ? '2025-S1' : '2025-01'] }).subscribe();
|
|
const req = http.expectOne(r => r.url === `/${dominio}/indicadores/i/figuras/f`);
|
|
expect(req.request.params.get('periodos')).toBe(dominio === 'tea' ? '2025-S1' : '2025-01');
|
|
req.flush({ data: [], layout: {} });
|
|
});
|
|
it('rechaza dominios arbitrarios y periodos mezclados antes de HTTP', () => {
|
|
expect(() => service.catalogo('otro' as Dominio)).toThrow('Dominio no permitido');
|
|
expect(() => service.figura({ dominio: '../otro' as Dominio, indicador: 'i', figura: 'f', tema: 'claro' })).toThrow();
|
|
for (const periodos of [['2025-01', '2025-S1'], ['2025-13'], ['2025-00']]) {
|
|
expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow();
|
|
}
|
|
http.expectNone(() => true);
|
|
});
|
|
it.each([{ tipos_periodo: undefined }, { tipos_periodo: [] }, { tipos_periodo: ['anual'] }, { tipos_periodo: ['mes', 'mes'] }])('rechaza tipos de periodo inválidos $tipos_periodo', ({ tipos_periodo }) => {
|
|
let error: unknown;
|
|
service.catalogo('cacu').subscribe({ error: value => error = value });
|
|
http.expectOne('/cacu/indicadores').flush([{ ...syntheticCatalogs.cacu[0], tipos_periodo }]);
|
|
expect(error).toBeInstanceOf(Error);
|
|
});
|
|
it.each(syntheticFigures)('conserva el JSON sintético $name con arrays, nulos, anotaciones y bdata', ({ figure }) => {
|
|
service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe(value => expect(value).toEqual(figure));
|
|
http.expectOne(r => r.url.includes('/figuras/')).flush(figure);
|
|
});
|
|
it('consume un arreglo directo sin hardcodear catálogo', () => {
|
|
const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }];
|
|
let actual: unknown;
|
|
service.catalogo().subscribe(value => actual = value);
|
|
http.expectOne('/tea/indicadores').flush(data);
|
|
expect(actual).toEqual(data);
|
|
});
|
|
it('acepta catálogo vacío y rechaza envelope inesperado', () => {
|
|
service.catalogo().subscribe(value => expect(value).toEqual([]));
|
|
http.expectOne('/tea/indicadores').flush([]);
|
|
let error: unknown;
|
|
service.catalogo().subscribe({ error: value => error = value });
|
|
http.expectOne('/tea/indicadores').flush({ items: [] });
|
|
expect(error).toBeInstanceOf(Error);
|
|
});
|
|
it('codifica segmentos y omite periodos en Todos', () => {
|
|
service.figura({ indicador: 'a/b ü', figura: 'f?#', tema: 'claro' }).subscribe();
|
|
const request = http.expectOne(req => req.url === '/tea/indicadores/a%2Fb%20%C3%BC/figuras/f%3F%23');
|
|
expect(request.request.method).toBe('GET');
|
|
expect(request.request.params.get('tema')).toBe('claro');
|
|
expect(request.request.params.has('periodos')).toBe(false);
|
|
request.flush({ data: [], layout: {} });
|
|
});
|
|
it('envía semestres y conserva atributos desconocidos, nulos y notas', () => {
|
|
const figure = { data: [{ y: [null, 0], customdata: [null] }], layout: { annotations: [{ text: 'Uso exclusivo de investigación' }] }, extension: { future: true }, frames: [] };
|
|
service.figura({ indicador: 'i', figura: 'f', tema: 'oscuro', periodos: ['2025-S1', '2025-S2'] })
|
|
.subscribe(value => expect(value).toEqual(figure));
|
|
const request = http.expectOne(req => req.url.endsWith('/i/figuras/f'));
|
|
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
|
expect(request.request.params.get('tema')).toBe('oscuro');
|
|
request.flush(figure);
|
|
});
|
|
it('rechaza una figura estructuralmente inválida', () => {
|
|
let error: unknown;
|
|
service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe({ error: value => error = value });
|
|
http.expectOne(req => req.url.endsWith('/i/figuras/f')).flush({ data: null, layout: {} });
|
|
expect(error).toBeInstanceOf(Error);
|
|
});
|
|
});
|
|
|
|
describe('UX-04 validación defensiva HTTP', () => {
|
|
it('bloquea explícitos vacíos antes de construir una petición', () => {
|
|
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
|
const service = TestBed.inject(IndicadoresService);
|
|
const http = TestBed.inject(HttpTestingController);
|
|
expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos: [] })).toThrow('Selección explícita vacía');
|
|
for (const periodos of [['0000-S1'], ['0000-01'], ['10000-01']]) {
|
|
expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow();
|
|
}
|
|
http.expectNone(() => true); http.verify();
|
|
});
|
|
});
|
|
|
|
describe('contrato datos exclusivo de KPI', () => {
|
|
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
|
|
it('conserva los conteos, totales y celdas suprimidas que publica WebApi para mastografías de CaMa', () => {
|
|
const http = TestBed.inject(HttpTestingController);
|
|
const payload = {
|
|
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'],
|
|
filas: [
|
|
{ periodo: '2025-S1', categoria: 'BIRADS_4', n: 15, suprimido: 0 },
|
|
{ periodo: '2025-S1', categoria: 'BIRADS_5', n: 0, suprimido: 0 },
|
|
{ periodo: '2025-S2', categoria: 'BIRADS_4', n: null, suprimido: 1 },
|
|
],
|
|
totales_estrato: [{ periodo: '2025-S1', estrato: 'BIRADS_4', n: 15, suprimido: 0 }],
|
|
};
|
|
let result: unknown;
|
|
TestBed.inject(IndicadoresService).datos('cama', payload.id, 'semestre', payload.periodos).subscribe(value => result = value);
|
|
http.expectOne(req => req.url === `/cama/indicadores/${payload.id}/datos`).flush(payload);
|
|
expect(result).toEqual(payload);
|
|
http.verify();
|
|
});
|
|
it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => {
|
|
const http = TestBed.inject(HttpTestingController); let result: unknown;
|
|
TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v);
|
|
const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos');
|
|
expect(req.request.params.keys()).toEqual(['periodos']); expect(req.request.params.get('periodos')).toBe('2025-01');
|
|
const payload = { id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'mes', periodos: ['2025-01'], filas: [{ periodo: '2025-01', n: null, suprimido: 1 }], notas: ['Nota'] };
|
|
req.flush(payload); expect(result).toEqual(payload); http.verify();
|
|
});
|
|
it('Todos omite periodos y rechaza respuesta de otro indicador', () => {
|
|
const http = TestBed.inject(HttpTestingController); let error: unknown;
|
|
TestBed.inject(IndicadoresService).datos('cama', 'cama_eu38a', 'semestre').subscribe({ error: e => error = e });
|
|
const req = http.expectOne('/cama/indicadores/cama_eu38a/datos'); expect(req.request.params.keys()).toEqual([]);
|
|
req.flush({ id: 'otro', contrato: 'C3r', tipo_periodo: 'semestre', periodos: [], filas: [] });
|
|
expect(error).toBeInstanceOf(Error); http.verify();
|
|
});
|
|
it('serializa cero, uno, dos y tres filtros en un único parámetro ordenado', () => {
|
|
const http = TestBed.inject(HttpTestingController);
|
|
const service = TestBed.inject(IndicadoresService);
|
|
const comprobar = (filtros: readonly string[]) => {
|
|
service.datos('cacu', 'cacu_eu7', 'mes', ['2025-01'], {
|
|
estrato: 'grupo_edad', filtros,
|
|
}).subscribe();
|
|
const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos');
|
|
expect(req.request.params.getAll('filtro')).toEqual(filtros.length ? [filtros.join(',')] : null);
|
|
expect(req.request.params.getAll('filtro')?.length ?? 0).toBe(filtros.length ? 1 : 0);
|
|
expect(req.request.params.get('periodos')).toBe('2025-01');
|
|
expect(req.request.params.get('estrato')).toBe('grupo_edad');
|
|
req.flush({ id:'cacu_eu7', contrato:'C2', tipo_periodo:'mes', periodos:['2025-01'], filas:[], estrato:'grupo_edad' });
|
|
};
|
|
comprobar([]);
|
|
comprobar(['grupo_edad:35-44']);
|
|
comprobar(['grupo_edad:35-44', 'estatus_seguimiento:VIGILANCIA']);
|
|
comprobar(['grupo_edad:35-44', 'estatus_seguimiento:VIGILANCIA', 'otra_dimension:valor']);
|
|
});
|
|
it('deja que HttpParams codifique caracteres reservados dentro de los pares', () => {
|
|
const http = TestBed.inject(HttpTestingController);
|
|
const service = TestBed.inject(IndicadoresService);
|
|
const pair = 'grupo_edad:35 & más';
|
|
service.datos('cacu', 'cacu_eu7', 'mes', undefined, { filtros:[pair] }).subscribe();
|
|
const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos');
|
|
expect(req.request.params.getAll('filtro')).toEqual([pair]);
|
|
expect(req.request.params.toString()).toContain('filtro=grupo_edad:35%20%26%20m%C3%A1s');
|
|
expect(req.request.params.has('periodos')).toBe(false);
|
|
expect(req.request.params.has('estrato')).toBe(false);
|
|
req.flush({ id:'cacu_eu7', contrato:'C2', tipo_periodo:'mes', periodos:[], filas:[] });
|
|
});
|
|
});
|