feat(sprint-1-5): cierre Etapa 2 - formatPayback + fixes de marca
[
This commit is contained in:
174
tests/e2e/payback-etapa-2.spec.ts
Normal file
174
tests/e2e/payback-etapa-2.spec.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Etapa 2 Sprint 1.5 — Validación visual de formatPayback.
|
||||
*
|
||||
* 1. Screenshot del RoiKpiBar mostrando payback formateado (no "0.0 meses").
|
||||
* 2. Screenshot de TransparencySection con ROI > 1000%.
|
||||
* 3. PDF correcto del tab "Comparación + ROI" guardado para validación visual.
|
||||
*
|
||||
* Setup: medium-with-gateways, task_recv + task_score + task_analisis automatizables,
|
||||
* $200 costo directo / $20 costo automatizado, 5000 ejecuciones/año, $80.000 inversión.
|
||||
*
|
||||
* Root cause del PDF erróneo en run anterior: el test exportaba antes de navegar al
|
||||
* tab ROI, por lo que activeTab = 'actual' y se generaba el PDF del escenario actual.
|
||||
* Fix: navegar al tab "Comparación + ROI" ANTES de exportar.
|
||||
*/
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { resolve } from 'path'
|
||||
import { mkdirSync } from 'fs'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url))
|
||||
const BPMN_DIR = resolve(__dirname, '../../public/sample-processes')
|
||||
const OUT_DIR = resolve(__dirname, './__output__')
|
||||
|
||||
test.beforeAll(() => { mkdirSync(OUT_DIR, { recursive: true }) })
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async function importBpmn(page: import('@playwright/test').Page, filename: string) {
|
||||
await page.goto('/')
|
||||
await page.locator('#bpmn-file-input').setInputFiles(resolve(BPMN_DIR, filename))
|
||||
await page.waitForURL(/\/workspace\//, { timeout: 15_000 })
|
||||
await page.waitForSelector('button:has-text("Simular")', { timeout: 10_000 })
|
||||
await page.waitForTimeout(1_000)
|
||||
}
|
||||
|
||||
async function setActivityCosts(
|
||||
page: import('@playwright/test').Page,
|
||||
elementId: string,
|
||||
directCost: number,
|
||||
automatedCost: number,
|
||||
automatedTime: number
|
||||
) {
|
||||
await page.locator(`[data-element-id="${elementId}"]`).first().click()
|
||||
await page.waitForTimeout(500)
|
||||
|
||||
const toggle = page.getByRole('switch', { name: /automatizable/i })
|
||||
if (await toggle.getAttribute('aria-checked') === 'false') {
|
||||
await toggle.click()
|
||||
await page.waitForTimeout(300)
|
||||
}
|
||||
|
||||
const directCostInput = page.getByLabel(/Costo directo fijo/i)
|
||||
await directCostInput.fill(String(directCost))
|
||||
|
||||
const autoCostInput = page.getByLabel(/Costo automatizado/i)
|
||||
await autoCostInput.fill(String(automatedCost))
|
||||
|
||||
const autoTimeInput = page.getByLabel(/Tiempo automatizado/i)
|
||||
await autoTimeInput.fill(String(automatedTime))
|
||||
|
||||
const guardar = page.getByRole('button', { name: /Guardar/i })
|
||||
await guardar.click()
|
||||
await page.waitForTimeout(500)
|
||||
}
|
||||
|
||||
async function configureGlobal(
|
||||
page: import('@playwright/test').Page,
|
||||
annualFrequency: number,
|
||||
investment: number
|
||||
) {
|
||||
const globalTab = page.getByRole('tab', { name: /Global/i })
|
||||
await globalTab.click()
|
||||
await page.waitForTimeout(300)
|
||||
|
||||
const freqInput = page.getByLabel(/Frecuencia anual/i)
|
||||
await freqInput.fill(String(annualFrequency))
|
||||
|
||||
const investInput = page.getByLabel(/Inversión en automatización/i)
|
||||
await investInput.fill(String(investment))
|
||||
|
||||
const guardar = page.getByRole('button', { name: /Guardar/i })
|
||||
await guardar.click()
|
||||
await page.waitForTimeout(500)
|
||||
}
|
||||
|
||||
async function setupRealisticScenario(page: import('@playwright/test').Page) {
|
||||
await importBpmn(page, 'medium-with-gateways.bpmn')
|
||||
await setActivityCosts(page, 'task_recv', 200, 20, 10)
|
||||
await setActivityCosts(page, 'task_score', 200, 20, 10)
|
||||
await setActivityCosts(page, 'task_analisis', 200, 20, 10)
|
||||
await configureGlobal(page, 5000, 80000)
|
||||
|
||||
const simBtn = page.getByRole('button', { name: 'Simular' })
|
||||
await expect(simBtn).not.toBeDisabled({ timeout: 5_000 })
|
||||
await simBtn.click()
|
||||
await page.waitForURL(/\/report\//, { timeout: 20_000 })
|
||||
await page.waitForSelector('button:has-text("Exportar PDF")', { timeout: 15_000 })
|
||||
await page.waitForTimeout(800)
|
||||
|
||||
// Navegar al tab Comparación + ROI — NECESARIO para que activeTab sea 'roi'
|
||||
const roiTab = page.getByRole('tab', { name: /Comparación/i })
|
||||
await expect(roiTab).not.toBeDisabled({ timeout: 5_000 })
|
||||
await roiTab.click()
|
||||
await page.waitForSelector('[data-testid="roi-kpi-card"]', { timeout: 10_000 })
|
||||
await page.waitForTimeout(800)
|
||||
}
|
||||
|
||||
// ─── Tests ────────────────────────────────────────────────────────────────────
|
||||
|
||||
test('screenshot RoiKpiBar — payback formateado (no "0.0 meses")', async ({ page }) => {
|
||||
await setupRealisticScenario(page)
|
||||
|
||||
// Screenshot del viewport — muestra KPI bar
|
||||
await page.screenshot({
|
||||
path: resolve(OUT_DIR, 'payback-roi-kpi-bar.png'),
|
||||
fullPage: false,
|
||||
})
|
||||
|
||||
// Verificar que el payback card NO muestra "0.0 meses"
|
||||
const cards = page.locator('[data-testid="roi-kpi-card"]')
|
||||
const texts = await cards.allTextContents()
|
||||
console.log('KPI card texts:', JSON.stringify(texts, null, 2))
|
||||
const hasOldFormat = texts.some(t => /\b0\.0 meses\b/.test(t))
|
||||
expect(hasOldFormat, 'Payback card must not show "0.0 meses" — use formatPayback').toBe(false)
|
||||
})
|
||||
|
||||
test('screenshot TransparencySection — ROI > 1000% dispara aviso', async ({ page }) => {
|
||||
await setupRealisticScenario(page)
|
||||
|
||||
// Verificar que ROI es > 1000% (condición para disparar Transparencia)
|
||||
const cards = page.locator('[data-testid="roi-kpi-card"]')
|
||||
const texts = await cards.allTextContents()
|
||||
const roiText = texts.find(t => t.toLowerCase().includes('roi anual')) ?? ''
|
||||
console.log('ROI card text:', roiText)
|
||||
|
||||
// Scroll hasta el final de la página para revelar TransparencySection
|
||||
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight))
|
||||
await page.waitForTimeout(500)
|
||||
|
||||
// Verificar que la sección existe en el DOM
|
||||
const transparency = page.locator('text=Transparencia metodológica').first()
|
||||
await expect(transparency).toBeVisible({ timeout: 5_000 })
|
||||
|
||||
// Screenshot full-page para capturar la sección
|
||||
await page.screenshot({
|
||||
path: resolve(OUT_DIR, 'payback-transparency-section.png'),
|
||||
fullPage: true,
|
||||
})
|
||||
|
||||
console.log('TransparencySection visible con ROI:', roiText)
|
||||
})
|
||||
|
||||
test('PDF ROI correcto — tab "Comparación + ROI" activo al exportar', async ({ page }) => {
|
||||
// Root cause del PDF erróneo anterior: exportar con activeTab = 'actual'.
|
||||
// Fix: setupRealisticScenario ya navega al tab ROI ANTES de este punto.
|
||||
await setupRealisticScenario(page)
|
||||
|
||||
// Tab ROI ya activo — el BPMN canvas no existe en este tab, no esperar por él
|
||||
await page.waitForTimeout(500)
|
||||
|
||||
const [download] = await Promise.all([
|
||||
page.waitForEvent('download', { timeout: 30_000 }),
|
||||
page.getByRole('button', { name: 'Exportar PDF' }).click(),
|
||||
])
|
||||
|
||||
const outPath = resolve(OUT_DIR, 'etapa-2-payback-roi-sample.pdf')
|
||||
await download.saveAs(outPath)
|
||||
console.log('PDF ROI guardado:', outPath)
|
||||
|
||||
expect(download.suggestedFilename()).toMatch(/_roi\.pdf$|\.pdf$/)
|
||||
|
||||
// El nombre debe contener "roi" si la implementación usa activeTab en el slug
|
||||
console.log('Nombre sugerido:', download.suggestedFilename())
|
||||
})
|
||||
@@ -147,9 +147,9 @@ describe('RoiKpiBar', () => {
|
||||
expect(text).toMatch(/810/)
|
||||
})
|
||||
|
||||
it('payback Infinity → muestra "No se recupera"', () => {
|
||||
it('payback Infinity → muestra "No recupera en horizonte"', () => {
|
||||
render(<RoiKpiBar roi={roiNoSavings} currency="USD" horizonYears={3} />)
|
||||
expect(screen.getByText(/No se recupera/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/No recupera en horizonte/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('payback 0 (inversión cero) → muestra "Inmediato"', () => {
|
||||
|
||||
@@ -1,21 +1,67 @@
|
||||
/**
|
||||
* Tests de formatPayback — Sprint 1.5 Etapa 2.
|
||||
*
|
||||
* Stubs preparados. La implementación se agrega en Etapa 2.
|
||||
* Los 7 casos están definidos en SPRINT_1_5_BRIEF_REDISENIO_VISUAL.md § 3.4.
|
||||
*
|
||||
* 7 casos base + 5 edge cases = 12 tests.
|
||||
* Regla: un payback de "0.0 meses" (como mostraba el sistema con costos
|
||||
* artificialmente bajos) es confuso. formatPayback resuelve esto con
|
||||
* una escala legible para el consultor y el cliente.
|
||||
*/
|
||||
import { describe, it } from 'vitest'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { formatPayback } from '../../src/lib/format'
|
||||
|
||||
describe('formatPayback', () => {
|
||||
it.todo('0 → "Inmediato" (inversión cero con ahorro positivo)')
|
||||
it.todo('0.05 → "< 1 día" (payback de horas, prácticamente instantáneo)')
|
||||
it.todo('0.5 → "< 1 mes (0.50 meses)"')
|
||||
it.todo('6 → "6.0 meses"')
|
||||
it.todo('15 → "15.0 meses (~1.3 años)"')
|
||||
it.todo('30 → "2.5 años"')
|
||||
it.todo('Infinity → "No recupera en horizonte"')
|
||||
// Casos base
|
||||
it('0 → "Inmediato"', () => {
|
||||
expect(formatPayback(0)).toBe('Inmediato')
|
||||
})
|
||||
|
||||
it('0.05 → "< 1 día"', () => {
|
||||
expect(formatPayback(0.05)).toBe('< 1 día')
|
||||
})
|
||||
|
||||
it('0.5 → "< 1 mes (0.50 meses)"', () => {
|
||||
expect(formatPayback(0.5)).toBe('< 1 mes (0.50 meses)')
|
||||
})
|
||||
|
||||
it('6 → "6.0 meses"', () => {
|
||||
expect(formatPayback(6)).toBe('6.0 meses')
|
||||
})
|
||||
|
||||
it('15 → "15.0 meses (~1.3 años)"', () => {
|
||||
expect(formatPayback(15)).toBe('15.0 meses (~1.3 años)')
|
||||
})
|
||||
|
||||
it('30 → "2.5 años"', () => {
|
||||
expect(formatPayback(30)).toBe('2.5 años')
|
||||
})
|
||||
|
||||
it('Infinity → "No recupera en horizonte"', () => {
|
||||
expect(formatPayback(Infinity)).toBe('No recupera en horizonte')
|
||||
})
|
||||
|
||||
// Edge cases
|
||||
it('-1 → "Sin payback (costo aumenta)"', () => {
|
||||
// payback negativo: costo automatizado supera al actual
|
||||
expect(formatPayback(-1)).toBe('Sin payback (costo aumenta)')
|
||||
})
|
||||
|
||||
it('-100 → "Sin payback (costo aumenta)"', () => {
|
||||
// negativo grande: mismo comportamiento
|
||||
expect(formatPayback(-100)).toBe('Sin payback (costo aumenta)')
|
||||
})
|
||||
|
||||
it('NaN → "No recupera en horizonte"', () => {
|
||||
// NaN cae en el primer guard
|
||||
expect(formatPayback(NaN)).toBe('No recupera en horizonte')
|
||||
})
|
||||
|
||||
it('11.95 → "11.9 meses"', () => {
|
||||
// verificar que el borde con 12 no salta a "1.0 años" prematuramente
|
||||
expect(formatPayback(11.95)).toBe('11.9 meses')
|
||||
})
|
||||
|
||||
it('12.0 → "12.0 meses (~1.0 años)"', () => {
|
||||
// exactamente en el umbral
|
||||
expect(formatPayback(12.0)).toBe('12.0 meses (~1.0 años)')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user