Files
WebApp/src/app/features/indicadores/indicadores-cama-fhir.spec.ts
T

341 lines
25 KiB
TypeScript

// What this module covers: CaMa's eight FHIR measures as the page reads them: their ids, catalog entries, category
// metadata, the rows of each contract (C1, C2, C3r) and what the summary's cards and figures make of them, for periods
// with data and for periods that legitimately have none.
// Fixtures (`fixtures/cama_fhir_*.json`): `reportes` are real `GET /cama/fhir/MeasureReport` answers of the local
// installation, cut to three semesters (2021-S1 without units, 2024-S2 and 2025-S2 with them) and two months;
// `measures` is the Measure bundle the WebApi serves from the current dbt definitions; `measures_instalada` is the one
// the installation served before the category metadata existed.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import { cajaDeDatos, categorias, datosDeReportes, FhirIndicadoresService, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
import { c2Figure } from './indicadores-c2-adapter';
import { modelosConteos, parConteos, totalExamenes } from './indicadores-conteos-pareados';
import { CAMA_CONFIRMACION_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
import { datosValidos } from './indicadores.service';
import measuresData from './fixtures/cama_fhir_measures.json';
import installedData from './fixtures/cama_fhir_measures_instalada.json';
import reportsData from './fixtures/cama_fhir_reportes.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const installed = resources(installedData as unknown as Bundle, 'Measure') as Measure[];
const answers = reportsData.reports as unknown as Record<string, { semestre: Bundle; mes?: Bundle }>;
const measure = (fhirId: string, from = measures) => from.find(m => m.id === fhirId)!;
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start: string) =>
(resources(answers[fhirId][tipo]!, 'MeasureReport') as Report[]).filter(r => r.period?.start === start);
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', from = measures): IndicadorDatos {
return datosValidos(datosDeReportes(measure(fhirId, from), reportsOf(fhirId, tipo, start), tipo), indicadorId(fhirId), tipo, [periodo]);
}
const SEMESTRE_VACIO = ['2021-01-01', '2021-S1'] as const;
const SEMESTRE_CON_DATOS = ['2025-07-01', '2025-S2'] as const;
describe('Identificadores de CaMa entre FHIR y la página', () => {
it('cada Measure publicada tiene un id de la página y ninguno se repite', () => {
// Pins down: the explicit table covers the eight measures the WebApi publishes and the page ids stay unique
// (`BIRADS456` is `birads_456`, which no rule derives). Fails if a measure is published without a
// correspondence, or two measures collapse into one page id.
const ids = measures.map(m => indicadorId(m.id!));
expect(ids.sort()).toEqual(['cama_biopsias', 'cama_birads', 'cama_birads_456_mastografia', 'cama_birads_456_paciente',
'cama_birads_cancer_invasor', 'cama_confirmacion_birads45', 'cama_dias_resultado_diagnostico', 'cama_dias_toma_diagnostico',
'cama_eu38a', 'cama_histopatologia_birads', 'cama_tasa_deteccion_histopatologica']);
expect(new Set(ids).size).toBe(measures.length);
expect(measures.every(m => Object.hasOwn(CAMA_MEASURE_IDS, m.id!))).toBe(true);
});
it('el id de una medida de otro dominio sigue la regla general', () => {
// Pins down: only CaMa's table maps CaMa's measures, and TEA's keep `-` to `_` (CaCu has a table of its own, see
// indicadores-cacu-fhir.spec.ts). Fails if CaMa's table captures ids of other domains or the generic rule changes.
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
expect(Object.hasOwn(CAMA_MEASURE_IDS, 'CACU-EU7')).toBe(false);
});
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
// Pins down: the contract, the figures and the period types each CaMa measure publishes: a distribution offers
// the donut and the bars, a duration its box plot, a proportion none (its history is drawn from the data rows).
// Fails if the dbt definitions stop declaring them or the mapper drops them.
const catalog = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
expect(catalog['cama_birads_456_paciente']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'], estratos: [] });
expect(catalog['cama_biopsias']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'] });
expect(catalog['cama_confirmacion_birads45']).toMatchObject({ contrato: 'C1', figuras: [], sentido: 'mayor_mejor' });
expect(catalog['cama_eu38a']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
expect(catalog['cama_dias_toma_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'] });
expect(catalog['cama_birads_cancer_invasor']).toMatchObject({ contrato: 'C2', estratos: ['grupo_edad', 'estadio', 'etapa', 'clasificacion', 'tamano'] });
});
});
describe('Ficha técnica de CaMa', () => {
it('cada medida tiene su propio código y sus poblaciones con la métrica que las cuenta', () => {
// Pins down: the sheet's code is the measure's name without the domain (not `CAMA` for all eight) and each
// population names the dbt metric that counts it. Fails if the sheets of different measures read alike.
const codes = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
expect(new Set(codes).size).toBe(measures.length);
expect(metadatosDeMeasure(measure('CAMA-EU38A')).ficha!.codigo).toBe('EU38A');
expect(metadatosDeMeasure(measure('CAMA-BIRADS456-PACIENTE')).ficha!.codigo).toBe('BIRADS456-PACIENTE');
expect(metadatosDeMeasure(measure('CAMA-CONFIRMACION-BIRADS45')).poblaciones!.map(p => p.grupo)).toEqual(['poblacion', 'denominador', 'numerador']);
});
});
describe('Categorías de las composiciones de CaMa', () => {
it('BI-RADS 4 a 6 declara solo sus subcategorías y BI-RADS completo añade «Sin dato»', () => {
// Pins down: the labels and colours come from the Measure's extensions, in the order of the catalog, and the
// exams' and patients' measures declare the same categories. Fails if the dbt labels drift or one measure loses them.
expect(Object.keys(categorias(measure('CAMA-BIRADS456-PACIENTE')))).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6']);
expect(categorias(measure('CAMA-BIRADS456-MASTOGRAFIA'))).toEqual(categorias(measure('CAMA-BIRADS456-PACIENTE')));
expect(Object.keys(categorias(measure('CAMA-BIRADS')))).toEqual(['B0', 'B1', 'B2', 'B3', 'B4A', 'B4B', 'B4C', 'B5', 'B6', 'SIN_DATO']);
expect(categorias(measure('CAMA-BIRADS'))['B5']).toEqual({ etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null });
expect(Object.keys(categorias(measure('CAMA-BIOPSIAS')))).toEqual(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'SIN_DATO']);
});
it('un BI-RADS 4 sin subcategoría se muestra después de las categorías declaradas y no se pierde', () => {
// Pins down: the real 2025-S2 report counts patients in `B4`, which no Measure declares. The rows add it after the
// declared categories under the Core catalog's caption, and the total is still the report's units. Fails if
// undeclared categories are dropped (the card would show fewer patients than the report counts).
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6', 'B4']);
expect((periodo['categorias'] as Record<string, { etiqueta: string }>)['B4'].etiqueta).toBe('BI-RADS 4 (sin subcategoría)');
const total = periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total).toBe(36);
expect(periodo.filas.map(row => [row['categoria'], row['orden']])).toEqual([['B4A', 0], ['B4B', 1], ['B4C', 2], ['B5', 3], ['B6', 4], ['B4', 5]]);
});
it('una Measure sin metadatos de categoría deja ver las categorías con su código, sin perder unidades', () => {
// Pins down: against the Measure the installation served before the labels existed (no category extensions),
// every counted category is still listed (by its code) and the figure still draws the whole partition. Fails if a
// Measure without metadata makes the distribution empty or undercounts it.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS, 'semestre', installed);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4', 'B5', 'B6']);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(36);
});
});
describe('Composiciones (C2): BI-RADS y biopsias', () => {
it.each(['CAMA-BIRADS456-PACIENTE', 'CAMA-BIRADS456-MASTOGRAFIA', 'CAMA-BIRADS', 'CAMA-BIOPSIAS'])('%s se dibuja como dona y como barras con el total de sus unidades', fhirId => {
// Pins down: for a period with units, both published figures are supported and the total equals the report's
// `initial-population`. Fails if a category, a label or the unit total is lost between the report and the figure.
const periodo = datos(fhirId, ...SEMESTRE_CON_DATOS);
const units = reportsOf(fhirId, 'semestre', SEMESTRE_CON_DATOS[0])[0].group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
const result = c2Figure(periodo, { dominio: 'cama', indicador: indicadorId(fhirId), figura, tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(`${fhirId} ${figura}: ${result.reason}`);
expect(result.model.total).toBe(units);
expect(result.model.total).toBeGreaterThan(0);
}
});
it('todas las composiciones de CaMa de los reportes reales suman las unidades de su periodo', () => {
// Pins down: for every C2 measure and every real period in the fixtures (semesters and months), the categories the
// mapper lists add up to the report's units, so none is dropped. Fails if a report counts a category the rows lose.
// The three measures of L3 have their own fixture (`indicadores-cama-l3.spec.ts`).
for (const m of measures.filter(item => indicadorDeMeasure(item).contrato === 'C2' && Object.hasOwn(answers, item.id!))) {
for (const tipo of ['semestre', 'mes'] as const) {
const bundle = answers[m.id!][tipo];
if (!bundle) continue;
const reports = resources(bundle, 'MeasureReport') as Report[];
const rows = datosDeReportes(m, reports, tipo).filas;
for (const report of reports) {
const units = report.group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
const label = report.period!.start;
const total = rows.filter(row => row['periodo'] === (tipo === 'mes' ? label.slice(0, 7) : label.slice(0, 4) + (label.slice(5, 7) < '07' ? '-S1' : '-S2'))).reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total, `${m.id} ${label}`).toBe(units);
}
}
}
});
it('un periodo sin unidades da una distribución vacía, no un error', () => {
// Pins down: a semester without mammograms (legitimate absence of data) is a supported figure with the
// «conteos en cero» message and every category at zero. Fails if an empty period turns into an unsupported figure.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_VACIO);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2021-S1'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(0);
expect(result.emptyMessage).toContain('cero');
expect(periodo.filas.every(row => row['n'] === 0)).toBe(true);
});
it('la tarjeta de pacientes BI-RADS 4, 5 y 6 suma las categorías del periodo', () => {
// Pins down: the opportunity card reads the patients' distribution: its value is the sum of the categories
// (including the undeclared B4) and the card says «Disponible». Fails if the card still sees the catalog without B4.
const result = kpiResult(datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS), KPI_BY_DOMAIN.cama[0], 'cama', apply('2025-S2'));
expect(result).toMatchObject({ state: 'Disponible', value: 36 });
expect(Object.values(result.categorias!).reduce((a, b) => a + b, 0)).toBe(36);
});
it('un mes con datos se lee igual que un semestre', () => {
// Pins down: the monthly search answers by `periodo` labels like `2025-12`, and the rows carry that label. Fails
// if the month's period is read as a semester or the categories are lost.
const periodo = datos('CAMA-BIRADS456-PACIENTE', '2025-12-01', '2025-12', 'mes');
expect(periodo.tipo_periodo).toBe('mes');
expect(periodo.periodos).toEqual(['2025-12']);
expect(periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0)).toBeGreaterThan(0);
});
it('las biopsias suman por grado histológico con los rótulos del catálogo', () => {
// Pins down: the grades arrive as `BENIGNO`, `CARCINOMA_IN_SITU` and `CARCINOMA_INVASOR` and are drawn with the
// catalog's captions. Fails if a grade loses its caption or is merged into another.
const periodo = datos('CAMA-BIOPSIAS', ...SEMESTRE_CON_DATOS);
const labels = Object.fromEntries(Object.entries(periodo['categorias'] as Record<string, { etiqueta: string }>).map(([k, v]) => [k, v.etiqueta]));
expect(labels).toEqual({ BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', SIN_DATO: 'Sin dato' });
expect(Object.fromEntries(periodo.filas.map(row => [row['categoria'], row['n']]))).toEqual({ BENIGNO: 11, CARCINOMA_IN_SITU: 1, CARCINOMA_INVASOR: 13, SIN_DATO: 0 });
});
});
describe('Proporción (C1): confirmación histopatológica', () => {
it('el grupo principal llega a la página como `total` con numerador, denominador y porcentaje', () => {
// Pins down: the WebApi's `principal` group is the page's `total`, and the score becomes a percentage next to
// its numerator and denominator. Fails if the group keeps its FHIR name (the card would find no rows).
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_CON_DATOS);
expect(periodo['grupos']).toEqual({ total: 'Total' });
expect(periodo.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador: 28, denominador: 37, valor: 75.7, suprimido: 0 })]);
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: '75.7',
info: '28 de 37 mastografías BI-RADS 4 y 5 con reporte de biopsia.' });
});
it('un periodo sin mastografías de sospecha no muestra un porcentaje', () => {
// Pins down: denominator zero and no score is «Sin valor disponible», never 0 %. Fails if an empty period is
// drawn as a measured zero.
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 0, valor: null });
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
});
describe('Duraciones (C3r): tiempos de CaMa', () => {
it('toma a resultado da mediana, cuartiles y número de mastografías', () => {
// Pins down: median 8 days with Q1 4 and Q3 12 over 101 mammograms for 2025-S2, and the card shows them. Fails if the
// quartiles or the observation count stop coming from the report's extensions and populations.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ grupo: 'TOTAL', n: 101, mediana: 8, q1: 4, q3: 12, n_sin_evento: 0, unidad: 'dias' });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 8,
info: '101 mastografías; Q1 a Q3: 4 a 12 días.' });
});
it('tamizaje a diagnóstico separa las mastografías medidas de las que no tienen diagnóstico', () => {
// Pins down: 55 measured and 43 without a diagnosis by the cut-off (FHIR's population exclusion), median 60 days.
// Fails if the unmeasured units are counted as observations or lost.
const periodo = datos('CAMA-DIAS-TOMA-DIAGNOSTICO', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ n: 55, n_sin_evento: 43, mediana: 60, q1: 41.5, q3: 131.5 });
expect(kpiResult(periodo, CAMA_TOMA_DIAGNOSTICO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 60 });
});
it('un periodo sin mastografías no tiene mediana', () => {
// Pins down: zero observations and no score is «Sin valor disponible», not a median of 0 days. Fails if an empty
// period is shown as an instant result.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ n: 0, mediana: null });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
it('la caja de cuartiles se dibuja con los semestres que tienen mediana', () => {
// Pins down: the box plot keeps the periods with a median and leaves out the empty one. Fails if an empty
// period becomes a box at zero.
const reports = ['2021-01-01', '2024-07-01', '2025-07-01'].flatMap(start => reportsOf('CAMA-EU38A', 'semestre', start));
const figure = cajaDeDatos(datosValidos(datosDeReportes(measure('CAMA-EU38A'), reports, 'semestre'), 'cama_eu38a', 'semestre'));
expect((figure.data[0] as Record<string, unknown>)['x']).toEqual(['2024-S2', '2025-S2']);
expect((figure.data[0] as Record<string, unknown>)['median']).toEqual([7.5, 8]);
});
});
describe('Servicio FHIR sobre CaMa', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('pide por el id de la página y consulta la medida por su canónico', async () => {
// Pins down: the page asks for `cama_birads_456_paciente` and the WebApi receives the canonical of
// `CAMA-BIRADS456-PACIENTE` with the periods asked for. Fails if the page id is sent as the measure or the table is bypassed.
const service = TestBed.inject(FhirIndicadoresService);
const answer = firstValueFrom(service.datos('cama', 'cama_birads_456_paciente', 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
const request = http.expectOne(r => r.url === '/cama/fhir/MeasureReport');
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE');
expect(request.request.params.get('periodo')).toBe('2025-S2');
request.flush({ ...answers['CAMA-BIRADS456-PACIENTE'].semestre, entry: reportsOf('CAMA-BIRADS456-PACIENTE', 'semestre', '2025-07-01').map(resource => ({ resource })) });
expect((await answer).id).toBe('cama_birads_456_paciente');
});
it('el catálogo de CaMa publica los ocho ids de la página', async () => {
// Pins down: the catalog the page receives lists the correspondence ids, so its filters and cards find them.
// Fails if a measure reaches the page under its FHIR id.
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).catalogo('cama'));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
expect((await answer).map(item => item.id).sort()).toEqual(Object.values(CAMA_MEASURE_IDS).sort());
});
});
describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () => {
const models = (examenes: IndicadorDatos, pacientes: IndicadorDatos) => modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, examenes, pacientes, 'semestre');
it('con datos reales del semestre da los conteos por categoría de ambas medidas', () => {
// Pins down: the page's pair reads the two real C2 answers (units `examen` and `paciente`, version 0.2.0 of the
// patients' measure) and gives the exams by category and the patients by BI-RADS family. Fails if an id, a unit or
// a category of either measure stops matching what the pair checks.
const [model] = models(datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS), datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS));
expect(model.pacientesVerificados).toBe(true);
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
});
it('un periodo sin BI-RADS 4 sin subcategoría cuenta cero en esa categoría y no rompe la tarjeta', () => {
// Pins down: `B4` is published only when some report counts it; a period set without it leaves the card
// working, with zero exams in that category. The reports are the real 2025-S2 ones with the `B4` stratum removed
// and the units reduced by its count. Fails if the card turns «categorías no coinciden» whenever no 4 arrives unqualified.
const without = (fhirId: string) => {
const [report] = reportsOf(fhirId, 'semestre', '2025-07-01');
const group = report.group![0];
const removed = group.stratifier![0].stratum!.find(s => s.value?.coding?.[0].code === 'B4')!.population![0].count!;
const units = group.population!.map(p => p.code?.coding?.[0].code === 'initial-population' ? { ...p, count: p.count! - removed } : p);
const stratifier = [{ ...group.stratifier![0], stratum: group.stratifier![0].stratum!.filter(s => s.value?.coding?.[0].code !== 'B4') }];
const copy = { ...report, group: [{ ...group, population: units, stratifier }] } as Report;
return datosValidos(datosDeReportes(measure(fhirId), [copy], 'semestre'), indicadorId(fhirId), 'semestre', ['2025-S2']);
};
const [model] = models(without('CAMA-BIRADS456-MASTOGRAFIA'), without('CAMA-BIRADS456-PACIENTE'));
expect(model.examenes.find(c => c.id === 'B4')!.n).toBe(0);
expect(model.filas.map(f => f.examenes)).toEqual([0, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
});
});
describe('Conteos publicados de CaMa en la ruta FHIR', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
function pedir(id: string, fhirId: string) {
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).datos('cama', id, 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) });
return answer;
}
it('las mastografías llegan a la tarjeta con los conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS);
const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA');
expect(mostrado.filas).toEqual(publicado.filas);
const pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre');
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
});
it('los pacientes conservan sus conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE');
expect(pacientes.filas).toEqual(publicado.filas);
});
});