Files
WebApp/e2e/pages.spec.ts
T
Angel Capetillo Zavala 44f3dce911 Integrate CaCu indicators, risk views and exports
Adapted from Angel Capetillo Zavala commits c0e4920 and 31400c7 and Edgar Hinojosas CaCu measures. Includes the existing 6F presentation and external donut labels.

Co-authored-by: edgar <edgar.hinojosas@uanl.edu.mx>
2026-11-30 16:02:00 -06:00

671 lines
32 KiB
TypeScript

import { readFileSync } from 'node:fs';
import { expect, Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
/** Every page loads from the API with no failed request and no console error. */
function watch(page: Page): string[] {
const problems: string[] = [];
page.on('console', (m) => m.type() === 'error' && problems.push(`console: ${m.text()}`));
page.on('response', (r) => r.status() >= 400 && problems.push(`${r.status()} ${r.url()}`));
page.on('pageerror', (e) => problems.push(`page: ${e.message}`));
return problems;
}
// The pages show only to someone signed in (the API itself answers everyone).
test.beforeEach(async ({ page }) => {
const signed = await page.request.post('/api/auth/login', {
form: { username: 'admin@isssteleon.mx', password: 'solo-para-pruebas' },
});
expect(signed.status()).toBe(204);
});
test('login: the pages wait for a sign-in, and a wrong password says so', async ({ browser }) => {
const page = await browser.newPage({ baseURL: 'http://127.0.0.1:4310' });
await page.goto('/conectar');
await expect(page).toHaveURL(/\/login\?next=%2Fconectar/);
await expect(page.getByRole('heading', { name: 'Inicio de sesión' })).toBeVisible();
await page.getByRole('textbox', { name: 'Usuario' }).fill('admin@isssteleon.mx');
await page.getByRole('textbox', { name: 'Contraseña' }).fill('otra');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page.getByText('Usuario o contraseña incorrectos.')).toBeVisible();
await page.getByRole('textbox', { name: 'Contraseña' }).fill('solo-para-pruebas');
await page.getByRole('button', { name: 'Ingresar' }).click();
await expect(page).toHaveURL(/\/conectar$/);
await page.getByRole('button', { name: 'Cuenta' }).click();
await page.getByRole('menuitem', { name: 'Salir' }).click();
await expect(page).toHaveURL(/\/login/);
await page.close();
});
test("indicators: the KPIs are the API's MeasureReports, every tab and the patient view load", async ({
page,
}) => {
const problems = watch(page);
const report = page.waitForResponse(
(r) =>
r.url().includes('MeasureReport') &&
r.url().includes('measure=cacu-eu7') &&
!r.url().includes('%2C'),
);
await page.goto('/indicadores/cacu');
const eu7 = await (await report).json();
const count = eu7.entry[0].resource.group[0].population.find(
(p: any) => p.code.coding[0].code === 'initial-population',
).count;
// the card says it as the old one did: "<n> pacientes"
await expect(page.locator('[data-measure="CACU_EU7"] .kpi-value')).toHaveText(
`${count.toLocaleString('es-MX')} pacientes`,
);
await expect(page.locator('app-tab-indicadores app-plot').first()).toBeVisible();
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
await expect(page.locator('app-tab-trazabilidad mat-card')).toHaveCount(14);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
await expect(page.locator('app-tab-definiciones tbody tr')).toHaveCount(14);
const list = page.waitForResponse((r) => r.url().includes('/fhir/Patient?'));
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const bundle = await (await list).json();
const patient = bundle.entry.find((e: any) => e.search.mode === 'match').resource;
const first = patient.name?.[0]?.text ?? patient.id.slice(0, 10);
const rows = page.locator('table.worklist tbody tr');
await expect(rows).toHaveCount(Math.min(20, bundle.total));
await expect(rows.first().locator('a').first()).toHaveText(first);
await page.getByRole('button', { name: 'Siguiente' }).click();
await expect(page.getByText(/Página 2 de \d+, \d+ registros/)).toBeVisible();
await page.getByRole('button', { name: 'Anterior' }).click();
await rows.first().locator('a').first().click();
await expect(page.getByText('Historial médico')).toBeVisible();
await expect(page.getByText('Pruebas y resultados')).toBeVisible();
await expect(
page.locator('app-paciente table').nth(1).locator('tbody tr').first(),
).not.toContainText('Sin estudios');
await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible();
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click();
const camaRows = page.locator('table.worklist tbody tr');
await expect(camaRows.first()).toContainText('BI-RADS');
await page.goto('/indicadores/tea');
await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
expect(problems).toEqual([]);
});
test('conectar: open the hospital pipeline, preview a source, run it to success', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible();
// a node's caption: its kind, then its name
await page.locator('.node-caption', { hasText: 'Pacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page;
await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
.click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await expect
.poll(() =>
page
.locator('app-concept-map-editor input')
.evaluateAll((els) => els.map((e) => (e as HTMLInputElement).value)),
)
.toContain('LIEAG');
await page.getByRole('button', { name: 'Ejecutar' }).click();
await expect(page.getByText('SUCCESS')).toBeVisible({ timeout: 10 * 60_000 });
expect(problems).toEqual([]);
});
test('revision: what the hospital source holds, and a decision through the page', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/revision');
await page.getByRole('tab', { name: 'Personas' }).click();
await page.locator('mat-form-field', { hasText: 'Canalización' }).click();
await page.getByRole('option', { name: 'site', exact: true }).click();
await expect(page.getByText(/Posibles pacientes duplicadas \([1-9]/)).toBeVisible();
await page.getByRole('button', { name: 'Distintas' }).first().click();
await expect(page.getByText('Decisión registrada.')).toBeVisible();
expect(problems).toEqual([]);
});
test('gobernanza: a version with its reports, its curves, and promotion refused without validation', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/gobernanza/cama');
await expect(page.getByRole('heading', { name: 'Supervivencia' })).toBeVisible();
const version = page.locator('tr', { hasText: 'v1' });
await expect(version.getByRole('link', { name: 'Validación técnica' })).toBeVisible();
await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
});
test('conectar: someone who knows nothing of databases connects the SQL Server with the dialog', async ({
page,
}) => {
const site = new URL((process.env['SITE_URL'] ?? '').replace(/^mssql\+pymssql/, 'http'));
const problems = watch(page);
await page.goto('/conectar');
await page.getByLabel('Nueva canalización').fill('asistente');
await page.getByLabel('Nueva canalización').press('Enter');
await page.getByRole('button', { name: 'Fuente de datos' }).click();
await expect(page.getByText('¿Dónde están los datos?')).toBeVisible();
await page.locator('[data-type="sqlserver"]').click();
await page.locator('[data-field="host"]').fill(site.hostname);
await page.locator('[data-field="database"]').fill(site.pathname.slice(1));
await page.locator('[data-field="user"]').fill(decodeURIComponent(site.username));
await page.locator('[data-field="password"]').fill(decodeURIComponent(site.password));
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText('Conexión correcta: 1 tabla.')).toBeVisible();
await page.locator('mat-select[data-field="table"]').click();
await page.getByRole('option', { name: 'ResultadoSubrogado' }).click();
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it');
await page.getByRole('button', { name: 'Probar conexión' }).click();
await expect(page.getByText(/usuario o la contraseña no son correctos/)).toBeVisible();
await page.getByRole('button', { name: 'Cancelar' }).click();
await expect(page.getByRole('dialog')).toHaveCount(0);
await page.getByRole('button', { name: 'Guardar', exact: true }).click();
await expect(page.getByText('Versión 1 guardada.')).toBeVisible();
expect(problems).toEqual([]);
});
/** The old app's Indicadores tab as captured (tools/capture_pages.py): its headings from the
* opportunity section on, in order, and the kind of each plot (its traces' types). */
function captured(domain: string) {
const path = `../tests/fixtures/reference/${domain}/ui/pages.json`;
const tabs = JSON.parse(readFileSync(path, 'utf8')).tabs;
const items = (tabs['Indicadores'] ?? tabs['Resumen']) as any[]; // TEA's first tab is its summary
const from = items.findIndex((i) => i.text === 'Indicadores de oportunidad');
const old = items
.slice(from)
.filter((i) => ['h2', 'h3', 'plot'].includes(i.kind))
.filter((i) => !/^(cacu|cama|tea), /.test(i.text ?? '')); // a figure's machine caption
return domain === 'cacu' ? rearranged(old) : old;
}
/** CaCu follows the 4312 candidate where it left the old page: the route's times sit in the
* opportunity section, under its cards, and the cytology distribution is a table in the joint
* results card (its nested donut is not drawn any more). Nothing else of the old page moves. */
function rearranged(old: any[]) {
const route = old.findIndex((i) => i.text === 'Tiempos de la ruta del tamizaje');
const moved = old.splice(route, 2); // its heading and its plot
old.splice(
old.findIndex((i) => i.text === 'Indicadores clínicos'),
0,
moved[0],
moved[1],
);
// the nested donut and the chart titled "TOTAL por escenario clínico" (now a figure of the
// cytology section, under another title) are not headings of this page any more
return old.filter(
(i) =>
!/^(Distribución de resultados, |TOTAL por escenario clínico|Por resultado de la citología, |Resultado de la biopsia, )/.test(
i.text ?? '',
),
);
}
/** Sections this platform adds to an old page, by domain, in the order they appear. The old
* headings still have to appear, in their order; nothing else may appear (a figure's own
* `h3.figure-title` inside a measure's card is the card's, not a section). */
const ADDED: Record<string, string[]> = {
cacu: [
'Resultados de citología, VPH y biopsia',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Pacientes evaluadas por resultado de VPH (última muestra con resultado)',
'VPP tras colposcopía registrada',
],
};
/** The page's headings against the old page's: the old ones in order, plus only what ADDED names. */
function oldThenAdded(actual: string[], old: string[], added: string[]) {
const extra: string[] = [];
let found = 0;
for (const heading of actual) {
if (found < old.length && heading === old[found]) found++;
else extra.push(heading);
}
return { allOldInOrder: found === old.length, extra, added };
}
const period = (text: string) => text.replace(/, \d{4}-(S[12]|\d{2})$/, ', <periodo>');
const kindOf = (types: string[]) => [...new Set(types)].sort().join('+');
for (const domain of ['cacu', 'cama', 'tea']) {
test(`indicadores ${domain}: the old page's headings, in order, and the same kinds of plots`, async ({
page,
}) => {
const old = captured(domain);
await page.goto(`/indicadores/${domain}`);
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
// textContent: a heading inside a collapsed section (CaCu's original confirmation measure)
// is still a heading of the page, though the browser gives it no rendered text.
const headings = await tab
.locator('h2, h3:not(.figure-title)')
.evaluateAll((els) => els.map((e) => (e.textContent ?? '').replace(/\s+/g, ' ').trim()));
const from = headings.indexOf('Indicadores de oportunidad');
const seen = oldThenAdded(
headings.slice(from).map(period),
old.filter((i) => i.kind !== 'plot').map((i) => period(i.text)),
ADDED[domain] ?? [],
);
expect(seen.allOldInOrder).toBe(true);
expect(seen.extra).toEqual(seen.added);
// Each figure drawn is one of the old kinds (a figure with no data in the period is named).
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`trazabilidad ${domain}: the old tab's panels, in order, and the same kinds of plots`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Trazabilidad'] as any[]).filter((i) =>
['h2', 'h3', 'plot'].includes(i.kind),
);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Trazabilidad' }).click();
const tab = page.locator('app-tab-trazabilidad');
await expect(tab.getByRole('heading', { name: 'Filtros' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old.filter((i) => i.kind !== 'plot').map((i) => i.text));
const drawn = await tab
.locator('.js-plotly-plot')
.evaluateAll((els) =>
els.map((e: any) => (e.data ?? []).map((t: any) => t.type ?? 'scatter')),
);
const kinds = new Set(
old.filter((i) => i.kind === 'plot').map((i) => kindOf(i.traces.map((t: any) => t.type))),
);
for (const types of drawn) expect(kinds).toContain(kindOf(types));
});
}
for (const domain of ['cacu', 'cama', 'tea']) {
test(`datos y definiciones ${domain}: the old tab's headings and an indicator that opens`, async ({
page,
}) => {
const tabs = JSON.parse(
readFileSync(`../tests/fixtures/reference/${domain}/ui/pages.json`, 'utf8'),
).tabs;
const old = (tabs['Datos y definiciones'] as any[])
.filter((i) => ['h2', 'h3'].includes(i.kind))
.map((i) => i.text);
await page.goto(`/indicadores/${domain}`);
await page.getByRole('tab', { name: 'Datos y definiciones' }).click();
const tab = page.locator('app-tab-definiciones');
await expect(tab.getByRole('heading', { name: 'Catálogo de indicadores' })).toBeVisible();
const headings = await tab
.locator('h2, h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings).toEqual(old);
await tab.locator('summary').first().click();
await expect(
tab.getByRole('heading', { name: 'Tipos de periodo admitidos' }).first(),
).toBeVisible();
});
}
test('indicadores cacu: the route in three readings, the new sections in theirs, and no as-of asked', async ({
page,
}) => {
const asked: string[] = [];
page.on('request', (r) => r.url().includes('as-of') && asked.push(r.url()));
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible();
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
// cumulative (the default), step by step with its warning and quartiles, and by ICD-10
// the route's times are in the opportunity section, after its cards and before the clinical ones
const opportunity = tab.locator('section.opportunity');
await expect(opportunity.locator('.route-card')).toBeVisible();
await expect(tab.locator('section.clinical-page .route-card')).toHaveCount(0);
expect(
await opportunity.evaluate((el) => {
const kpis = el.querySelector('.kpis')!;
const card = el.querySelector('.route-card')!;
return !!(kpis.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING);
}),
).toBe(true);
await expect(tab.getByRole('radio', { name: 'Acumulado desde la toma' })).toBeVisible();
await tab.getByRole('radio', { name: 'Por pasos' }).click();
// by steps: independent bars from zero in a table, every step kept, and the medians not added
const steps = tab.getByRole('table', { name: 'Tiempos por tramo de la ruta del tamizaje' });
await expect(steps).toBeVisible();
await expect(steps.locator('tbody tr')).toHaveCount(4);
await expect(tab.getByText('por lo que las medianas no se suman')).toBeVisible();
await expect(opportunity.locator('.js-plotly-plot')).toHaveCount(0);
await tab.getByRole('radio', { name: 'Desglose por CIE-10' }).click();
await expect(tab.getByText('no confirma un vínculo clínico')).toBeVisible();
await tab.getByRole('radio', { name: 'Acumulado desde la toma' }).click();
await expect(tab.getByText('Las marcas indican el primer y tercer cuartil')).toBeVisible();
await expect(tab.getByRole('table', { name: 'Tiempos de la ruta del tamizaje' })).toBeVisible();
// the sections of the new measures: each one in the place of its subject
for (const measure of [
'CACU_VPH_GENOTIPO',
'CACU_VPH',
'CACU_BIOPSIA_RESULTADOS',
'CACU_VPP_COLPOSCOPIA',
])
await expect(tab.locator(`[data-measure="${measure}"]`)).toBeVisible();
// a PPV says what it is and what it is not
await expect(
tab
.locator('[data-measure="CACU_VPP_COLPOSCOPIA"]')
.getByText('no un vínculo clínico confirmado'),
).toBeVisible();
// the joint card: cytology and HPV side by side, the biopsy below across the width, no nested donut
const joint = tab.locator('.results-card');
const [cyto, hpv, biopsy] = await Promise.all(
['CACU_EU7', 'CACU_VPH_GENOTIPO', 'CACU_BIOPSIA_RESULTADOS'].map((m) =>
joint.locator(`section[data-measure="${m}"]`).boundingBox(),
),
);
expect(Math.abs(cyto!.y - hpv!.y)).toBeLessThan(2);
expect(cyto!.x).toBeLessThan(hpv!.x);
expect(biopsy!.y).toBeGreaterThan(cyto!.y + cyto!.height - 1);
expect(biopsy!.width).toBeGreaterThan(cyto!.width * 1.8);
await expect(
joint.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(joint.getByText('Menor que LIEAG')).toBeVisible();
await expect(joint.getByText('LIEAG o más')).toBeVisible();
// three HPV categories are not listed, and the page says so only when it has such reports
const hpvRows = await joint
.locator('section[data-measure="CACU_VPH_GENOTIPO"] tbody th')
.allInnerTexts();
for (const hidden of ['genotipificación incompleta', 'Indeterminado', 'No clasificable'])
expect(hpvRows.join('|')).not.toContain(hidden);
// the cytology column reads one way at a time: the general table, or the clinical scenarios
const cytology = joint.locator('section[data-measure="CACU_EU7"]');
await expect(cytology.getByRole('radio', { name: 'Distribución general' })).toBeChecked();
await expect(cytology.locator('.js-plotly-plot')).toHaveCount(0);
await cytology.getByRole('radio', { name: 'Por escenario clínico' }).click();
await expect(cytology.locator('.js-plotly-plot')).toBeVisible();
await expect(cytology.getByRole('table')).toHaveCount(0);
await expect(
cytology.getByText('estatus de seguimiento de cada paciente al inicio del periodo'),
).toBeVisible();
await expect(cytology.locator('.legend li')).toHaveCount(6);
await cytology.getByRole('radio', { name: 'Distribución general' }).click();
await expect(
cytology.getByRole('table', { name: 'Distribución de resultados citológicos' }),
).toBeVisible();
await expect(
joint.locator('section[data-measure="CACU_VPH_GENOTIPO"] .js-plotly-plot'),
).toHaveCount(0);
await expect(tab.getByText('TOTAL por escenario clínico')).toHaveCount(0);
// the confirmation card: one perspective at a time, each with its own PPV and its readings
const confirmation = tab.locator('.confirmation-card');
await expect(
confirmation.getByRole('heading', { name: 'Tasa de confirmación histopatológica' }),
).toBeVisible();
await expect(confirmation.getByText('No son tasas de referencias emitidas')).toBeVisible();
await expect(confirmation.getByRole('radio', { name: 'Colposcopía', exact: true })).toBeChecked();
for (const [perspective, measure, title] of [
['Colposcopía', 'CACU_VPP_COLPOSCOPIA', 'VPP tras colposcopía registrada'],
['Biopsia', 'CACU_VPP_BIOPSIA', 'VPP tras biopsia registrada'],
]) {
await confirmation.getByRole('radio', { name: perspective, exact: true }).click();
await expect(confirmation.locator('app-ppv-card')).toHaveCount(1);
const ppv = confirmation.locator(`app-ppv-card[data-measure="${measure}"]`);
await expect(ppv.getByRole('heading', { name: title })).toBeVisible();
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
await expect(ppv.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
await expect(ppv.locator('.ppv-rows')).toHaveCount(0);
for (const mode of [
'Citología previa',
'VPH previo',
'Nivel de histología',
'Ronda de tamizaje',
]) {
await ppv.getByRole('radio', { name: mode, exact: true }).click();
await expect(ppv.getByRole('table', { name: mode })).toBeVisible();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(0);
await expect(ppv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
// the score line and the methodological note stay in view in every reading
await expect(ppv.locator('.measure-score')).toContainText('IC 95 %');
await expect(ppv.getByText('no un vínculo clínico confirmado')).toBeVisible();
}
await ppv.getByRole('radio', { name: 'Total' }).click();
await expect(ppv.locator('.js-plotly-plot')).toHaveCount(1);
}
// the biopsy requests are one more reading of the biopsy perspective, with their own heading
const biopsyPpv = confirmation.locator('app-ppv-card[data-measure="CACU_VPP_BIOPSIA"]');
await expect(
biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }),
).toBeVisible();
await biopsyPpv.getByRole('radio', { name: 'Solicitudes de biopsia', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'Confirmación por solicitudes de biopsia registradas' }),
).toBeVisible();
await expect(biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' })).toHaveCount(
0,
);
await expect(biopsyPpv.locator('.measure-score')).toContainText(
'solicitudes registradas (no pacientes)',
);
await expect(
biopsyPpv.getByText('La tasa de referencias emitidas no está disponible'),
).toBeVisible();
await expect(biopsyPpv.getByText('no se pide un corte histórico (as-of)')).toBeVisible();
await expect(biopsyPpv.getByRole('table', { name: 'Solicitudes de biopsia' })).toBeVisible();
await expect(biopsyPpv.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(biopsyPpv.getByText('Pendientes:')).toContainText('Registros fusionados ambiguos');
await expect(biopsyPpv.locator('.js-plotly-plot')).toHaveCount(0);
await biopsyPpv.getByRole('radio', { name: 'Total', exact: true }).click();
await expect(
biopsyPpv.getByRole('heading', { name: 'VPP tras biopsia registrada' }),
).toBeVisible();
// the original confirmation measure is not shown on this tab any more
await expect(confirmation.locator('details')).toHaveCount(0);
await expect(tab.getByText('medida original')).toHaveCount(0);
await expect(tab.getByText('Denominador: ')).toHaveCount(0);
// the tabs are short and the full explanation is in the tab's content
await confirmation.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = confirmation.locator('app-ppv-card');
await colposcopy.getByRole('radio', { name: 'Citología previa', exact: true }).click();
await expect(colposcopy.locator('.ppv-caption').first()).toContainText('asociada por fechas');
await expect(colposcopy.getByRole('radio')).toHaveCount(5);
const tops = await colposcopy
.locator('mat-button-toggle')
.evaluateAll((els) => new Set(els.map((x) => Math.round(x.getBoundingClientRect().top))).size);
expect(tops).toBe(1); // one line on desktop
// the patients by HPV result: the whole as a donut, then one breakdown at a time
const vph = tab.locator('app-ppv-card[data-measure="CACU_VPH"]');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
await expect(vph.getByText('Es distinto de los reportes de VPH por genotipo')).toBeVisible();
await expect(vph.getByRole('radio', { name: 'Total' })).toBeChecked();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
for (const mode of [
'Por grupo de edad',
'Por estatus de seguimiento',
'Por genotipo',
'Por tamizaje inicial o subsecuente',
]) {
await vph.getByRole('radio', { name: mode, exact: true }).click();
await expect(vph.getByRole('table', { name: mode })).toBeVisible();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(0);
await expect(vph.locator('.ppv-row:not(.ppv-head)').first()).toContainText('/');
await expect(vph.locator('.measure-score')).toContainText('pacientes');
}
await vph.getByRole('radio', { name: 'Total' }).click();
await expect(vph.locator('.js-plotly-plot')).toHaveCount(1);
// the two HPV measures are told apart: reports against patients
await expect(tab.locator('[data-measure="CACU_VPH"]')).toContainText(
'Pacientes evaluadas por resultado de VPH',
);
await expect(tab.locator('[data-measure="CACU_VPH_GENOTIPO"]')).toContainText(
'Cuenta reportes, no pacientes',
);
expect(asked).toEqual([]);
});
test('riesgos cacu: age and stages on the list, its filters, its exports, and the record', async ({
page,
}) => {
const problems = watch(page);
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const rows = page.locator('table.worklist tbody tr:not(.stage-panel)');
await expect(rows.first().locator('a')).toBeVisible();
const total = async () =>
Number(
/(\d+) registros/.exec((await page.locator('.pager .muted').innerText()) ?? '')?.[1] ?? 0,
);
// her age at the cut-off, and the stages: a compact line with a chevron that opens the panel
await expect(page.getByRole('columnheader', { name: 'Edad', exact: true })).toBeVisible();
await expect(rows.first().locator('app-stages .node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Mostrar etapas' }).click();
const panel = page.locator('tr.stage-panel');
await expect(panel).toContainText('Toma de muestra');
await expect(panel).toContainText('Desde anterior');
await expect(panel.locator('.node')).toHaveCount(5);
await rows.first().getByRole('button', { name: 'Ocultar etapas' }).click();
await expect(panel).toHaveCount(0);
// the age filters apply before the page is cut; the name search of Rebuild is still there
const all = await total();
await page.getByLabel('Edad mínima').fill('200');
await expect(page.getByText('Indique edades enteras entre 0 y 150')).toBeVisible();
await page.getByLabel('Edad mínima').fill('45');
await expect(async () => expect(await total()).toBeLessThan(all)).toPass();
await expect(page.getByRole('searchbox', { name: 'Buscar paciente' })).toBeVisible();
await page.getByRole('button', { name: 'Limpiar edades' }).click();
await expect(async () => expect(await total()).toBe(all)).toPass();
// the whole query, as the two files
const [pdf] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar PDF' }).click(),
]);
expect(pdf.suggestedFilename()).toBe('cacu-reporte.pdf');
expect(
readFileSync((await pdf.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
const [xlsx] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar Excel (.xlsx)' }).click(),
]);
expect(xlsx.suggestedFilename()).toBe('cacu-seguimiento.xlsx');
expect(
readFileSync((await xlsx.path())!)
.subarray(0, 2)
.toString(),
).toBe('PK');
// her record: age, the detailed stages, the scales, and the file
await rows.first().locator('a').first().click();
await expect(page.getByRole('heading', { level: 1 })).toContainText('Edad:');
await expect(page.locator('app-paciente app-stages .node')).toHaveCount(5);
await expect(page.getByText('Desde toma:').first()).toBeVisible();
await expect(page.getByText('Riesgo inmediato')).toBeVisible();
await expect(page.getByText('Riesgo a 5 años')).toBeVisible();
const [ficha] = await Promise.all([
page.waitForEvent('download'),
page.getByRole('button', { name: 'Exportar ficha PDF' }).click(),
]);
expect(
readFileSync((await ficha.path())!)
.subarray(0, 5)
.toString(),
).toBe('%PDF-');
expect(problems).toEqual([]);
});
/** Waits for a page's data: no loading indicator left. */
async function loaded(page: Page): Promise<void> {
await expect(page.locator('app-loading, mat-progress-bar')).toHaveCount(0, {
timeout: 5 * 60_000,
});
await page.waitForTimeout(1000); // plots finish drawing
}
for (const width of [1440, 820]) {
test(`layout at ${width} px: no page has overlapping, clipped or wrapped labels`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const found: string[] = [];
const check = async (where: string) => {
await loaded(page);
for (const p of await layoutProblems(page)) found.push(`${where}: ${p}`);
};
for (const domain of ['cacu', 'cama', 'tea']) {
await page.goto(`/indicadores/${domain}`);
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`${domain} tab ${i + 1}`);
}
// the record of the risk list's first patient
await tabs.nth(2).click();
await loaded(page);
const first = page.locator('table a[href*="/pacientes/"]').first();
if (await first.count()) {
await first.click();
await check(`${domain} record`);
}
await page.goto(`/gobernanza/${domain}`);
await check(`${domain} gobernanza`);
}
await page.goto('/conectar');
await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision');
const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) {
await tabs.nth(i).click();
await check(`revision tab ${i + 1}`);
}
expect(found).toEqual([]);
});
}