178 lines
11 KiB
TypeScript
178 lines
11 KiB
TypeScript
// Covers Luis's specification of CaMa's record: the risk-factor label built from a summary row (the factors present in at least 95 % and in
|
|
// 50-95 % of the scenario, robust solid and suggestive outlined, grey "none" message), the survival analysis (one menu of scenarios; the
|
|
// one chosen decides the curve and the label at once; it opens on the patient's) and the recurrence analysis (two chained menus, the
|
|
// cohorts never mixed, a horizon for the label with 60 months by default). Fixtures: stubs of `CamaCurvasService` and
|
|
// `CamaRecurrenciaService` with a record like the API answers.
|
|
import { TestBed } from '@angular/core/testing';
|
|
import { of } from 'rxjs';
|
|
import { vi } from 'vitest';
|
|
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
|
|
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
|
|
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
|
|
import { CamaCurvasService, respuestaCurvas } from './cama-curvas.service';
|
|
import { CamaFactoresRiesgo, entradasDe } from './cama-factores-riesgo.component';
|
|
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
|
|
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
|
|
|
const meses = Array.from({ length: 25 }, (_, i) => i);
|
|
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
|
|
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
|
|
const curvas = (escenario: string, n = 245) => ({ modelo: { nombre: 'cama-survival', version: '3' }, curvas: {
|
|
version: 1, escenario, n, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200,
|
|
km: { months: meses, S: decreciente(0.7), low: decreciente(0.6), high: decreciente(0.8) }, km_adjusted: { months: meses, S: decreciente(0.72) },
|
|
weibull: { t: [0, 12, 24], S: [1, 0.85, 0.72] }, weibull_fractional: { t: [0, 12, 24], S: [1, 0.84, 0.71] },
|
|
points: { LR: serie([0.93, 0.85, 0.78]), HBN: serie([0.92, 0.84, 0.77]), COMB: serie([0.925, 0.845, 0.775]) }, etiquetas: {} } });
|
|
const fila = (escenario: string, extra: object = {}) => ({ escenario, riesgo_definitorios: 'Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)', riesgo_mayoritarios: 'HER2=H3 (sugerente, 60%)',
|
|
n_factores_riesgo_incluidos: 3, incluye_factor_riesgo: true, ...extra });
|
|
|
|
const texto = (f: { nativeElement: unknown }) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
|
function plotly() {
|
|
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
|
const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) },
|
|
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
|
|
return { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) };
|
|
}
|
|
function elegir(f: { nativeElement: unknown; detectChanges(): void }, etiqueta: string, valor: string) {
|
|
const select = [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!.querySelector('select')!;
|
|
select.value = valor;
|
|
select.dispatchEvent(new Event('change'));
|
|
f.detectChanges();
|
|
}
|
|
|
|
describe('Factores de riesgo: la etiqueta', () => {
|
|
const montar = (f: object | null) => {
|
|
const fx = TestBed.createComponent(CamaFactoresRiesgo);
|
|
fx.componentRef.setInput('fila', f);
|
|
fx.detectChanges();
|
|
return fx;
|
|
};
|
|
|
|
// Fails if an entry is cut at the wrong place or its strength is read from anything but its own parentheses.
|
|
it('reads the entries of a cell and whether each is robust', () => {
|
|
expect(entradasDe('Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)')).toEqual([
|
|
{ texto: 'Grado=G3 (robusto, 97%)', robusto: true }, { texto: 'Ki67=alto (sugerente, 96%)', robusto: false }]);
|
|
expect(entradasDe('')).toEqual([]);
|
|
});
|
|
|
|
// Fails if the two groups lose their order or a robust factor is not told from a suggestive one.
|
|
it('lists the defining factors, then the majority ones, a robust one solid and a suggestive one outlined', () => {
|
|
const fx = montar(fila('< 45 años'));
|
|
const items = [...(fx.nativeElement as HTMLElement).querySelectorAll('li')];
|
|
|
|
expect(texto(fx)).toContain('Factores de riesgo de este escenario');
|
|
expect(items.map(i => i.textContent!.trim())).toEqual(['Grado=G3 (robusto, 97%)', 'Ki67=alto (sugerente, 96%)', 'HER2=H3 (sugerente, 60%)']);
|
|
expect(items.map(i => i.classList.contains('robust'))).toEqual([true, false, false]);
|
|
});
|
|
|
|
// Fails if a scenario with no factors is shown empty, or with a different message.
|
|
it.each([[null], [fila('X', { incluye_factor_riesgo: false })], [fila('X', { n_factores_riesgo_incluidos: 0 })]])('says there are none (%#)', f => {
|
|
const fx = montar(f);
|
|
|
|
expect(texto(fx)).toContain('Sin factores de riesgo identificados en este escenario.');
|
|
expect((fx.nativeElement as HTMLElement).querySelector('li')).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('Análisis de supervivencia', () => {
|
|
let consulta: ReturnType<typeof vi.fn>;
|
|
beforeEach(() => {
|
|
consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) }));
|
|
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
|
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] });
|
|
});
|
|
afterEach(() => vi.unstubAllGlobals());
|
|
const montar = () => {
|
|
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
|
|
f.componentRef.setInput('pacId', '7');
|
|
f.detectChanges();
|
|
f.detectChanges();
|
|
return f;
|
|
};
|
|
|
|
// Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed.
|
|
it('opens on the patient\'s scenario with the menu the API gave', () => {
|
|
const f = montar();
|
|
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
|
|
|
|
expect(opciones).toEqual(['< 45 años', 'Estadio I']);
|
|
expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
|
|
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
|
|
});
|
|
|
|
// Fails if choosing a scenario changes only the curve or only the label: the selector decides both at once, one scenario at a time.
|
|
it('changes the curve and the label together when another scenario is chosen, and never draws two', () => {
|
|
const f = montar();
|
|
expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row
|
|
|
|
elegir(f, 'Escenario clínico', '< 45 años');
|
|
|
|
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
|
|
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
|
|
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
|
});
|
|
});
|
|
|
|
describe('Análisis de recurrencia', () => {
|
|
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
|
|
it('scales the y axis to the months it draws', () => {
|
|
const largo = { ...figura('metabric', 'Largo'), observado_hasta: 300, months_max: 72,
|
|
km: { months: Array.from({ length: 301 }, (_, i) => i), S: Array.from({ length: 301 }, (_, i) => 1 - i / 400), low: Array.from({ length: 301 }, (_, i) => (i <= 72 ? 0.85 : 0.2)), high: Array.from({ length: 301 }, () => 1) } };
|
|
|
|
expect((figuraRecurrencia(respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios: [largo], resumen: [], predeterminado: null }).escenarios[0]).layout as any).yaxis.range[0]).toBeGreaterThan(0.5);
|
|
});
|
|
|
|
const figura = (cohorte: string, escenario: string) => ({ cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, n: 300, recaidas: 180,
|
|
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
|
|
km: { months: Array.from({ length: 61 }, (_, i) => i), S: Array.from({ length: 61 }, (_, i) => 1 - i / 200), low: Array.from({ length: 61 }, (_, i) => 1 - i / 190), high: Array.from({ length: 61 }, () => 1) },
|
|
weibull: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, weibull_fractional: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, points: { COMB: { S: [0.9, 0.8, 0.7], low: [0.85, 0.75, 0.65], high: [0.95, 0.85, 0.75] } } });
|
|
const resumen = (cohorte: string, escenario: string, h: number) => ({ cohorte, escenario, horizonte_meses: h, riesgo_definitorios: `Marca=${cohorte}-${h} (robusto, 99%)`, riesgo_mayoritarios: '',
|
|
n_factores_riesgo_incluidos: 1, incluye_factor_riesgo: true });
|
|
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
|
|
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
|
|
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
|
|
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
|
|
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
|
|
afterEach(() => vi.unstubAllGlobals());
|
|
const montar = () => {
|
|
const f = TestBed.createComponent(CamaAnalisisRecurrencia);
|
|
f.componentRef.setInput('pacId', '7');
|
|
f.detectChanges();
|
|
f.detectChanges();
|
|
return f;
|
|
};
|
|
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
|
|
.querySelectorAll('option');
|
|
|
|
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
|
|
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
|
|
const f = montar();
|
|
|
|
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
|
|
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
|
|
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
|
|
});
|
|
|
|
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
|
|
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
|
|
const f = montar();
|
|
|
|
elegir(f, 'Cohorte', 'metabric');
|
|
|
|
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
|
|
expect(texto(f)).toContain('Marca=metabric-60');
|
|
expect(texto(f)).not.toContain('scanb');
|
|
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
|
});
|
|
|
|
// Fails if the label ignores the horizon, or does not open on 60 months.
|
|
it('shows the label at the horizon chosen, 60 months by default', () => {
|
|
const f = montar();
|
|
expect((f.nativeElement as HTMLElement).querySelector<HTMLSelectElement>('.horizons select')!.value).toBe('60');
|
|
|
|
elegir(f, 'Horizonte', '12');
|
|
|
|
expect(texto(f)).toContain('Marca=scanb-12');
|
|
expect(texto(f)).not.toContain('Marca=scanb-60');
|
|
});
|
|
});
|