Files
WebApp/e2e/cacu.spec.ts
T
2026-12-02 14:09:02 -06:00

344 lines
14 KiB
TypeScript

import { expect, type Locator, type Page, test } from '@playwright/test';
import { layoutProblems } from './layout';
import { type Simulation, simulateRounds } from './simulated-rounds';
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);
});
const ROUND = { name: 'Por detección inicial y subsecuente' };
const VIEWS_LABEL = 'Lectura de la distribución citológica y del VPH por genotipo';
const VIEWS = ['General', 'Por grupo de edad', 'Por estatus de seguimiento', ROUND.name];
const TITLES = {
cytology: 'Distribución de resultados citológicos',
genotype: 'Resultados de VPH por genotipo',
biopsy: 'Resultados de biopsia cervical',
colposcopy: 'Valor predictivo positivo de la colposcopía',
ppvBiopsy: 'Valor predictivo positivo de la biopsia',
};
test('indicadores cacu: its sections in order, each card read one mode at a time', async ({
page,
}) => {
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 });
const headings = await tab
.locator('h2, app-readings h3')
.evaluateAll((els) => els.map((e) => (e as HTMLElement).innerText.trim()));
expect(headings.slice(headings.indexOf('Indicadores de oportunidad'))).toEqual([
'Indicadores de oportunidad',
'Tiempos de la ruta del tamizaje',
'Indicadores clínicos',
'Resultados de citología, VPH y biopsia',
'Distribución de resultados citológicos',
'Resultados de VPH por genotipo',
'Resultados de biopsia cervical',
'Tasa de confirmación histopatológica',
'Valor predictivo positivo de la colposcopía',
]);
const route = tab.locator('app-readings').first();
for (const mode of ['Por pasos', 'Por CIE-10', 'Acumulado desde la toma']) {
await route.getByRole('radio', { name: mode }).click();
await expect(
route.getByRole('table', { name: mode }).or(route.getByText('Sin datos en el periodo.')),
).toBeVisible();
}
// one selector for the cytology distribution and the HPV by genotype; the biopsy card is apart
await expect(
tab.locator('app-readings', {
has: page.getByRole('heading', { name: 'Pacientes evaluadas por resultado de VPH' }),
}),
).toHaveCount(0);
const views = tab.getByRole('radiogroup', { name: VIEWS_LABEL });
await expect(views.getByRole('radio')).toHaveText(VIEWS);
await expect(views.getByRole('radio', { name: 'General' })).toBeChecked();
await expect(tab.getByRole('radio', { name: 'Por escenario clínico' })).toHaveCount(0);
for (const view of VIEWS.slice(1)) {
await views.getByRole('radio', { name: view }).click();
for (const card of [TITLES.cytology, TITLES.genotype]) {
const readings = tab.locator('app-readings', {
has: page.getByRole('heading', { name: card }),
});
// each card has no toggle of its own: the selector drives both
await expect(readings.getByRole('radio')).toHaveCount(0);
// no long description beside the bars: the cards read from their title, note and legend
await expect(readings).not.toContainText(
/Cada barra|Cada paciente cuenta una vez|«Detección inicial»|una barra vacía|«Positivo»/,
);
await expect(
readings
.locator('.group')
.first()
.or(readings.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
}
}
const biopsyCard = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.biopsy }),
});
await expect(biopsyCard.getByRole('radio')).toHaveCount(0);
await views.getByRole('radio', { name: 'General' }).click();
await expect(
tab
.locator('app-readings', { has: page.getByRole('heading', { name: TITLES.cytology }) })
.getByRole('table'),
).toBeVisible();
// the PPV cards keep their round tab, in the same words and order
await tab.getByRole('radio', { name: 'Colposcopía', exact: true }).click();
const colposcopy = tab.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.colposcopy }),
});
await colposcopy.getByRole('radio', ROUND).click();
await expect(
colposcopy
.getByRole('table', ROUND)
.or(colposcopy.getByText(/No disponible|Sin datos en el periodo/)),
).toBeVisible();
await tab.getByRole('radio', { name: 'Biopsia', exact: true }).click();
await tab
.locator('app-readings', {
has: page.getByRole('heading', { name: TITLES.ppvBiopsy }),
})
.getByRole('radio', ROUND)
.click();
await expect(
tab.getByRole('heading', { name: 'Valor predictivo positivo de la biopsia' }),
).toBeVisible();
await tab.getByRole('radio', { name: 'Solicitudes' }).click();
});
test('riesgos cacu: ages filter the whole list and a row opens its stages', async ({ page }) => {
await page.goto('/indicadores/cacu');
await page.getByRole('tab', { name: 'Análisis de riesgos' }).click();
const list = page.locator('table.worklist tbody tr');
await expect(list.first().locator('app-stages li')).toHaveCount(5);
await list.first().getByRole('button', { name: 'Detalle' }).click();
await expect(page.locator('tr.stage-detail')).toContainText('Toma de muestra');
const answer = page.waitForResponse((r) => r.url().includes('birthdate=le'));
await page.getByLabel('Edad mínima').fill('45');
expect((await answer).ok()).toBe(true);
for (const age of await list.locator('td:nth-child(2)').allInnerTexts())
expect(parseInt(age)).toBeGreaterThanOrEqual(45);
for (const [button, file] of [
['Exportar Excel', 'seguimiento-cacu.xlsx'],
['Exportar PDF', 'seguimiento-cacu.pdf'],
]) {
const saved = page.waitForEvent('download');
await page.getByRole('button', { name: button }).click();
expect((await saved).suggestedFilename()).toBe(file);
}
await list.first().locator('a').first().click();
await expect(page.locator('[data-section=etapas]')).toContainText('Reporte de biopsia');
const record = page.waitForEvent('download');
await page.getByRole('button', { name: 'Exportar PDF' }).click();
expect((await record).suggestedFilename()).toBe('expediente-cacu.pdf');
});
// ---- Screening rounds on SIMULATED answers (see simulated-rounds.ts): the groups the contract of
// `rebuild` allows, tried on top of the API's own answers. They show how the page draws them, not the
// backend. The shared selector drives the cytology and the HPV-by-genotype cards; the PPV cards keep a tab.
const BAR = {
initial: 'rgb(95, 127, 154)',
subsequent: 'rgb(143, 167, 187)',
no_data: 'rgb(201, 205, 210)',
};
const GENOTYPE_COLOURS = {
Negativo: '#42A77E',
'VPH 16': '#DF8640',
'VPH 18': '#C29C42',
'VPH 16 y 18': '#C24269',
Positivo: '#A8C243',
};
const CYTOLOGY_COLOURS = {
Normal: '#408651',
'ASC-US': '#2778B8',
LIEBG: '#B19525',
'ASC-H': '#7955B1',
LIEAG: '#CE4778',
'Carcinoma in situ': '#AA394D',
};
async function withRounds(page: Page, how: Simulation) {
await simulateRounds(page, how);
await page.goto('/indicadores/cacu');
const tab = page.locator('app-tab-indicadores');
await expect(tab.getByRole('heading', { name: 'Indicadores clínicos' })).toBeVisible({
timeout: 3 * 60_000,
});
await expect(tab.locator('app-loading')).toHaveCount(0, { timeout: 5 * 60_000 });
const card = (title: string) =>
tab.locator('app-readings', { has: page.getByRole('heading', { name: title }) }).first();
const view = async (name: string) => {
await tab.getByRole('radiogroup', { name: VIEWS_LABEL }).getByRole('radio', { name }).click();
};
/** A PPV card on its round tab. */
const ppv = async (key: 'colposcopy' | 'ppvBiopsy') => {
await tab
.getByRole('radio', { name: key === 'colposcopy' ? 'Colposcopía' : 'Biopsia', exact: true })
.click();
const readings = card(TITLES[key]);
await readings.getByRole('radio', ROUND).click();
return readings;
};
return { tab, card, view, ppv };
}
/** The first group of independent bars of a card (the cytology and genotype breakdowns). */
const plotOf = (readings: Locator) => readings.locator('.group').first();
/** The groups of a card as the page draws them: "label<br>n = N", the width of the first bar and the colour of
* each category (the first group's rows), in hex. */
const traces = (readings: Locator) =>
readings.evaluate((el) => {
const hex = (rgb: string) =>
'#' +
(rgb.match(/\d+/g) ?? [])
.slice(0, 3)
.map((n) => Number(n).toString(16).padStart(2, '0'))
.join('')
.toUpperCase();
const groups = [...el.querySelectorAll('.group')];
return {
y: groups.map(
(g) =>
`${g.querySelector('h4')!.childNodes[0].textContent!.trim()}<br>n = ${g.querySelector('.n')!.textContent!.replace('n = ', '').trim()}`,
),
x: groups.map((g) => parseFloat((g.querySelector('.fill') as HTMLElement).style.width)),
colours: Object.fromEntries(
[...groups[0].querySelectorAll('.row')].map((r) => [
r.querySelector('.name')!.textContent!.trim(),
hex(getComputedStyle(r.querySelector('.fill')!).backgroundColor),
]),
),
};
});
for (const key of ['colposcopy', 'ppvBiopsy'] as const) {
test(`rondas (simulado) ${key}: three groups in order, each with its own colour`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'as-is');
const readings = await ppv(key);
const rows = readings.getByRole('row').filter({ has: page.getByRole('rowheader') });
await expect(rows).toHaveCount(3);
const names = await readings.getByRole('rowheader').allInnerTexts();
expect(names.map((n) => n.trim().split(/\s*\n\s*/)[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
const colours = await readings
.locator('tbody .bar')
.evaluateAll((els) => els.map((e) => getComputedStyle(e).backgroundColor));
expect(colours).toEqual([BAR.initial, BAR.subsequent, BAR.no_data]);
});
test(`rondas (simulado) ${key}: an empty initial group is zero patients, not hidden`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'no-initial');
const readings = await ppv(key);
const initial = readings.getByRole('row').filter({ hasText: 'Detección inicial' });
await expect(initial).toContainText('Sin pacientes en el periodo');
await expect(initial).toContainText('0/0');
});
test(`rondas (simulado) ${key}: without the stratum the card says it is not available`, async ({
page,
}) => {
const { ppv } = await withRounds(page, 'unpublished');
const readings = await ppv(key);
await expect(readings).toContainText('No disponible');
await expect(readings.getByRole('table', ROUND)).toHaveCount(0);
});
}
for (const card of ['cytology', 'genotype'] as const) {
test(`rondas (simulado) ${card}: the selector draws the rounds in order, with the category colours`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'as-is');
await view(ROUND.name);
const readings = of(TITLES[card]);
await expect(plotOf(readings)).toBeVisible();
const found = await traces(readings);
expect(found.y.map((l) => l.split('<br>')[0])).toEqual([
'Detección inicial',
'Detección subsecuente',
'Sin dato',
]);
expect(found.colours).toMatchObject(card === 'cytology' ? CYTOLOGY_COLOURS : GENOTYPE_COLOURS);
});
test(`rondas (simulado) ${card}: an empty initial group is an empty bar with its zero`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'no-initial');
await view(ROUND.name);
const found = await traces(of(TITLES[card]));
expect(found.y[0]).toBe('Detección inicial<br>n = 0');
expect(found.x[0]).toBe(0);
});
test(`rondas (simulado) ${card}: without the stratum the selector says it is not available`, async ({
page,
}) => {
const { card: of, view } = await withRounds(page, 'unpublished');
await view(ROUND.name);
await expect(of(TITLES[card])).toContainText('No disponible');
});
}
test('rondas (simulado): the genotype card never shows the incomplete positives, and carries no long description', async ({
page,
}) => {
const { card, view } = await withRounds(page, 'as-is');
const readings = card(TITLES.genotype);
await expect(readings).not.toContainText('«Positivo»');
await expect(readings).not.toContainText('Cada barra');
await expect(readings.getByRole('rowheader')).not.toContainText([
'Otro de alto riesgo',
'incompleto',
]);
const labels = await readings.getByRole('rowheader').allInnerTexts();
expect(labels.map((l) => l.trim())).toEqual([
'Negativo',
'VPH 16',
'VPH 18',
'VPH 16 y 18',
'Positivo',
]);
for (const name of VIEWS.slice(1)) {
await view(name);
const found = await traces(readings);
expect(Object.keys(found.colours)).toEqual(Object.keys(GENOTYPE_COLOURS));
}
});
for (const width of [1440, 480]) {
test(`rondas (simulado) at ${width} px: the shared selector on each view lays out cleanly`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 1000 });
const { view, ppv } = await withRounds(page, 'as-is');
for (const name of VIEWS) {
await view(name);
await page.waitForTimeout(1200);
// every option of the selector is inside the window (it wraps on a narrow screen)
for (const box of await page
.getByRole('radiogroup', { name: VIEWS_LABEL })
.getByRole('radio')
.evaluateAll((els) =>
els.map((e) => e.closest('mat-button-toggle')!.getBoundingClientRect().right),
))
expect(box).toBeLessThanOrEqual(width);
expect(await layoutProblems(page), name).toEqual([]);
}
await ppv('colposcopy');
await ppv('ppvBiopsy');
await page.waitForTimeout(1200);
expect(await layoutProblems(page)).toEqual([]);
});
}