975 lines
39 KiB
TypeScript
975 lines
39 KiB
TypeScript
import { expect, type Locator, type Page, test } from '@playwright/test';
|
||
import { layoutProblems } from './layout';
|
||
|
||
// The individual record of CaCu: the stages inside "Historial médico" and the risk scales.
|
||
// "(simulado)" tests rewrite the API's answers in the browser to cover what the synthetic data
|
||
// do not hold (every stage state, every risk value); they show how the page draws them, not the backend.
|
||
|
||
const EXT = 'https://isssteleon.org/fhir/StructureDefinition/';
|
||
test.beforeEach(async ({ page }) => {
|
||
const form = { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' };
|
||
expect((await page.request.post('/api/auth/login', { form })).status()).toBe(204);
|
||
});
|
||
|
||
/** The record of the first patient of the risk list, as an address. */
|
||
async function firstRecord(page: Page): Promise<{ url: string; sample: string }> {
|
||
await page.goto('/indicadores/cacu');
|
||
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
|
||
const link = page.locator('table.worklist tbody tr a').first();
|
||
await link.waitFor({ timeout: 120_000 });
|
||
const url = (await link.getAttribute('href'))!;
|
||
return { url, sample: new URL(url, 'http://x').searchParams.get('citologia')! };
|
||
}
|
||
const plus = (day: string, days: number) =>
|
||
new Date(Date.parse(day) + days * 86_400_000).toISOString().slice(0, 10);
|
||
|
||
type Route = Partial<
|
||
Record<'report' | 'colposcopy' | 'request' | 'biopsy' | 'diagnosis', number>
|
||
> & {
|
||
link?: 'recorded';
|
||
/** more extensions on the report, as the backend would publish them (stage states and sources) */
|
||
extra?: object[];
|
||
};
|
||
/** The shown cytology's report carries these dates (days after its sample). */
|
||
async function withRoute(page: Page, sample: string, days: Route) {
|
||
await page.route('**/api/cacu/fhir/DiagnosticReport**', async (route) => {
|
||
const response = await route.fetch();
|
||
const body = await response.json();
|
||
for (const { resource: r } of body.entry ?? []) {
|
||
if (r.code?.coding?.[0]?.code !== 'cervical_cytology' || r.effectiveDateTime !== sample)
|
||
continue;
|
||
const names = {
|
||
report: 'report-date',
|
||
colposcopy: 'colposcopy-date',
|
||
request: 'biopsy-request-date',
|
||
biopsy: 'biopsy-date',
|
||
diagnosis: 'diagnosis-date',
|
||
} as const;
|
||
r.extension = (r.extension ?? []).filter(
|
||
(e: any) =>
|
||
!Object.values(names).some((n) => e.url === EXT + n) && e.url !== EXT + 'biopsy-link',
|
||
);
|
||
for (const [key, name] of Object.entries(names)) {
|
||
const d = days[key as keyof typeof names];
|
||
if (d !== undefined) r.extension.push({ url: EXT + name, valueDate: plus(sample, d) });
|
||
}
|
||
if (days.link) r.extension.push({ url: EXT + 'biopsy-link', valueCode: days.link });
|
||
r.extension.push(...(days.extra ?? []));
|
||
}
|
||
await route.fulfill({
|
||
response,
|
||
body: JSON.stringify(body),
|
||
contentType: 'application/fhir+json',
|
||
});
|
||
});
|
||
}
|
||
|
||
type Prediction = [years: number, p: number, low?: number, high?: number];
|
||
const risk = (
|
||
id: string,
|
||
text: string,
|
||
model: string,
|
||
index: string,
|
||
predictions: Prediction[],
|
||
) => ({
|
||
resourceType: 'RiskAssessment',
|
||
id,
|
||
status: 'final',
|
||
method: { text, coding: [{ code: model }] },
|
||
occurrenceDateTime: index,
|
||
prediction: predictions.map(([years, p, low, high]) => ({
|
||
whenRange: { high: { value: years, unit: 'a', code: 'a' } },
|
||
probabilityDecimal: p,
|
||
extension:
|
||
low === undefined
|
||
? []
|
||
: [
|
||
{ url: EXT + 'ic-bajo', valueDecimal: low },
|
||
{ url: EXT + 'ic-alto', valueDecimal: high },
|
||
],
|
||
})),
|
||
});
|
||
/** The patient has these risk assessments. */
|
||
async function withRisks(page: Page, assessments: object[]) {
|
||
await page.route('**/api/cacu/fhir/RiskAssessment**', (route) =>
|
||
route.fulfill({
|
||
contentType: 'application/fhir+json',
|
||
body: JSON.stringify({
|
||
resourceType: 'Bundle',
|
||
type: 'searchset',
|
||
entry: assessments.map((resource) => ({ resource })),
|
||
}),
|
||
}),
|
||
);
|
||
}
|
||
|
||
const historial = (page: Page) =>
|
||
page.locator('mat-card', {
|
||
has: page.locator('mat-card-title', { hasText: 'Historial médico' }),
|
||
});
|
||
const scale = (page: Page, label: string, nth = 0) =>
|
||
page.locator(`.risk-scale[data-scale="${label}"]`).nth(nth);
|
||
const IMMEDIATE = 'Riesgo inmediato (al índice)';
|
||
const FIVE = 'Riesgo a 5 años';
|
||
|
||
async function open(page: Page, url: string) {
|
||
await page.goto(url);
|
||
await expect(historial(page)).toBeVisible({ timeout: 120_000 });
|
||
await expect(page.locator('app-loading')).toHaveCount(0, { timeout: 60_000 });
|
||
}
|
||
/** Where a scale draws its marker, in % of the bar, and the figure it prints. */
|
||
async function drawn(scaleBox: Locator) {
|
||
const marker = scaleBox.locator('.risk-marker');
|
||
return {
|
||
markers: await marker.count(),
|
||
left: (await marker.count())
|
||
? await marker.evaluate((e) => (e as HTMLElement).style.left)
|
||
: undefined,
|
||
value: (await scaleBox.locator('.risk-value').count())
|
||
? (await scaleBox.locator('.risk-value').innerText()).trim()
|
||
: undefined,
|
||
grey: await scaleBox.locator('.risk-plot.unavailable').count(),
|
||
};
|
||
}
|
||
|
||
test('ficha: the five stages are a line of nodes inside "Historial médico", with the export button', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await open(page, url);
|
||
await expect(page.locator('mat-card-title', { hasText: 'Etapas del tamizaje' })).toHaveCount(0);
|
||
const stages = historial(page).locator('[data-section=etapas] app-stages li');
|
||
await expect(stages).toHaveCount(5);
|
||
// one row: the five nodes are level
|
||
const tops = await stages
|
||
.locator('.node')
|
||
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
|
||
expect(new Set(tops).size).toBe(1);
|
||
// each stage says its name, state, day and both intervals, centred
|
||
const first = stages.first();
|
||
await expect(first).toContainText('Toma de muestra');
|
||
await expect(first).toContainText('Registrada');
|
||
await expect(first).toContainText('Desde anterior: —');
|
||
await expect(first).toContainText('Desde toma: 0 días');
|
||
expect(
|
||
await first.locator('.info').evaluate((e) => getComputedStyle(e.parentElement!).textAlign),
|
||
).toBe('center');
|
||
await expect(historial(page)).toContainText('a la fecha de corte');
|
||
await expect(historial(page).getByRole('button', { name: 'Exportar PDF' })).toBeVisible();
|
||
// history and tests keep their tables
|
||
await expect(historial(page).getByRole('table')).toBeVisible();
|
||
await expect(page.locator('mat-card-title', { hasText: 'Pruebas y resultados' })).toBeVisible();
|
||
});
|
||
|
||
test('ficha: the export of the record still downloads its PDF', async ({ page }) => {
|
||
const { url } = await firstRecord(page);
|
||
await open(page, url);
|
||
const saved = page.waitForEvent('download');
|
||
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
|
||
expect((await saved).suggestedFilename()).toBe('expediente-cacu.pdf');
|
||
});
|
||
|
||
test('ficha: with no model both horizons are drawn grey, not available, without a marker', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await open(page, url);
|
||
for (const label of [IMMEDIATE, FIVE]) {
|
||
const box = scale(page, label);
|
||
await expect(box).toContainText('No disponible');
|
||
expect(await drawn(box)).toMatchObject({ markers: 0, grey: 1 });
|
||
await expect(box.locator('.risk-labels span')).toHaveText([
|
||
'0 %',
|
||
'25 %',
|
||
'50 %',
|
||
'75 %',
|
||
'100 %',
|
||
]);
|
||
}
|
||
await expect(
|
||
page.getByText('Divisiones numéricas descriptivas; no representan umbrales clínicos.'),
|
||
).toBeVisible();
|
||
});
|
||
|
||
test('ficha (simulado): every state of a stage, its dates and its intervals', async ({ page }) => {
|
||
const { url, sample } = await firstRecord(page);
|
||
await withRoute(page, sample, {
|
||
report: 14,
|
||
colposcopy: 30,
|
||
request: 40,
|
||
biopsy: 50,
|
||
diagnosis: 70,
|
||
link: 'recorded',
|
||
});
|
||
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
|
||
const stages = historial(page).locator('app-stages li');
|
||
const text = async (n: number) => (await stages.nth(n).innerText()).replace(/\s+/g, ' ');
|
||
expect(await text(0)).toContain(`Registrada ${sample}`);
|
||
expect(await text(1)).toContain(
|
||
`Registrada ${plus(sample, 14)} Procedencia: Formulario de citología Desde anterior: 14 días Desde toma: 14 días`,
|
||
);
|
||
// colposcopy and diagnosis are inferred from dates: their intervals say so
|
||
expect(await text(2)).toContain(
|
||
`Inferida por fechas ${plus(sample, 30)} Desde anterior: 16 días (inferido) Desde toma: 30 días (inferido)`,
|
||
);
|
||
// a recorded biopsy link is recorded; the interval since an inferred stage is still inferred
|
||
expect(await text(3)).toContain(
|
||
`Registrada ${plus(sample, 50)} Desde anterior: 20 días (inferido) Desde toma: 50 días`,
|
||
);
|
||
expect(await text(4)).toContain(
|
||
`Inferida por fechas ${plus(sample, 70)} Desde anterior: 20 días (inferido)`,
|
||
);
|
||
const state = (n: number) =>
|
||
stages
|
||
.nth(n)
|
||
.locator('.node')
|
||
.evaluate(
|
||
(e) => getComputedStyle(e).backgroundColor + '|' + getComputedStyle(e).borderTopStyle,
|
||
);
|
||
expect(await state(0)).toBe('rgb(56, 123, 102)|solid'); // recorded
|
||
expect(await state(2)).toBe('rgb(66, 105, 160)|double'); // inferred
|
||
// an inferred biopsy link: inferred as well
|
||
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
|
||
await withRoute(page, sample, {
|
||
report: 14,
|
||
colposcopy: 30,
|
||
request: 40,
|
||
biopsy: 50,
|
||
diagnosis: 70,
|
||
});
|
||
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
|
||
expect(await text(3)).toContain('Inferida por fechas');
|
||
});
|
||
|
||
test('ficha (simulado): the cut-off hides what is dated after it; a biopsy asked and not reported is pending', async ({
|
||
page,
|
||
}) => {
|
||
const { url, sample } = await firstRecord(page);
|
||
await withRoute(page, sample, {
|
||
report: 14,
|
||
colposcopy: 30,
|
||
request: 40,
|
||
biopsy: 50,
|
||
diagnosis: 70,
|
||
});
|
||
const cutoff = plus(sample, 45); // after the request, before the report
|
||
await open(page, `${url.split('?')[0]}?corte=${cutoff}&citologia=${sample}`);
|
||
const stages = historial(page).locator('app-stages li');
|
||
const states = await stages.locator('.info span:nth-child(2)').allInnerTexts();
|
||
expect(states.map((s) => s.trim())).toEqual([
|
||
'Registrada',
|
||
'Registrada',
|
||
'Inferida por fechas',
|
||
'Pendiente',
|
||
'Sin dato',
|
||
]);
|
||
await expect(historial(page)).toContainText(`a la fecha de corte ${cutoff}`);
|
||
const pending = await stages
|
||
.nth(3)
|
||
.locator('.node')
|
||
.evaluate((e) => getComputedStyle(e).backgroundColor);
|
||
expect(pending).toBe('rgb(255, 241, 201)');
|
||
const unknown = await stages
|
||
.nth(4)
|
||
.locator('.node')
|
||
.evaluate((e) => getComputedStyle(e).borderTopStyle);
|
||
expect(unknown).toBe('dashed');
|
||
await expect(stages.nth(4)).toContainText('Sin fecha');
|
||
await expect(stages.nth(4)).toContainText('Desde toma: —');
|
||
// a cut-off before the sample: nothing is known
|
||
await page.unroute('**/api/cacu/fhir/DiagnosticReport**');
|
||
await withRoute(page, sample, { report: 14 });
|
||
await open(page, `${url.split('?')[0]}?corte=${plus(sample, -1)}&citologia=${sample}`);
|
||
expect(
|
||
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
|
||
).toEqual(Array(5).fill('Sin dato'));
|
||
});
|
||
|
||
test('ficha (simulado): the scales draw 0, 2, 50, 98 and 100 % in place, and tell zero from absent', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await withRisks(page, [
|
||
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
|
||
[0, 0],
|
||
[5, 0.5, 0.4, 0.6],
|
||
]),
|
||
risk('b', 'Recurrencia v2', 'cacu.recurrence', '2026-03-01', [
|
||
[0, 0.02, 0.01, 0.03],
|
||
[5, 0.98, 0.95, 1],
|
||
]),
|
||
risk('c', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]), // no immediate horizon
|
||
risk('d', 'Parcial v1', 'cacu.partial', '2026-05-01', [[0, 0.5]]), // no five-year horizon
|
||
]);
|
||
await open(page, url);
|
||
await expect(
|
||
page.getByRole('heading', { name: 'Supervivencia v3 · fecha índice 2026-02-01' }),
|
||
).toBeVisible();
|
||
await expect(
|
||
page.getByRole('heading', { name: 'Recurrencia v2 · fecha índice 2026-03-01' }),
|
||
).toBeVisible();
|
||
const at = async (label: string, nth: number) => drawn(scale(page, label, nth));
|
||
// group order follows the page's models: survival, recurrence, other, partial
|
||
const groups = await page.locator('.risk-scale').count();
|
||
expect(groups).toBe(8); // both horizons of four models
|
||
const model = async (n: number) => [await at(IMMEDIATE, n), await at(FIVE, n)];
|
||
const [survival, recurrence, other, partial] = [
|
||
await model(0),
|
||
await model(1),
|
||
await model(2),
|
||
await model(3),
|
||
];
|
||
expect(survival[0]).toMatchObject({ markers: 1, left: '0%', value: '0.0 %', grey: 0 }); // a real zero
|
||
expect(survival[1]).toMatchObject({ left: '50%', value: '50.0 %' });
|
||
expect(recurrence[0]).toMatchObject({ left: '2%', value: '2.0 %' });
|
||
expect(recurrence[1]).toMatchObject({ left: '98%', value: '98.0 %' });
|
||
expect(other[0]).toMatchObject({ markers: 0, grey: 1 }); // absent, not zero
|
||
expect(other[1]).toMatchObject({ left: '100%', value: '100.0 %' });
|
||
expect(partial[0]).toMatchObject({ left: '50%' });
|
||
expect(partial[1]).toMatchObject({ markers: 0, grey: 1 });
|
||
await expect(scale(page, IMMEDIATE, 2)).toContainText('No disponible');
|
||
await expect(scale(page, FIVE, 3)).toContainText('No disponible');
|
||
await expect(scale(page, FIVE, 0)).toContainText('IC 95 %: 40.0–60.0 %');
|
||
await expect(scale(page, FIVE, 1)).toContainText('IC 95 %: 95.0–100.0 %');
|
||
await expect(scale(page, IMMEDIATE, 0)).not.toContainText('IC 95 %'); // none published, none invented
|
||
// the descriptive note stays, and the model table and curve of rebuild are still there
|
||
await expect(page.getByText('no representan umbrales clínicos')).toBeVisible();
|
||
await expect(page.getByRole('columnheader', { name: 'Probabilidad', exact: true })).toBeVisible();
|
||
});
|
||
|
||
test('ficha (simulado): the scale is drawn in four equal segments with the numeric divisions', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await withRisks(page, [
|
||
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [[5, 0.5, 0.4, 0.6]]),
|
||
]);
|
||
await open(page, url);
|
||
const box = scale(page, FIVE);
|
||
await expect(box.locator('.risk-labels span')).toHaveText([
|
||
'0 %',
|
||
'25 %',
|
||
'50 %',
|
||
'75 %',
|
||
'100 %',
|
||
]);
|
||
const line = await box.locator('.risk-line').evaluate((e) => getComputedStyle(e).backgroundImage);
|
||
for (const colour of [
|
||
'rgb(66, 167, 126)',
|
||
'rgb(168, 194, 67)',
|
||
'rgb(223, 134, 64)',
|
||
'rgb(194, 66, 105)',
|
||
])
|
||
expect(line).toContain(colour);
|
||
// the marker sits at 50 % of the bar
|
||
const [bar, mark] = await Promise.all([
|
||
box.locator('.risk-plot').boundingBox(),
|
||
box.locator('.risk-marker').boundingBox(),
|
||
]);
|
||
expect(Math.abs(mark!.x + mark!.width / 2 - (bar!.x + bar!.width / 2))).toBeLessThan(3);
|
||
});
|
||
|
||
for (const width of [1440, 480]) {
|
||
test(`ficha (simulado) at ${width} px: the stages and the scales lay out cleanly`, async ({
|
||
page,
|
||
}) => {
|
||
await page.setViewportSize({ width, height: 1000 });
|
||
const { url, sample } = await firstRecord(page);
|
||
await withRoute(page, sample, {
|
||
report: 14,
|
||
colposcopy: 30,
|
||
request: 40,
|
||
biopsy: 50,
|
||
diagnosis: 70,
|
||
link: 'recorded',
|
||
});
|
||
await withRisks(page, [
|
||
risk('a', 'Supervivencia v3', 'cacu.survival', '2026-02-01', [
|
||
[0, 0],
|
||
[5, 0.98, 0.95, 1],
|
||
]),
|
||
risk('b', 'Otro modelo v1', 'cacu.other', '2026-04-01', [[5, 1]]),
|
||
]);
|
||
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
|
||
await page.waitForTimeout(800);
|
||
expect(await layoutProblems(page)).toEqual([]);
|
||
const tops = await historial(page)
|
||
.locator('app-stages li .node')
|
||
.evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().top)));
|
||
// wide: one row of nodes; narrow: a column (each below the previous)
|
||
if (width > 700) expect(new Set(tops).size).toBe(1);
|
||
else {
|
||
expect(tops).toEqual([...tops].sort((a, b) => a - b));
|
||
expect(new Set(tops).size).toBe(5);
|
||
}
|
||
expect(
|
||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
|
||
).toBe(true);
|
||
});
|
||
}
|
||
|
||
const code = (name: string, valueCode: string) => ({ url: EXT + name, valueCode });
|
||
const nodeOf = (page: Page, n: number) => historial(page).locator('app-stages li').nth(n);
|
||
|
||
/** A record, by the API, whose cytology (the latest of the first patients) satisfies `wanted`. */
|
||
async function recordWhere(page: Page, wanted: (report: any) => boolean) {
|
||
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
|
||
const ids: string[] = patients.entry.map((e: any) => e.resource.id);
|
||
for (let i = 0; i < ids.length; i += 25) {
|
||
const subject = ids
|
||
.slice(i, i + 25)
|
||
.map((p) => 'Patient/' + p)
|
||
.join(',');
|
||
const found = await (
|
||
await page.request.get(`/api/cacu/fhir/DiagnosticReport?_count=200&subject=${subject}`)
|
||
).json();
|
||
for (const { resource: r } of found.entry ?? [])
|
||
if (r.code?.coding?.[0]?.code === 'cervical_cytology' && wanted(r))
|
||
return {
|
||
id: r.subject.reference.split('/')[1] as string,
|
||
sample: r.effectiveDateTime as string,
|
||
};
|
||
}
|
||
throw new Error('no record with those stages in the first patients');
|
||
}
|
||
const has = (r: any, name: string) => (r.extension ?? []).some((e: any) => e.url === EXT + name);
|
||
|
||
test('ficha: the stages say what the backend demonstrates, with their sources', async ({
|
||
page,
|
||
}) => {
|
||
const { id, sample } = await recordWhere(
|
||
page,
|
||
(r) => has(r, 'stage-colposcopy-state') && has(r, 'stage-biopsy-state'),
|
||
);
|
||
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
|
||
const states = await historial(page)
|
||
.locator('app-stages li .info span:nth-child(2)')
|
||
.allInnerTexts();
|
||
expect(states[0]).toBe('Registrada');
|
||
expect(states[2]).toBe('Inferida por fechas'); // colposcopy is always inferred
|
||
expect(['Inferida por fechas', 'Registrada']).toContain(states[3]);
|
||
const colposcopy = (await nodeOf(page, 2).innerText()).replace(/\s+/g, ' ');
|
||
expect(colposcopy).toMatch(/Procedencia: (Nota clínica|Orden de biopsia)/);
|
||
expect(colposcopy).toContain('Desde anterior:');
|
||
expect((await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ')).toMatch(
|
||
/Procedencia: (Asociación por fechas|Registro de la biopsia)/,
|
||
);
|
||
// the first two stages come from the form
|
||
expect(await nodeOf(page, 0).innerText()).toContain('Procedencia: Formulario de citología');
|
||
});
|
||
|
||
test('ficha (simulado): a stage the backend flags as ambiguous is drawn so, with no interval resting on it', async ({
|
||
page,
|
||
}) => {
|
||
const { url, sample } = await firstRecord(page);
|
||
await withRoute(page, sample, {
|
||
report: 14,
|
||
colposcopy: 30,
|
||
request: 40,
|
||
biopsy: 50,
|
||
diagnosis: 70,
|
||
extra: [
|
||
code('stage-biopsy-state', 'ambiguous'),
|
||
code('stage-biopsy-source', 'date-association'),
|
||
code('stage-colposcopy-state', 'inferred'),
|
||
code('stage-colposcopy-source', 'clinical-note'),
|
||
code('stage-colposcopy-source', 'biopsy-order'),
|
||
],
|
||
});
|
||
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
|
||
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
|
||
expect(biopsy).toContain(`Ambigua ${plus(sample, 50)}`);
|
||
expect(biopsy).toContain('Procedencia: Asociación por fechas');
|
||
expect(biopsy).toContain('Desde anterior: — Desde toma: —');
|
||
expect(
|
||
await nodeOf(page, 3)
|
||
.locator('.node')
|
||
.evaluate((e) => getComputedStyle(e).borderTopStyle),
|
||
).toBe('double');
|
||
// no interval rests on the ambiguous day, so the next stage has none from the previous one either
|
||
expect((await nodeOf(page, 4).innerText()).replace(/\s+/g, ' ')).toContain('Desde anterior: —');
|
||
// a colposcopy dated by a note and a biopsy order lists both sources
|
||
expect(await nodeOf(page, 2).innerText()).toContain(
|
||
'Procedencia: Nota clínica · Orden de biopsia',
|
||
);
|
||
});
|
||
|
||
test('ficha (simulado): a biopsy the backend says is pending shows its request, not a day', async ({
|
||
page,
|
||
}) => {
|
||
const { url, sample } = await firstRecord(page);
|
||
await withRoute(page, sample, {
|
||
report: 14,
|
||
colposcopy: 30,
|
||
request: 40,
|
||
extra: [
|
||
code('stage-biopsy-state', 'pending'),
|
||
code('stage-biopsy-source', 'date-association'),
|
||
code('biopsy-link', 'inferred'),
|
||
],
|
||
});
|
||
await open(page, `${url.split('?')[0]}?corte=${plus(sample, 200)}&citologia=${sample}`);
|
||
const biopsy = (await nodeOf(page, 3).innerText()).replace(/\s+/g, ' ');
|
||
expect(biopsy).toContain('Pendiente');
|
||
expect(biopsy).toContain(`Solicitada el ${plus(sample, 40)}`);
|
||
expect(biopsy).toContain('Desde toma: —');
|
||
// colposcopy and diagnosis are never pending: no request is known for them
|
||
expect(
|
||
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts(),
|
||
).not.toContain('Pendiente' + 'x');
|
||
const states = (
|
||
await historial(page).locator('app-stages li .info span:nth-child(2)').allInnerTexts()
|
||
).map((t) => t.trim());
|
||
expect(states.filter((t) => t === 'Pendiente')).toHaveLength(1);
|
||
});
|
||
|
||
// ---- the record's tests and its antecedents
|
||
const antecedents = (page: Page) => page.locator('[data-section=antecedentes]');
|
||
const tests = (page: Page) =>
|
||
page.locator('mat-card', {
|
||
has: page.locator('mat-card-title', { hasText: 'Pruebas y resultados' }),
|
||
});
|
||
|
||
test('ficha: antecedents and gynecologic evaluation have their own section; tests keep their results', async ({
|
||
page,
|
||
}) => {
|
||
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
|
||
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
|
||
const card = antecedents(page);
|
||
await expect(card).toBeVisible();
|
||
await expect(card).toContainText('no son diagnósticos confirmados');
|
||
await expect(card).toContainText(`Citología cervical · toma ${sample}`);
|
||
for (const title of [
|
||
'Detección de cáncer de cérvix',
|
||
'Condición ginecoobstétrica a la detección',
|
||
'Actualmente presenta',
|
||
'A la exploración se observa',
|
||
])
|
||
await expect(card.locator('dl.facts dt', { hasText: title })).toBeVisible();
|
||
// the earlier forms are collapsed, each with its own day
|
||
const earlier = card.locator('details.findings');
|
||
if (await earlier.count()) {
|
||
expect(await earlier.getAttribute('open')).toBeNull();
|
||
await earlier.locator('summary').click();
|
||
await expect(earlier.locator('tbody tr').first().locator('td').first()).toHaveText(
|
||
/\d{4}-\d{2}-\d{2}/,
|
||
);
|
||
}
|
||
// the tests keep date, study, report and the results of the study, without the form's antecedents
|
||
const table = tests(page);
|
||
await expect(table.getByRole('columnheader')).toHaveText([
|
||
'Toma',
|
||
'Estudio',
|
||
'Reporte',
|
||
'Resultados',
|
||
]);
|
||
const text = await table.innerText();
|
||
expect(text).toContain('Resultado (Bethesda)');
|
||
expect(text).not.toContain('Detección de cáncer de cérvix');
|
||
expect(text).not.toContain('A la exploración se observa');
|
||
// the extra findings are collapsed under their report
|
||
const findings = table.locator('details.findings').first();
|
||
await expect(findings.locator('summary')).toContainText('Hallazgos (');
|
||
expect(await findings.getAttribute('open')).toBeNull();
|
||
expect((await findings.locator('li').first().textContent())!.trim().length).toBeGreaterThan(0);
|
||
});
|
||
|
||
test('ficha (simulado): a missing antecedent says it is not documented; with none, no section', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
const strip = (keep: string[]) =>
|
||
page.route('**/api/cacu/fhir/Observation**', async (route) => {
|
||
const response = await route.fetch();
|
||
const body = await response.json();
|
||
body.entry = (body.entry ?? []).filter((e: any) => {
|
||
const field = (e.resource.code?.coding?.[0]?.code ?? '').split('.').pop();
|
||
const antecedent = [
|
||
'screening_history',
|
||
'gynecologic_condition',
|
||
'presenting_symptom',
|
||
'cervix_appearance',
|
||
].includes(field);
|
||
return !antecedent || keep.includes(field);
|
||
});
|
||
await route.fulfill({
|
||
response,
|
||
body: JSON.stringify(body),
|
||
contentType: 'application/fhir+json',
|
||
});
|
||
});
|
||
await strip(['screening_history']);
|
||
await open(page, url);
|
||
const card = antecedents(page);
|
||
await expect(card.locator('dl.facts dd').first()).not.toHaveText('No documentado');
|
||
await expect(card.locator('dl.facts dd', { hasText: 'No documentado' })).toHaveCount(3);
|
||
await page.unroute('**/api/cacu/fhir/Observation**');
|
||
await strip([]);
|
||
await open(page, url);
|
||
await expect(antecedents(page)).toHaveCount(0);
|
||
// the record's tests are still there without them
|
||
await expect(tests(page).getByRole('table')).toBeVisible();
|
||
});
|
||
|
||
test('ficha: the PDF keeps the stages, antecedents, tests and risks', async ({ page }) => {
|
||
const { id, sample } = await recordWhere(page, (r) => (r.result ?? []).length > 8);
|
||
await open(page, `/indicadores/cacu/pacientes/${id}?corte=2026-12-31&citologia=${sample}`);
|
||
const saved = page.waitForEvent('download');
|
||
await historial(page).getByRole('button', { name: 'Exportar PDF' }).click();
|
||
const download = await saved;
|
||
expect(download.suggestedFilename()).toBe('expediente-cacu.pdf');
|
||
const file = await download.path();
|
||
expect(file).toBeTruthy();
|
||
const { readFileSync } = await import('node:fs');
|
||
const bytes = readFileSync(file!);
|
||
expect(bytes.subarray(0, 4).toString()).toBe('%PDF');
|
||
expect(bytes.length).toBeGreaterThan(5_000);
|
||
});
|
||
|
||
// ---- the NCI reference comparison (experimental) and the institutional curves ---------------------
|
||
|
||
const REFERENCE = '**/api/cacu/fhir/Patient/*/$reference-risk*';
|
||
const section = (page: Page) => page.locator('[data-section=referencia-nci]');
|
||
const value = (p: any) =>
|
||
p.valueCode ?? p.valueString ?? p.valueDate ?? p.valueInteger ?? p.valueDecimal ?? p.valueBoolean;
|
||
|
||
/** The first patients' answers of the API, to find one with a given state (the data is synthetic). */
|
||
async function referenceWhere(page: Page, status: string) {
|
||
const patients = await (await page.request.get('/api/cacu/fhir/Patient?_count=100')).json();
|
||
for (const { resource } of patients.entry) {
|
||
const answer = await page.request.get(`/api/cacu/fhir/Patient/${resource.id}/$reference-risk`);
|
||
if (!answer.ok()) throw new Error(`the reference operation answered ${answer.status()}`);
|
||
const body = await answer.json();
|
||
if (value(body.parameter.find((p: any) => p.name === 'status')) === status)
|
||
return { id: resource.id as string, body };
|
||
}
|
||
throw new Error(`no patient with the state ${status}`);
|
||
}
|
||
const part = (name: string, extra: object) => ({ name, ...extra });
|
||
const answerOf = (...parameter: object[]) => ({ resourceType: 'Parameters', parameter });
|
||
/** A resolved answer for fixtures, with the given horizons and comparisons. */
|
||
function fixture(
|
||
horizons: { years: number; reference?: number; comparison?: object[] }[],
|
||
more: object[] = [],
|
||
) {
|
||
return answerOf(
|
||
part('status', { valueCode: 'resolved' }),
|
||
part('experimental', { valueBoolean: true }),
|
||
part('cutoff', { valueDate: '2026-11-30' }),
|
||
part('scenario', {
|
||
part: [
|
||
part('table', { valueCode: 'screening' }),
|
||
part('label', { valueString: 'Tamizaje' }),
|
||
part('key', {
|
||
part: [
|
||
part('name', { valueCode: 'history' }),
|
||
part('value', { valueString: 'Cotest-negative' }),
|
||
],
|
||
}),
|
||
],
|
||
}),
|
||
part('source', {
|
||
part: [
|
||
part('id', { valueString: 'fixture-table' }),
|
||
part('file', { valueString: 'fixture.xlsx' }),
|
||
],
|
||
}),
|
||
...more,
|
||
...horizons.map((h) =>
|
||
part('horizon', {
|
||
part: [
|
||
part('years', { valueInteger: h.years }),
|
||
part('published', { valueBoolean: h.reference !== undefined }),
|
||
...(h.reference !== undefined ? [part('reference', { valueDecimal: h.reference })] : []),
|
||
...(h.comparison ?? []),
|
||
],
|
||
}),
|
||
),
|
||
);
|
||
}
|
||
const comparison = (status: string, reasons: string[], extra: object[] = []) =>
|
||
part('comparison', {
|
||
part: [
|
||
part('model', { valueCode: 'fixture.model' }),
|
||
part('title', { valueString: 'Modelo de prueba' }),
|
||
part('outcome', { valueString: 'CIN3+' }),
|
||
...extra,
|
||
part('status', { valueCode: status }),
|
||
...reasons.map((r) => part('reason', { valueCode: r })),
|
||
],
|
||
});
|
||
const answerWith = (page: Page, body: object, status = 200) =>
|
||
page.route(REFERENCE, (route) =>
|
||
route.fulfill({ status, contentType: 'application/fhir+json', body: JSON.stringify(body) }),
|
||
);
|
||
|
||
test('referencia NCI: a resolved cytology shows its reference with scenario, source and no institutional model', async ({
|
||
page,
|
||
}) => {
|
||
const { id, body } = await referenceWhere(page, 'resolved');
|
||
await open(page, `/indicadores/cacu/pacientes/${id}`);
|
||
const box = section(page);
|
||
await expect(box).toBeVisible();
|
||
await expect(box.locator('dd[data-status=resolved]')).toHaveText('Referencia disponible');
|
||
await expect(box).toContainText('Tamizaje');
|
||
await expect(box).toContainText('CIN3 o más grave (CIN3+)');
|
||
await expect(box).toContainText('Master_NCI_Risk_Table.xlsx');
|
||
const rows = box.locator('tbody tr');
|
||
await expect(rows).toHaveCount(2);
|
||
await expect(rows.first()).toContainText('Inmediato (al índice)');
|
||
await expect(rows.nth(1)).toContainText('5 años');
|
||
// the figures are the API's: percent with two decimals, and no institutional model is made up
|
||
const expected = body.parameter
|
||
.filter((p: any) => p.name === 'horizon')
|
||
.map((h: any) =>
|
||
(h.part.find((x: any) => x.name === 'reference').valueDecimal * 100).toFixed(2),
|
||
);
|
||
for (const [i, pct] of expected.entries())
|
||
await expect(rows.nth(i).locator('td').nth(2)).toContainText(`${pct} %`);
|
||
await expect(rows.first().locator('td').nth(1)).toContainText('No disponible');
|
||
await expect(rows.first().locator('td').nth(3)).toContainText('No comparable');
|
||
await expect(rows.first().locator('td').nth(3)).toContainText('Ningún modelo institucional');
|
||
// the antecedents used are collapsed
|
||
const used = box.locator('details.used');
|
||
expect(await used.getAttribute('open')).toBeNull();
|
||
await used.locator('summary').click();
|
||
await expect(used).toContainText('Fila de origen');
|
||
await expect(used).toContainText('Citología evaluada');
|
||
// the other risk displays of the record are still there, and the reference is below the scales
|
||
await expect(scale(page, FIVE)).toBeVisible();
|
||
const [scales, reference] = await Promise.all([
|
||
scale(page, FIVE).boundingBox(),
|
||
box.boundingBox(),
|
||
]);
|
||
expect(reference!.y).toBeGreaterThan(scales!.y);
|
||
await expect(
|
||
page.locator('mat-card-title', { hasText: 'Riesgos y recomendaciones' }),
|
||
).toBeVisible();
|
||
});
|
||
|
||
test('referencia NCI: a cytology the tables cannot resolve says the state and why, with no figure', async ({
|
||
page,
|
||
}) => {
|
||
const { id } = await referenceWhere(page, 'unverifiable_correspondence');
|
||
await open(page, `/indicadores/cacu/pacientes/${id}`);
|
||
const box = section(page);
|
||
await expect(box.locator('dd[data-status=unverifiable_correspondence]')).toHaveText(
|
||
'Correspondencia no verificable',
|
||
);
|
||
await expect(box.locator('ul.why li').first()).not.toBeEmpty();
|
||
await expect(box.locator('table')).toHaveCount(0);
|
||
await expect(box).not.toContainText('%');
|
||
});
|
||
|
||
test('referencia NCI: with the feature off (404) the section is not there and the record is whole', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await answerWith(
|
||
page,
|
||
{ resourceType: 'OperationOutcome', issue: [{ severity: 'error', code: 'not-found' }] },
|
||
404,
|
||
);
|
||
await open(page, url);
|
||
await expect(section(page)).toHaveCount(0);
|
||
await expect(scale(page, FIVE)).toBeVisible();
|
||
});
|
||
|
||
test('referencia NCI (simulado): a comparison that is valid shows the difference as institutional minus reference', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await answerWith(
|
||
page,
|
||
fixture([
|
||
{
|
||
years: 5,
|
||
reference: 0.0027,
|
||
comparison: [
|
||
comparison(
|
||
'comparable',
|
||
[],
|
||
[
|
||
part('institutional', { valueDecimal: 0.0127 }),
|
||
part('institutional-low', { valueDecimal: 0.005 }),
|
||
part('institutional-high', { valueDecimal: 0.02 }),
|
||
part('difference-pp', { valueDecimal: 1 }),
|
||
],
|
||
),
|
||
],
|
||
},
|
||
]),
|
||
);
|
||
await open(page, url);
|
||
const row = section(page).locator('tbody tr').first();
|
||
await expect(row).toContainText('Modelo de prueba');
|
||
await expect(row).toContainText('1.27 %');
|
||
await expect(row).toContainText('IC 95 %: 0.50–2.00 %');
|
||
await expect(row.locator('td').nth(2)).toContainText('0.27 %');
|
||
await expect(row.locator('td').nth(3)).toContainText('+1.00');
|
||
await expect(row.locator('td').nth(3)).not.toContainText('No comparable');
|
||
});
|
||
|
||
test('referencia NCI (simulado): another outcome or horizon is "No comparable" with its reasons and no difference', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await answerWith(
|
||
page,
|
||
fixture([
|
||
{
|
||
years: 0,
|
||
reference: 0.0001,
|
||
comparison: [
|
||
comparison(
|
||
'not_comparable',
|
||
['outcome_differs', 'horizon_not_published_by_model', 'population_not_verified'],
|
||
[part('institutional', { valueDecimal: 0.05 })],
|
||
),
|
||
],
|
||
},
|
||
{ years: 5, reference: 0.0027 },
|
||
]),
|
||
);
|
||
await open(page, url);
|
||
const first = section(page).locator('tbody tr').first();
|
||
await expect(first.locator('td').nth(3)).toContainText('No comparable');
|
||
await expect(first.locator('td').nth(3)).toContainText(
|
||
'El desenlace del modelo no es el de la tabla (CIN3+)',
|
||
);
|
||
await expect(first.locator('td').nth(3)).toContainText(
|
||
'no publica una predicción a este horizonte',
|
||
);
|
||
await expect(first.locator('td').nth(3)).not.toContainText(/[+-]\d/); // no signed difference
|
||
await expect(first.locator('td').nth(1)).toContainText('5.00 %'); // the model's own risk is shown, never subtracted
|
||
});
|
||
|
||
test('referencia NCI (simulado): a year-one reference is a year, never the immediate risk; a blank is not zero', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await answerWith(page, fixture([{ years: 1, reference: 0.0136 }, { years: 5 }]));
|
||
await open(page, url);
|
||
const rows = section(page).locator('tbody tr');
|
||
await expect(rows.first()).toContainText('1 año');
|
||
await expect(section(page)).not.toContainText('Inmediato');
|
||
await expect(rows.nth(1).locator('td').nth(2)).toContainText('No publicado');
|
||
await expect(rows.nth(1).locator('td').nth(2)).not.toContainText('0.00');
|
||
await expect(rows.first().locator('td').nth(2)).toContainText('1.36 %');
|
||
});
|
||
|
||
for (const width of [1440, 480]) {
|
||
test(`referencia NCI (simulado) at ${width} px: the section lays out cleanly beside the scales and curves`, async ({
|
||
page,
|
||
}) => {
|
||
await page.setViewportSize({ width, height: 1000 });
|
||
const { url } = await firstRecord(page);
|
||
await answerWith(
|
||
page,
|
||
fixture(
|
||
[
|
||
{
|
||
years: 0,
|
||
reference: 0.0001,
|
||
comparison: [
|
||
comparison(
|
||
'not_comparable',
|
||
['outcome_differs', 'population_not_verified'],
|
||
[part('institutional', { valueDecimal: 0.05 })],
|
||
),
|
||
],
|
||
},
|
||
{
|
||
years: 5,
|
||
reference: 0.0027,
|
||
comparison: [
|
||
comparison(
|
||
'comparable',
|
||
[],
|
||
[
|
||
part('institutional', { valueDecimal: 0.0127 }),
|
||
part('difference-pp', { valueDecimal: 1 }),
|
||
],
|
||
),
|
||
],
|
||
},
|
||
],
|
||
[part('assumption', { valueString: 'un supuesto sin verificar' })],
|
||
),
|
||
);
|
||
await withRisks(page, [
|
||
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
|
||
[1, 0.08, 0.05, 0.12],
|
||
[3, 0.21, 0.15, 0.28],
|
||
[5, 0.34, 0.26, 0.44],
|
||
]),
|
||
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
|
||
[1, 0.002, 0.001, 0.005],
|
||
[3, 0.008],
|
||
[5, 0.015, 0.008, 0.028],
|
||
]),
|
||
]);
|
||
await open(page, url);
|
||
await section(page).locator('details.used summary').click();
|
||
await page.waitForTimeout(800);
|
||
expect(await layoutProblems(page)).toEqual([]);
|
||
expect(
|
||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1),
|
||
).toBe(true);
|
||
});
|
||
}
|
||
|
||
test('curvas (simulado): one series per model at its published horizons, its band only where it has intervals, and no NCI data', async ({
|
||
page,
|
||
}) => {
|
||
const { url } = await firstRecord(page);
|
||
await answerWith(page, fixture([{ years: 5, reference: 0.0027 }]));
|
||
await withRisks(page, [
|
||
risk('a', 'Riesgo LIEAG+ v3', 'cacu.survival', '2026-06-01', [
|
||
[1, 0.08, 0.05, 0.12],
|
||
[3, 0.21, 0.15, 0.28],
|
||
[5, 0.34, 0.26, 0.44],
|
||
]),
|
||
risk('b', 'Riesgo cáncer v2', 'cacu.recurrence', '2026-06-01', [
|
||
[1, 0.002, 0.001, 0.005],
|
||
[3, 0.008],
|
||
[5, 0.015, 0.008, 0.028],
|
||
]),
|
||
risk('c', 'Sin intervalo v1', 'cacu.other', '2026-06-01', [
|
||
[2, 0.1],
|
||
[4, 0.2],
|
||
]),
|
||
risk('d', 'Un punto v1', 'cacu.partial', '2026-06-01', [[5, 0.5]]),
|
||
]);
|
||
await open(page, url);
|
||
const card = page.locator('details.curves');
|
||
await expect(card.locator('summary')).toHaveText('Curvas de probabilidad con su intervalo');
|
||
await expect(card).toHaveAttribute('open', '');
|
||
await expect(card.locator('li').first()).toContainText(
|
||
'Riesgo LIEAG+ (fecha índice 2026-06-01): 1 año: 8.0 % (IC 95 %: 5.0–12.0 %); 3 años: 21.0 %',
|
||
);
|
||
const plot = await card.locator('.js-plotly-plot').evaluate((e: any) => ({
|
||
names: e.data.filter((t: any) => t.showlegend !== false).map((t: any) => t.name),
|
||
series: Object.fromEntries(
|
||
e.data.filter((t: any) => t.mode?.includes('markers')).map((t: any) => [t.name, t.x]),
|
||
),
|
||
bands: e.data.filter((t: any) => t.fill === 'tonexty').map((t: any) => t.name),
|
||
ticks: e.layout.xaxis.tickvals,
|
||
title: e.layout.xaxis.title.text,
|
||
}));
|
||
expect(plot.series).toEqual({
|
||
'Riesgo LIEAG+': [1, 3, 5],
|
||
'Riesgo cáncer': [1, 3, 5],
|
||
'Sin intervalo': [2, 4],
|
||
'Un punto': [5],
|
||
});
|
||
expect(plot.bands).toEqual(['IC 95 % Riesgo LIEAG+', 'IC 95 % Riesgo cáncer']); // none for the models without intervals
|
||
expect(plot.ticks).toEqual([1, 2, 3, 4, 5]);
|
||
expect(plot.title).toBe('Horizonte (años desde la fecha índice (2026-06-01))');
|
||
// the reference is a separate table: its 0.27 % is nowhere in the figure
|
||
expect(
|
||
JSON.stringify(await card.locator('.js-plotly-plot').evaluate((e: any) => e.data)),
|
||
).not.toContain('0.27');
|
||
await expect(page.locator('[data-section=referencia-nci]')).toBeVisible();
|
||
});
|