Files
WebApp/src/app/paciente/tea-patient.spec.ts
T

277 lines
9.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Component, input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import type { Observation } from 'fhir/r4';
import { describe, expect, it, vi } from 'vitest';
import { EXT, Fhir } from '../fhir';
import { Paciente } from './paciente';
import { loadTeaPatient, Metric, Pair } from './tea-data';
import { ageNorm, forest, headMap, probabilityCurve, zBars } from './tea-figures';
import { TeaRecord, TeaSection } from './tea-patient';
import { recordSections, teaPdfContent, teaPdfName } from './tea-sections';
const metric: Metric = {
key: 'spindles_n2',
title: 'Husos N2',
value: 1.7,
unit: undefined,
model: 'tea.eeg-spindles-n2/1',
z: 0.3,
outside: 0,
sites: [
{ kind: 'zone', name: 'central', z: 2.4, outside: 1 },
{ kind: 'electrode', name: 'O1', z: -1.2, outside: 0 },
],
};
const pair: Pair = {
key: 'spindles|central|CSS',
title: 'Husos N2 · Central · CSS',
headline: true,
altered: true,
z: 2.4,
odds: 3,
low: 1.2,
high: 4.5,
probability: 0.7,
reference: 0.2,
};
const ados: Observation = {
resourceType: 'Observation',
id: 'ados2-child-2025-11-22',
status: 'final',
code: { coding: [{ code: 'ados2' }] },
effectiveDateTime: '2025-11-22',
valueInteger: 0,
component: [
{ code: { coding: [{ code: 'ados2.module' }] }, valueCodeableConcept: { text: 'Módulo 1' } },
{
code: { coding: [{ code: 'ados2.pointing' }, { code: 'A-7' }], text: 'Señalar' },
extension: [
{ url: EXT + 'ados2-domain', valueCoding: { display: 'Afectación social (AS)' } },
{ url: EXT + 'ados2-subdomain', valueCoding: { display: 'Comunicación' } },
],
valueQuantity: { value: 0 },
},
{
code: {
coding: [{ code: 'ados2.intonation' }, { code: 'A-3' }],
text: 'Entonación de las vocalizaciones o verbalizaciones',
},
extension: [
{
url: EXT + 'ados2-domain',
valueCoding: { display: 'Comportamiento restringido y repetitivo (CRR)' },
},
{
url: EXT + 'ados2-subdomain',
valueCoding: { display: 'Comportamientos restringidos y repetitivos' },
},
],
valueQuantity: { value: 2 },
},
{ code: { coding: [{ code: 'ados2.response_to_name' }], text: 'Respuesta al nombre' } },
],
};
const record = {
patient: {
resourceType: 'Patient' as const,
id: 'child',
name: [{ text: 'Paciente de prueba' }],
},
timeline: [['2025-11-22', 'ADOS-2', '—']],
ados: [ados],
studies: [],
riskStudy: undefined,
pairs: [pair],
};
describe('Figuras del paciente TEA', () => {
it('interpola los sitios puntuados y dibuja los electrodos y el contorno', () => {
const figure = headMap(metric.sites);
expect(figure.data[0]).toMatchObject({ type: 'contour' });
const grid = (figure.data[0] as { z?: unknown }).z as (number | null)[][];
expect(grid[20][20]).toBeCloseTo(2.4);
expect(grid[0][0]).toBeNull();
expect(figure.data[1]).toMatchObject({
mode: 'text+markers',
text: expect.arrayContaining(['O1', 'Cz']),
});
expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'circle' });
});
it('dibuja los centiles del campeón y el valor observado a la edad del paciente', () => {
const figure = ageNorm(
[
{ age_months: 20, p5: 0, median: 1, p95: 2 },
{ age_months: 21, p5: 0.2, median: 1.2, p95: 2.2 },
],
metric,
20.5,
);
expect(figure.data[0]).toMatchObject({ fill: 'toself', y: [2, 2.2, 0.2, 0] });
expect(figure.data[2]).toMatchObject({ mode: 'markers', x: [20.5], y: [1.7] });
});
it('usa escala logarítmica y conserva solo zonas alteradas al activar el filtro', () => {
const pairs = [pair, { ...pair, title: 'Zona normal', altered: false, odds: 2 }];
expect(forest(pairs, false).data[0].x).toEqual([3, 2]);
const filtered = forest(pairs, true);
expect(filtered.layout?.xaxis?.type).toBe('log');
expect(filtered.data[0]).toMatchObject({
x: [3],
error_x: { array: [1.5], arrayminus: [1.8] },
});
});
it('marca la banda de z entre −2 y 2', () => {
const figure = zBars({
id: 'eeg-1',
date: '2025-11-22',
age: 20.5,
checks: [],
summary: [],
metrics: [metric],
});
expect(figure.data[0]).toMatchObject({
x: [0.3, 2.4],
y: ['Husos N2 · Global', 'Husos N2 · Central'],
});
expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'rect', x0: -2, x1: 2 });
});
it('dibuja solo los puntos de paciente y referencia cuando faltan parámetros', () => {
expect(probabilityCurve(pair).data).toMatchObject([
{ mode: 'markers', x: [2.4], y: [70] },
{ mode: 'markers', x: [0], y: [20] },
]);
});
});
describe('Expediente TEA', () => {
it('muestra solo los ítems del módulo con dominio, subdominio, código y título', async () => {
const fixture = TestBed.createComponent(TeaSection);
fixture.componentRef.setInput(
'section',
recordSections(record, new Map()).find((section) => section.title === 'ADOS-2'),
);
await fixture.whenStable();
const rows = fixture.nativeElement.querySelectorAll('tbody tr');
expect(rows).toHaveLength(2);
const cells = Array.from(rows[0].cells, (c: HTMLTableCellElement) => c.textContent?.trim());
expect(cells).toEqual(['Afectación social (AS)', 'Comunicación', 'A-7', 'Señalar', '0']);
expect(rows[1].cells[2].textContent.trim()).toBe('A-3');
});
it('exporta las secciones, tablas y figuras con un nombre sin identificador', async () => {
const table = recordSections(record, new Map());
const sections = [
...table,
{
title: 'Normas',
blocks: [{ chart: { title: 'Mapa', figure: headMap(metric.sites) } }],
},
];
const filename = teaPdfName('seguimiento');
const content = teaPdfContent('Expediente TEA', sections, ['data:image/png;base64,YQ==']);
expect(filename).toMatch(/^tea-seguimiento-\d{4}-\d{2}-\d{2}$/);
expect(content).toEqual(
expect.arrayContaining([
expect.objectContaining({ text: 'Datos' }),
expect.objectContaining({ text: 'Relación con el ADOS-2' }),
expect.objectContaining({
table: expect.objectContaining({
body: expect.arrayContaining([
[
'Comportamiento restringido y repetitivo (CRR)',
'Comportamientos restringidos y repetitivos',
'A-3',
'Entonación de las vocalizaciones o verbalizaciones',
'2',
],
]),
}),
}),
expect.objectContaining({ image: 'data:image/png;base64,YQ==' }),
]),
);
});
it('usa los eventos visibles de la búsqueda y ordena primero el par principal', async () => {
const entry = [
{ resource: record.patient, search: { mode: 'match' } },
{ resource: ados, search: { mode: 'include' } },
{
resource: {
resourceType: 'Observation',
code: { coding: [{ code: 'eeg.lab_record_id' }] },
effectiveDateTime: '2025-11-30',
valueString: 'LAB-01',
},
search: { mode: 'include' },
},
{
resource: {
resourceType: 'RiskAssessment',
prediction: [
{ outcome: { coding: [{ code: 'spikes|occipital|CSS' }] } },
{
outcome: { coding: [{ code: pair.key }] },
extension: [{ url: EXT + 'association-headline', valueBoolean: true }],
},
],
},
search: { mode: 'include' },
},
];
const search = vi.fn(async () => ({ entry }));
const data = await loadTeaPatient({ search } as unknown as Fhir, 'child');
expect(search).toHaveBeenCalledWith('tea', 'Patient', {
_id: 'child',
_revinclude: ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject'],
});
expect(data.timeline[0]).toEqual(['2025-11-30', 'EEG', 'LAB-01']);
expect(data.studies).toHaveLength(0);
expect(data.pairs[0].key).toBe(pair.key);
});
});
@Component({ selector: 'app-tea-record', template: '<h2>Datos</h2><h2>Línea del tiempo</h2>' })
class RecordStub {
readonly id = input.required<string>();
}
describe('Secciones por dominio', () => {
it('elige las secciones TEA y sigue mostrando las secciones de CaCu y CaMa', async () => {
const read = vi.fn(async () => record.patient);
TestBed.configureTestingModule({
providers: [
provideRouter([]),
{ provide: Fhir, useValue: { read, all: async () => [], search: async () => ({}) } },
],
}).overrideComponent(Paciente, {
remove: { imports: [TeaRecord] },
add: { imports: [RecordStub] },
});
const fixture = TestBed.createComponent(Paciente);
fixture.componentRef.setInput('id', 'child');
fixture.componentRef.setInput('domain', 'tea');
await fixture.whenStable();
expect(fixture.nativeElement.querySelector('app-tea-record')?.textContent).toContain(
'Línea del tiempo',
);
expect(read).not.toHaveBeenCalled();
for (const domain of ['cacu', 'cama']) {
fixture.componentRef.setInput('domain', domain);
await fixture.whenStable();
expect(fixture.nativeElement.querySelector('app-tea-record')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Historial médico');
expect(read).toHaveBeenCalledWith(domain, 'Patient', 'child');
}
});
});