96b1cabb5a
The section sat flush against its cards, each card repeated the period, the history selector was taller than the summary, and each CaMa line used a different color. Co-authored-by: Cursor <cursoragent@cursor.com>
358 lines
26 KiB
TypeScript
358 lines
26 KiB
TypeScript
// Covers CaMa's four opportunity cards: their definitions, how each indicator's response becomes a card,
|
|
// which cards are pending while the catalog lacks their indicator, and the page drawing them.
|
|
// Fixtures are synthetic rows shaped like the /cama/indicadores/<id>/datos contract; no card reads a bundled value.
|
|
import { TestBed } from '@angular/core/testing';
|
|
import { provideHttpClient } from '@angular/common/http';
|
|
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
|
import { provideRouter } from '@angular/router';
|
|
import { By } from '@angular/platform-browser';
|
|
import { IndicadoresPage } from './indicadores-page';
|
|
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
|
import { IndicadorKpiCard } from './indicador-kpi-card';
|
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
|
import { emptyAvailability } from './indicadores-periodos';
|
|
import {
|
|
CAMA_CONFIRMACION_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, CAMA_OPORTUNIDAD_KPIS, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI,
|
|
KPI_BY_DOMAIN, KpiDefinition, camaKpiCards, kpiResult,
|
|
} from './indicadores-kpi';
|
|
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
|
import { IndicadorDatos } from './indicadores.models';
|
|
|
|
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
|
const row = { periodo: '2025-S1', estrato: null, suprimido: 0 };
|
|
const datos = (definition: KpiDefinition, filas: Record<string, unknown>[]): IndicadorDatos => ({
|
|
id: definition.id, contrato: definition.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas });
|
|
const c1 = (fields: Record<string, unknown>) => datos(CAMA_TASA_DETECCION_KPI, [{ ...row, grupo: 'total', ...fields }]);
|
|
const c3r = (definition: KpiDefinition, fields: Record<string, unknown>) => datos(definition, [{ ...row, grupo: 'TOTAL', unidad: 'dias', ...fields }]);
|
|
|
|
describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
|
|
it('son cuatro, en este orden, y la primera sigue siendo el ancla del periodo inicial', () => {
|
|
// Fails if a card is dropped or reordered, or if the anchor (KPI_BY_DOMAIN.cama[0]) stops leading.
|
|
expect(CAMA_OPORTUNIDAD_KPIS.map(d => [d.id, d.contrato, d.unit])).toEqual([
|
|
['cama_birads_456_paciente', 'C2', 'pacientes'],
|
|
['cama_tasa_deteccion_histopatologica', 'C1', '%'],
|
|
['cama_eu38a', 'C3r', 'días (mediana)'],
|
|
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
|
|
]);
|
|
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
|
|
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
|
|
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
|
|
});
|
|
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
|
|
// Fails if an indicator the catalog does not publish is queried by default, or if a card the summary retired comes back.
|
|
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
|
|
expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_TASA_DETECCION_KPI);
|
|
expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_RESULTADO_DIAGNOSTICO_KPI);
|
|
expect([CAMA_CONFIRMACION_KPI, CAMA_TOMA_DIAGNOSTICO_KPI].map(d => [d.id, d.contrato])).toEqual([
|
|
['cama_confirmacion_birads45', 'C1'], ['cama_dias_toma_diagnostico', 'C3r'],
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe('Tarjetas de oportunidad de CaMa: valores', () => {
|
|
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
|
|
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
|
|
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
|
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
|
|
});
|
|
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
|
|
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
|
expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0');
|
|
});
|
|
it('un denominador de cero no se presenta como una tasa válida', () => {
|
|
// Fails if the 0/0 response that activated the CaMa card is drawn as a valid 0.0%.
|
|
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 0 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
|
expect(result.state).toBe('Sin valor disponible'); expect(result.value).toBeUndefined();
|
|
});
|
|
it.each([
|
|
['valor nulo', { valor: null, numerador: 0, denominador: 8 }],
|
|
['denominador nulo', { valor: 0, numerador: 0, denominador: null }],
|
|
['denominador ausente', { valor: 0, numerador: 0 }],
|
|
])('la tasa con %s no se convierte en cero', (_name, fields) => {
|
|
// Fails if a missing or incoherent rate is drawn as a value.
|
|
const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
|
expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible');
|
|
});
|
|
it.each([
|
|
['numerador mayor que denominador', { valor: 100, numerador: 9, denominador: 8 }],
|
|
['numerador positivo con denominador cero', { valor: 0, numerador: 1, denominador: 0 }],
|
|
['denominador negativo', { valor: 0, numerador: 0, denominador: -1 }],
|
|
])('los conteos incompatibles (%s) son error de contrato', (_name, fields) => {
|
|
// Fails if structurally impossible counts are collapsed into a legitimate no-value response.
|
|
const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
|
expect(result.state).toBe('Error de contrato'); expect(result.value).toBeUndefined();
|
|
});
|
|
it.each(['tea', 'cacu', 'cama'] as const)('el 0/0 se trata como tasa sin valor para %s', domain => {
|
|
// Fails if the shared C1 result path regresses another domain's zero-denominator semantics.
|
|
const definition = domain === 'cacu'
|
|
? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' }
|
|
: domain === 'cama' ? CAMA_TASA_DETECCION_KPI : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!;
|
|
const group = domain === 'tea' ? 'TOTAL' : 'total';
|
|
const data = { ...c1({ valor: 0, numerador: 0, denominador: 0 }), id: definition.id,
|
|
filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 0 }] };
|
|
const result = kpiResult(data, definition, domain, applied);
|
|
expect(result.state).toBe('Sin valor disponible'); expect(result.value).toBeUndefined();
|
|
});
|
|
it.each(['tea', 'cacu', 'cama'] as const)('el cero con denominador positivo permanece disponible para %s', domain => {
|
|
// Fails if the denominator guard accidentally rejects a real zero rate in any C1 domain.
|
|
const definition = domain === 'cacu'
|
|
? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' }
|
|
: domain === 'cama' ? CAMA_TASA_DETECCION_KPI : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!;
|
|
const group = domain === 'tea' ? 'TOTAL' : 'total';
|
|
const data = { ...c1({ valor: 0, numerador: 0, denominador: 8 }), id: definition.id,
|
|
filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 8 }] };
|
|
const result = kpiResult(data, definition, domain, applied);
|
|
expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0');
|
|
});
|
|
it('un dato suprimido por tamaño oculta la cifra en las cuatro tarjetas', () => {
|
|
// Fails if a suppressed row leaks a number.
|
|
const cases: [KpiDefinition, IndicadorDatos][] = [
|
|
[CAMA_OPORTUNIDAD_KPIS[0], datos(CAMA_OPORTUNIDAD_KPIS[0], [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 3, suprimido: 1 }])],
|
|
[CAMA_TASA_DETECCION_KPI, c1({ valor: 10, numerador: 1, denominador: 10, suprimido: 1 })],
|
|
[CAMA_TAMIZAJE_RESULTADO_KPI, c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })],
|
|
[CAMA_RESULTADO_DIAGNOSTICO_KPI, c3r(CAMA_RESULTADO_DIAGNOSTICO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })],
|
|
];
|
|
for (const [definition, data] of cases) {
|
|
const result = kpiResult(data, definition, 'cama', applied);
|
|
expect(result.state).toBe('Dato oculto por tamaño'); expect(result.value).toBeUndefined();
|
|
}
|
|
});
|
|
it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana y cuartiles tal como los publica el C3r', definition => {
|
|
const result = kpiResult(c3r(definition, { mediana: 6.5, n: 40, q1: 3, q3: 11 }), definition, 'cama', applied);
|
|
expect(result).toEqual({ state: 'Disponible', value: 6.5, info: '40 mastografías; Q1 a Q3: 3 a 11 días.' });
|
|
});
|
|
it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana de cero días con observaciones es un valor; sin observaciones no hay valor', definition => {
|
|
// Fails if a median over zero observations is drawn as "0 días", or a true same-day median is dropped.
|
|
expect(kpiResult(c3r(definition, { mediana: 0, n: 5, q1: 0, q3: 2 }), definition, 'cama', applied).value).toBe(0);
|
|
const empty = kpiResult(c3r(definition, { mediana: 0, n: 0, q1: 0, q3: 0 }), definition, 'cama', applied);
|
|
expect(empty.value).toBeUndefined(); expect(empty.state).toBe('Sin valor disponible');
|
|
});
|
|
it('los cuartiles inconsistentes o la unidad ajena no producen cifra', () => {
|
|
const bad = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 9, n: 5, q1: 3, q3: 6 }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied);
|
|
const unit = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 2, n: 5, q1: 1, q3: 3, unidad: 'horas' }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied);
|
|
expect(bad.value).toBeUndefined(); expect(unit.value).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('Tarjetas de oportunidad de CaMa: cuáles se dibujan', () => {
|
|
const only = (...ids: string[]) => (id: string) => ids.includes(id);
|
|
it('sin ningún indicador de oportunidad publicado no hay tarjetas, ni siquiera pendientes', () => {
|
|
// Fails if "Integración pendiente" is shown while the catalog is empty, loading or failed, or because of other CaMa indicators.
|
|
expect(camaKpiCards(only())).toEqual([]);
|
|
expect(camaKpiCards(only('cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_biopsias'))).toEqual([]);
|
|
expect(camaKpiCards(only('cama_tasa_deteccion_histopatologica')).filter(c => !c.pending).length).toBe(1);
|
|
});
|
|
it('con el catálogo actual del laboratorio hay dos tarjetas vivas y dos pendientes, y nada más', () => {
|
|
// Fails if the confirmation and screening-to-diagnosis cards, retired from the strip, are drawn again.
|
|
const cards = camaKpiCards(only('cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a'));
|
|
expect(cards.map(c => [c.definition.id, c.pending])).toEqual([
|
|
['cama_birads_456_paciente', false], ['cama_tasa_deteccion_histopatologica', true],
|
|
['cama_eu38a', false], ['cama_dias_resultado_diagnostico', true]]);
|
|
});
|
|
it('una tarjeta pendiente pasa a viva cuando el catálogo publica su indicador, sin tocar código', () => {
|
|
const cards = camaKpiCards(only(...CAMA_OPORTUNIDAD_KPIS.map(d => d.id)));
|
|
expect(cards.map(c => c.pending)).toEqual([false, false, false, false]);
|
|
});
|
|
it('un indicador de las tarjetas que el catálogo retira no deja una tarjeta consultable', () => {
|
|
expect(camaKpiCards(only('cama_birads_456_paciente')).map(c => c.pending)).toEqual([false, true, true, true]);
|
|
});
|
|
});
|
|
|
|
describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
|
beforeEach(() => {
|
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
|
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
|
// The initial-period search has its own suites; these tests begin once it has finished.
|
|
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama');
|
|
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
|
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
|
});
|
|
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
|
const catalog = (definitions: KpiDefinition[]) => definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }));
|
|
// What 18080 publishes besides the opportunity indicators: none of them has a card in the strip.
|
|
const otros = (): KpiDefinition[] => [
|
|
{ id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' },
|
|
{ id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
|
{ id: 'cama_biopsias', title: 'Distribución de resultados de biopsia', contrato: 'C2', unit: 'biopsias' },
|
|
{ id: 'cama_birads_456_mastografia', title: 'Porcentaje individual de mastografías', contrato: 'C2', unit: 'mastografías' }];
|
|
const dataFor = (definition: KpiDefinition): IndicadorDatos => {
|
|
if (definition.contrato === 'C2') return datos(definition, [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 5 }]);
|
|
if (definition.contrato === 'C1') return datos(definition, [{ ...row, grupo: 'total', valor: 40, numerador: 2, denominador: 5 }]);
|
|
return c3r(definition, { mediana: 7, n: 5, q1: 3, q3: 9 });
|
|
};
|
|
// The period inventory runs four requests at a time: answer it in waves.
|
|
function inventory() {
|
|
for (let wave = http.match(r => r.url.endsWith('/periodos')); wave.length; wave = http.match(r => r.url.endsWith('/periodos'))) {
|
|
wave.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
|
|
}
|
|
fixture.detectChanges();
|
|
}
|
|
type Served = { listed?: ReturnType<typeof catalog>; answer?: (r: TestRequest, definition: KpiDefinition) => void };
|
|
function load(definitions: KpiDefinition[], served: Served = {}) {
|
|
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
|
http.expectOne('/cama/indicadores').flush(served.listed ?? catalog(definitions));
|
|
inventory();
|
|
// Data requests also go out in waves of four.
|
|
const requested: string[] = [];
|
|
for (let wave = http.match(r => r.url.endsWith('/datos')); wave.length; wave = http.match(r => r.url.endsWith('/datos'))) {
|
|
wave.forEach(r => {
|
|
requested.push(r.request.url);
|
|
const definition = definitions.find(d => r.request.url.endsWith('/' + d.id + '/datos'))!;
|
|
if (served.answer) served.answer(r, definition); else r.flush(dataFor(definition));
|
|
});
|
|
fixture.detectChanges();
|
|
}
|
|
return requested;
|
|
}
|
|
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
|
const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim();
|
|
|
|
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y diagnóstico a tratamiento sin dato ni consulta', () => {
|
|
// Fails if any card without a published measure makes a request or displays a value.
|
|
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
|
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
|
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
|
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
|
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
|
|
expect(cards().map(card => text(card, 'h3'))).toEqual([
|
|
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica',
|
|
'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']);
|
|
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]);
|
|
expect(cards().map(card => text(card, '.kpi-state'))).toEqual([
|
|
'Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
|
expect(cards()[1].textContent).toContain('aún no está publicado');
|
|
expect(cards()[1].textContent).not.toMatch(/\d/);
|
|
expect(cards()[4].textContent).toContain('aún no está publicado');
|
|
expect(cards()[4].textContent).not.toMatch(/\d|días|mediana/);
|
|
});
|
|
it('dibuja los cuatro indicadores publicados y mantiene diagnóstico a tratamiento sin valor', () => {
|
|
// Fails if a published measure is skipped or the placeholder borrows data from another measure.
|
|
const urls = load([...KPI_BY_DOMAIN.cama, CAMA_TASA_DETECCION_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI]);
|
|
expect(cards()).toHaveLength(5);
|
|
expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica'))).toBe(true);
|
|
expect(urls.some(url => url.includes('cama_dias_resultado_diagnostico'))).toBe(true);
|
|
expect(cards().slice(0, 4).map(card => text(card, 'h3'))).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title));
|
|
expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible');
|
|
expect(text(cards()[4], '.value')).toBeUndefined();
|
|
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
|
|
expect(cards()[1].textContent).toContain('2 de 5 biopsias con riesgo a carcinoma.');
|
|
});
|
|
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
|
|
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
|
http.expectOne('/cama/indicadores').flush([]); fixture.detectChanges();
|
|
expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull();
|
|
expect(fixture.nativeElement.textContent).not.toContain('Integración pendiente'); http.expectNone(r => r.url.endsWith('/datos'));
|
|
});
|
|
it('un indicador publicado con otro contrato no se muestra como la tarjeta esperada', () => {
|
|
// Fails if a contract mismatch (C1 served where C3r is expected) is drawn as a median.
|
|
load(KPI_BY_DOMAIN.cama, { listed: catalog(KPI_BY_DOMAIN.cama).map(i => i.id === 'cama_eu38a' ? { ...i, contrato: 'C1' } : i) });
|
|
const panel = fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel)
|
|
.find(p => p.definition.id === 'cama_eu38a')!;
|
|
expect(panel.result().state).toBe('Error de contrato'); expect(panel.result().value).toBeUndefined();
|
|
});
|
|
it('el error de una consulta se muestra en su tarjeta y las demás conservan sus datos', () => {
|
|
load(KPI_BY_DOMAIN.cama, { answer: (r, definition) => definition.id === 'cama_eu38a' ? r.flush('private', { status: 500, statusText: 'Error' }) : r.flush(dataFor(definition)) });
|
|
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
|
|
expect(text(cards()[0], '.value')).toBe('5pacientes');
|
|
expect(fixture.nativeElement.textContent).not.toContain('private');
|
|
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía a interpretación radiológica"]')).not.toBeNull();
|
|
});
|
|
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
|
|
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
|
load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
|
const ids = fixture.componentInstance.searchResults().items.map(item => item.id);
|
|
expect(ids).not.toContain('cama_biopsias');
|
|
expect(ids).toContain('cama_birads_456_mastografia');
|
|
expect(fixture.nativeElement.querySelector('.catalog-grid').textContent).not.toContain('Distribución de resultados de biopsia');
|
|
});
|
|
it('la cabecera de CaMa dice «Cáncer de mama», sin subtítulo superior, y el bloque de filtros queda simplificado', () => {
|
|
load(KPI_BY_DOMAIN.cama);
|
|
const text = fixture.nativeElement.textContent as string;
|
|
expect(fixture.nativeElement.querySelector('#dashboard-title').textContent.trim()).toBe('Cáncer de mama');
|
|
expect(fixture.nativeElement.querySelector('header .domain')).toBeNull();
|
|
expect(text).not.toContain('Cáncer de mama, investigación');
|
|
expect(text).toContain('Explora los indicadores de cáncer de mama.');
|
|
expect(fixture.nativeElement.querySelector('#global-filters-title').textContent.trim()).toBe('Filtros');
|
|
expect(fixture.nativeElement.querySelector('.global-filters .section-description')).toBeNull();
|
|
expect(text).not.toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
|
|
expect(text).not.toContain('Filtro general aplicado');
|
|
expect(text).not.toContain('Existe reporte en al menos un indicador del dominio.');
|
|
});
|
|
it('Disponible queda visualmente oculto y sigue en un único estado accesible en CaMa', () => {
|
|
const card = TestBed.createComponent(IndicadorKpiCard);
|
|
card.componentRef.setInput('title', 'Indicador'); card.componentRef.setInput('state', 'Disponible'); card.detectChanges();
|
|
expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Disponible');
|
|
card.componentRef.setInput('quietWhenAvailable', true); card.detectChanges();
|
|
const status = card.nativeElement.querySelectorAll('[role="status"]');
|
|
expect(status).toHaveLength(1);
|
|
expect(status[0].textContent).toBe('Disponible');
|
|
expect(status[0].classList.contains('visually-hidden')).toBe(true);
|
|
card.componentRef.setInput('state', 'Sin datos del periodo'); card.detectChanges();
|
|
expect(card.nativeElement.querySelectorAll('[role="status"]')).toHaveLength(1);
|
|
expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Sin datos del periodo');
|
|
expect(card.nativeElement.querySelector('.kpi-state').classList.contains('visually-hidden')).toBe(false);
|
|
card.componentRef.setInput('quietWhenAvailable', false); card.componentRef.setInput('state', 'Disponible'); card.detectChanges();
|
|
expect(card.nativeElement.querySelectorAll('[role="status"]')).toHaveLength(1);
|
|
expect(card.nativeElement.querySelector('.kpi-state').classList.contains('visually-hidden')).toBe(false);
|
|
card.destroy();
|
|
});
|
|
});
|
|
|
|
describe('Filtros generales de CaMa: periodo único', () => {
|
|
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorPeriodFilters>>;
|
|
const availability = () => ({ ...emptyAvailability('ready'), options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } });
|
|
function mount(compact: boolean, draft: unknown = { mode: 'explicit', periodos: ['2025-S2'] }, applied: unknown = { mode: 'explicit', periodos: ['2025-S2'] }) {
|
|
TestBed.configureTestingModule({ imports: [IndicadorPeriodFilters] });
|
|
fixture = TestBed.createComponent(IndicadorPeriodFilters);
|
|
fixture.componentRef.setInput('types', ['semestre', 'mes']);
|
|
fixture.componentRef.setInput('compact', compact);
|
|
fixture.componentRef.setInput('availability', availability());
|
|
fixture.componentRef.setInput('state', { tipo: 'semestre', editors: { semestre: { added: [], draft }, mes: { added: [], draft: { mode: 'empty' } } },
|
|
applied: { tipo: 'semestre', selection: applied } });
|
|
fixture.detectChanges();
|
|
return fixture.componentInstance;
|
|
}
|
|
afterEach(() => fixture.destroy());
|
|
const labels = () => [...fixture.nativeElement.querySelectorAll('mat-label')].map(e => (e as HTMLElement).textContent?.trim());
|
|
|
|
it('muestra Intervalo de análisis, Periodo seleccionado y Aplicar en una fila, sin modalidad ni resúmenes de edición', () => {
|
|
// Fails if the multi-period controls or the editing summaries come back to CaMa.
|
|
mount(true);
|
|
expect(fixture.nativeElement.querySelector('.field-label').textContent!.trim()).toBe('Intervalo de análisis');
|
|
expect(labels()).toEqual(['Periodo seleccionado']);
|
|
expect(fixture.nativeElement.querySelector('.fields.compact .apply-button')).not.toBeNull();
|
|
const text = fixture.nativeElement.textContent as string;
|
|
expect(text).not.toContain('Modalidad');
|
|
expect(text).not.toContain('Selección en edición');
|
|
expect(text).not.toContain('Sin cambios pendientes');
|
|
expect(text).not.toContain('Filtro general aplicado');
|
|
expect(text).not.toContain('Existe reporte en al menos un indicador del dominio.');
|
|
});
|
|
it('elegir otro periodo deja un solo periodo en el borrador y avisa que hay cambios sin aplicar', () => {
|
|
// Fails if the control keeps more than one period, or if the pending notice is lost.
|
|
const control = mount(true);
|
|
expect(fixture.nativeElement.textContent).not.toContain('Hay cambios sin aplicar.');
|
|
control.select(['2025-S1']); fixture.componentRef.setInput('state', { ...control.state }); fixture.detectChanges();
|
|
expect(control.state.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
|
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar.');
|
|
let applied = 0; control.apply.subscribe(() => applied++);
|
|
(fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).click();
|
|
expect(applied).toBe(1);
|
|
});
|
|
it('el bloque compacto de CaMa lleva la clase de densidad reducida y los demás dominios no', () => {
|
|
mount(true); expect((fixture.nativeElement as HTMLElement).classList.contains('compacto')).toBe(true);
|
|
fixture.destroy(); TestBed.resetTestingModule();
|
|
mount(false, { mode: 'todos' }, { mode: 'todos' }); expect((fixture.nativeElement as HTMLElement).classList.contains('compacto')).toBe(false);
|
|
});
|
|
it('Aplicar no se puede pulsar sin cambios pendientes', () => {
|
|
mount(true);
|
|
expect((fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).disabled).toBe(true);
|
|
});
|
|
it('sin periodo elegido no hay nada que aplicar', () => {
|
|
const control = mount(true, { mode: 'empty' });
|
|
expect(control.canApply).toBe(false);
|
|
expect(fixture.nativeElement.textContent).toContain('Selecciona un periodo válido para aplicar.');
|
|
});
|
|
});
|