feat: MVP Fase 0 — Process Cost Platform v0.1.0
Plataforma completa de análisis de costos operativos basada en BPMN 2.0. Funcionalidades incluidas: - Import de archivos BPMN 2.0 por drag & drop + 3 procesos de ejemplo - Visualización read-only del diagrama (bpmn-js) - Configuración de actividades (costo, tiempo, recursos asignados) - CRUD de recursos (rol, persona, sistema, equipo, insumo) - Configuración global (moneda, overhead %, nombre, cliente) - Motor de simulación determinístico agregado con propagación de gateways XOR/AND - Reporte visual con mapa de calor en dos modos (relativo/absoluto) - Gráficos: KPIs, top actividades, composición, costo por recurso - Export PDF (jsPDF + html2canvas) y CSV (papaparse) - Persistencia en IndexedDB (Dexie) - 268 tests unitarios/integración + 6 E2E con Playwright - Deploy: https://process-cost-platform.pages.dev Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
213
tests/lib/colors.test.ts
Normal file
213
tests/lib/colors.test.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
heatmapColorHex,
|
||||
computeActivityT,
|
||||
hasSignificantCostVariance,
|
||||
activityColor,
|
||||
NEUTRAL_HEATMAP_COLOR,
|
||||
type ActivityCostData,
|
||||
} from '@/lib/colors'
|
||||
|
||||
// ─── Fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeActs(costs: number[]): ActivityCostData[] {
|
||||
const total = costs.reduce((s, c) => s + c, 0) || 1
|
||||
return costs.map((c) => ({
|
||||
expectedTotalCost: Math.max(0, c),
|
||||
percentOfTotal: (c / total) * 100,
|
||||
}))
|
||||
}
|
||||
|
||||
// ─── heatmapColorHex ─────────────────────────────────────────────────────────
|
||||
describe('heatmapColorHex', () => {
|
||||
it('t=0 → verde (#10b981)', () => {
|
||||
expect(heatmapColorHex(0)).toBe('#10b981')
|
||||
})
|
||||
|
||||
it('t=1 → rojo (#ef4444)', () => {
|
||||
expect(heatmapColorHex(1)).toBe('#ef4444')
|
||||
})
|
||||
|
||||
it('t=0.5 → amarillo (#f59e0b)', () => {
|
||||
expect(heatmapColorHex(0.5)).toBe('#f59e0b')
|
||||
})
|
||||
|
||||
it('t<0 → clampea a t=0 (verde)', () => {
|
||||
expect(heatmapColorHex(-1)).toBe(heatmapColorHex(0))
|
||||
})
|
||||
|
||||
it('t>1 → clampea a t=1 (rojo)', () => {
|
||||
expect(heatmapColorHex(2)).toBe(heatmapColorHex(1))
|
||||
})
|
||||
|
||||
it('devuelve string hex válido en formato #rrggbb', () => {
|
||||
for (const t of [0, 0.25, 0.5, 0.75, 1]) {
|
||||
const hex = heatmapColorHex(t)
|
||||
expect(hex).toMatch(/^#[0-9a-f]{6}$/)
|
||||
}
|
||||
})
|
||||
|
||||
it('colores intermedios son distintos entre sí', () => {
|
||||
const colors = [0, 0.25, 0.5, 0.75, 1].map(heatmapColorHex)
|
||||
const unique = new Set(colors)
|
||||
expect(unique.size).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
// ─── hasSignificantCostVariance ──────────────────────────────────────────────
|
||||
describe('hasSignificantCostVariance', () => {
|
||||
it('varianza cero: todos iguales → false', () => {
|
||||
expect(hasSignificantCostVariance(makeActs([100, 100, 100, 100, 100]))).toBe(false)
|
||||
})
|
||||
|
||||
it('una sola actividad → false (no hay con qué comparar)', () => {
|
||||
expect(hasSignificantCostVariance(makeActs([500]))).toBe(false)
|
||||
})
|
||||
|
||||
it('lista vacía → false', () => {
|
||||
expect(hasSignificantCostVariance([])).toBe(false)
|
||||
})
|
||||
|
||||
it('varianza < 5%: costos casi iguales → false', () => {
|
||||
// rango = (103-100)/103 ≈ 2.9% < 5%
|
||||
expect(hasSignificantCostVariance(makeActs([100, 101, 102, 103]))).toBe(false)
|
||||
})
|
||||
|
||||
it('varianza > 5%: costos claramente distintos → true', () => {
|
||||
// rango = (200-100)/200 = 50% > 5%
|
||||
expect(hasSignificantCostVariance(makeActs([100, 200]))).toBe(true)
|
||||
})
|
||||
|
||||
it('varianza ≈ THRESHOLD (5%): está justo en el límite', () => {
|
||||
// rango = (105-100)/105 ≈ 4.76% < 5% → false
|
||||
expect(hasSignificantCostVariance(makeActs([100, 105]))).toBe(false)
|
||||
// rango = (111-100)/111 ≈ 9.9% > 5% → true
|
||||
expect(hasSignificantCostVariance(makeActs([100, 111]))).toBe(true)
|
||||
})
|
||||
|
||||
it('no crashea con costos negativos (defensivo)', () => {
|
||||
expect(() => hasSignificantCostVariance(makeActs([-10, -5, 0]))).not.toThrow()
|
||||
})
|
||||
|
||||
it('todos en cero → false (max=0)', () => {
|
||||
expect(hasSignificantCostVariance(makeActs([0, 0, 0]))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// ─── computeActivityT ────────────────────────────────────────────────────────
|
||||
describe('computeActivityT — modo relativo', () => {
|
||||
it('actividad con mayor % → t = 1.0', () => {
|
||||
const acts = makeActs([300, 100, 50])
|
||||
const t = computeActivityT(acts[0], acts, 'relative')
|
||||
expect(t).toBeCloseTo(1.0)
|
||||
})
|
||||
|
||||
it('actividad con menor costo → t < t de la más cara', () => {
|
||||
const acts = makeActs([300, 100, 50])
|
||||
const tBarata = computeActivityT(acts[2], acts, 'relative')
|
||||
const tCara = computeActivityT(acts[0], acts, 'relative')
|
||||
expect(tBarata).toBeLessThan(tCara)
|
||||
})
|
||||
|
||||
it('t siempre está en [0, 1]', () => {
|
||||
const acts = makeActs([1000, 500, 100, 10])
|
||||
for (const act of acts) {
|
||||
const t = computeActivityT(act, acts, 'relative')
|
||||
expect(t).toBeGreaterThanOrEqual(0)
|
||||
expect(t).toBeLessThanOrEqual(1)
|
||||
}
|
||||
})
|
||||
|
||||
it('lista vacía → t = 0 sin crash', () => {
|
||||
const act: ActivityCostData = { expectedTotalCost: 100, percentOfTotal: 100 }
|
||||
expect(computeActivityT(act, [], 'relative')).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('computeActivityT — modo absoluto', () => {
|
||||
it('actividad más cara → t = 1.0', () => {
|
||||
const acts = makeActs([100, 200, 300])
|
||||
const t = computeActivityT(acts[2], acts, 'absolute')
|
||||
expect(t).toBeCloseTo(1.0)
|
||||
})
|
||||
|
||||
it('actividad más barata → t = 0.0', () => {
|
||||
const acts = makeActs([100, 200, 300])
|
||||
const t = computeActivityT(acts[0], acts, 'absolute')
|
||||
expect(t).toBeCloseTo(0.0)
|
||||
})
|
||||
|
||||
it('actividad del medio → t ≈ 0.5', () => {
|
||||
const acts = makeActs([100, 200, 300])
|
||||
const t = computeActivityT(acts[1], acts, 'absolute')
|
||||
expect(t).toBeCloseTo(0.5)
|
||||
})
|
||||
|
||||
it('un solo precio (max=min) → t = 0.5 (defensivo)', () => {
|
||||
const acts = makeActs([100, 100])
|
||||
const t = computeActivityT(acts[0], acts, 'absolute')
|
||||
expect(t).toBe(0.5)
|
||||
})
|
||||
})
|
||||
|
||||
// ─── activityColor — función unificada ───────────────────────────────────────
|
||||
describe('activityColor', () => {
|
||||
it('SIN varianza significativa → TODOS devuelven NEUTRAL_HEATMAP_COLOR', () => {
|
||||
const acts = makeActs([100, 100, 100, 100, 100])
|
||||
for (const act of acts) {
|
||||
expect(activityColor(act, acts, 'relative')).toBe(NEUTRAL_HEATMAP_COLOR)
|
||||
expect(activityColor(act, acts, 'absolute')).toBe(NEUTRAL_HEATMAP_COLOR)
|
||||
}
|
||||
})
|
||||
|
||||
it('CON varianza real modo relativo: la más cara NO es neutra', () => {
|
||||
const acts = makeActs([500, 100, 10])
|
||||
const color = activityColor(acts[0], acts, 'relative')
|
||||
expect(color).not.toBe(NEUTRAL_HEATMAP_COLOR)
|
||||
})
|
||||
|
||||
it('CON varianza real modo relativo: la más cara es roja (#ef4444)', () => {
|
||||
const acts = makeActs([500, 100, 10])
|
||||
const colorCara = activityColor(acts[0], acts, 'relative')
|
||||
expect(colorCara).toBe('#ef4444')
|
||||
})
|
||||
|
||||
it('CON varianza real modo relativo: la más barata es verde (#10b981)', () => {
|
||||
const acts = makeActs([500, 100, 10])
|
||||
const colorBarata = activityColor(acts[2], acts, 'relative')
|
||||
// No necesariamente exactamente verde, pero sí del espectro inferior
|
||||
// La más barata tiene percentOfTotal bajo / maxPercent bajo → t bajo → color verdoso
|
||||
expect(colorBarata).not.toBe('#ef4444')
|
||||
})
|
||||
|
||||
it('CON varianza real modo absoluto: la más cara es roja', () => {
|
||||
const acts = makeActs([1000, 100, 10])
|
||||
const colorCara = activityColor(acts[0], acts, 'absolute')
|
||||
expect(colorCara).toBe('#ef4444')
|
||||
})
|
||||
|
||||
it('CON varianza real modo absoluto: la más barata es verde', () => {
|
||||
const acts = makeActs([1000, 100, 10])
|
||||
const colorBarata = activityColor(acts[2], acts, 'absolute')
|
||||
expect(colorBarata).toBe('#10b981')
|
||||
})
|
||||
|
||||
it('edge: costos negativos no crashean', () => {
|
||||
const acts = makeActs([0, 0, 0])
|
||||
expect(() => activityColor(acts[0], acts, 'relative')).not.toThrow()
|
||||
})
|
||||
|
||||
it('simple-linear scenario: 5 actividades igual costo → todas neutras', () => {
|
||||
// Este es el caso de use real de simple-linear.bpmn con costos fijos iguales
|
||||
const acts = makeActs([100, 100, 100, 100, 100])
|
||||
const colors = acts.map((a) => activityColor(a, acts, 'relative'))
|
||||
expect(colors.every((c) => c === NEUTRAL_HEATMAP_COLOR)).toBe(true)
|
||||
})
|
||||
|
||||
it('NEUTRAL_HEATMAP_COLOR es un hex válido y claramente distinto del gradiente', () => {
|
||||
expect(NEUTRAL_HEATMAP_COLOR).toMatch(/^#[0-9a-f]{6}$/)
|
||||
expect(NEUTRAL_HEATMAP_COLOR).not.toBe('#10b981') // no es verde
|
||||
expect(NEUTRAL_HEATMAP_COLOR).not.toBe('#f59e0b') // no es amarillo
|
||||
expect(NEUTRAL_HEATMAP_COLOR).not.toBe('#ef4444') // no es rojo
|
||||
})
|
||||
})
|
||||
220
tests/lib/export/csv-export.test.ts
Normal file
220
tests/lib/export/csv-export.test.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { generateCsvContent } from '@/lib/export/csv-export'
|
||||
import type { Process, Simulation, Resource, SimulationResult } from '@/domain/types'
|
||||
|
||||
// ─── Fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeProcess(currency: string, extras: Partial<Process> = {}): Process {
|
||||
return {
|
||||
id: 'p1', name: 'Proceso de Ventas', clientName: 'Empresa ABC',
|
||||
bpmnXml: '', currency, overheadPercentage: 0.2,
|
||||
createdAt: 0, updatedAt: 0, ...extras,
|
||||
}
|
||||
}
|
||||
|
||||
function makeSimulation(perActivity: SimulationResult['perActivity'] = []): Simulation {
|
||||
const totalDirect = perActivity.reduce((s, a) => s + a.expectedDirectCost, 0)
|
||||
const totalIndirect = perActivity.reduce((s, a) => s + a.expectedIndirectCost, 0)
|
||||
return {
|
||||
id: 'sim1', processId: 'p1',
|
||||
executedAt: new Date('2026-05-13T10:00:00Z').getTime(),
|
||||
result: {
|
||||
totalCost: totalDirect + totalIndirect,
|
||||
totalDirectCost: totalDirect,
|
||||
totalIndirectCost: totalIndirect,
|
||||
totalTimeMinutes: 90,
|
||||
perActivity,
|
||||
perResource: [],
|
||||
warnings: [],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const mockActivities: SimulationResult['perActivity'] = [
|
||||
{
|
||||
activityId: 'a1', bpmnElementId: 'task1', activityName: 'Recibir solicitud',
|
||||
expectedDirectCost: 500, expectedIndirectCost: 100, expectedTotalCost: 600,
|
||||
percentOfTotal: 60, executionProbability: 1.0, expectedExecutions: 1.0,
|
||||
executionTimeMinutes: 30, resourceCostBreakdown: [],
|
||||
},
|
||||
{
|
||||
activityId: 'a2', bpmnElementId: 'task2', activityName: 'Análisis de crédito',
|
||||
expectedDirectCost: 250, expectedIndirectCost: 50, expectedTotalCost: 300,
|
||||
percentOfTotal: 30, executionProbability: 0.8, expectedExecutions: 0.8,
|
||||
executionTimeMinutes: 60, resourceCostBreakdown: [],
|
||||
},
|
||||
{
|
||||
activityId: 'a3', bpmnElementId: 'task3', activityName: 'Notificación al cliente',
|
||||
expectedDirectCost: 83.33, expectedIndirectCost: 16.67, expectedTotalCost: 100,
|
||||
percentOfTotal: 10, executionProbability: 0.5, expectedExecutions: 0.5,
|
||||
executionTimeMinutes: 15, resourceCostBreakdown: [],
|
||||
},
|
||||
]
|
||||
|
||||
const resources: Resource[] = []
|
||||
|
||||
// ─── BOM UTF-8 ────────────────────────────────────────────────────────────────
|
||||
describe('CSV — BOM UTF-8', () => {
|
||||
it('comienza con BOM UTF-8 (\\uFEFF)', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv.charCodeAt(0)).toBe(0xFEFF)
|
||||
})
|
||||
|
||||
it('BOM está presente para PYG también', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('PYG'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv.charCodeAt(0)).toBe(0xFEFF)
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Separadores ──────────────────────────────────────────────────────────────
|
||||
describe('CSV — separadores', () => {
|
||||
it('USD: separador de columnas es coma ","', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
// Los headers deben estar separados por coma
|
||||
const headerLine = csv.split('\r\n').find((l) => l.includes('Actividad'))!
|
||||
expect(headerLine).toContain(',')
|
||||
expect(headerLine).not.toContain(';')
|
||||
})
|
||||
|
||||
it('PYG: separador de columnas es punto y coma ";"', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('PYG'), simulation: makeSimulation(mockActivities), resources })
|
||||
const headerLine = csv.split('\r\n').find((l) => l.includes('Actividad'))!
|
||||
expect(headerLine).toContain(';')
|
||||
expect(headerLine).not.toContain(',"Actividad"')
|
||||
})
|
||||
|
||||
it('BRL: separador es punto y coma', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('BRL'), simulation: makeSimulation(mockActivities), resources })
|
||||
const headerLine = csv.split('\r\n').find((l) => l.includes('Actividad'))!
|
||||
expect(headerLine).toContain(';')
|
||||
})
|
||||
|
||||
it('EUR: separador es punto y coma', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('EUR'), simulation: makeSimulation(mockActivities), resources })
|
||||
const headerLine = csv.split('\r\n').find((l) => l.includes('Actividad'))!
|
||||
expect(headerLine).toContain(';')
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Separadores decimales ─────────────────────────────────────────────────────
|
||||
describe('CSV — separadores decimales', () => {
|
||||
it('USD: decimal es punto "." → "500.00"', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('500.00')
|
||||
})
|
||||
|
||||
it('PYG: decimal es coma "," → "500,00"', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('PYG'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('500,00')
|
||||
})
|
||||
|
||||
it('BRL: decimal es coma', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('BRL'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('500,00')
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Headers ──────────────────────────────────────────────────────────────────
|
||||
describe('CSV — headers', () => {
|
||||
it('contiene "Actividad" en los headers', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('Actividad')
|
||||
})
|
||||
|
||||
it('header de costo incluye la moneda: "Costo total (USD)"', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('Costo total (USD)')
|
||||
})
|
||||
|
||||
it('header de costo incluye la moneda: "Costo total (PYG)"', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('PYG'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('Costo total (PYG)')
|
||||
})
|
||||
|
||||
it('contiene todos los headers requeridos', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('ID BPMN')
|
||||
expect(csv).toContain('Tiempo (min)')
|
||||
expect(csv).toContain('% del total')
|
||||
expect(csv).toContain('Ejecuciones esperadas')
|
||||
expect(csv).toContain('Recursos asignados')
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Cantidad de filas ────────────────────────────────────────────────────────
|
||||
describe('CSV — cantidad de filas', () => {
|
||||
it('tiene exactamente N filas de datos + header + metadata', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
// Quitar BOM antes de procesar para no confundir el filtro de comentarios
|
||||
const csvNoBom = csv.startsWith('') ? csv.slice(1) : csv
|
||||
const lines = csvNoBom.split('\r\n').filter((l) => l.trim() && !l.startsWith('#'))
|
||||
// 1 header + N actividades
|
||||
expect(lines).toHaveLength(mockActivities.length + 1)
|
||||
})
|
||||
|
||||
it('0 actividades → solo header', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation([]), resources })
|
||||
const csvNoBom = csv.startsWith('') ? csv.slice(1) : csv
|
||||
const lines = csvNoBom.split('\r\n').filter((l) => l.trim() && !l.startsWith('#'))
|
||||
expect(lines).toHaveLength(1) // solo el header
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Metadata de cabecera ─────────────────────────────────────────────────────
|
||||
describe('CSV — metadata', () => {
|
||||
it('la metadata comienza con "# Proceso:"', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('# Proceso: Proceso de Ventas')
|
||||
})
|
||||
|
||||
it('la metadata contiene el nombre del cliente', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('# Cliente: Empresa ABC')
|
||||
})
|
||||
|
||||
it('la metadata contiene el costo total', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources })
|
||||
expect(csv).toContain('# Costo total (USD)')
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Caracteres especiales / UTF-8 ───────────────────────────────────────────
|
||||
describe('CSV — UTF-8 y caracteres especiales', () => {
|
||||
it('nombres con acentos se preservan correctamente', () => {
|
||||
const activitiesWithAccents: SimulationResult['perActivity'] = [{
|
||||
activityId: 'a1', bpmnElementId: 't1',
|
||||
activityName: 'Revisión y Análisis Crítico',
|
||||
expectedDirectCost: 100, expectedIndirectCost: 20, expectedTotalCost: 120,
|
||||
percentOfTotal: 100, executionProbability: 1, expectedExecutions: 1,
|
||||
executionTimeMinutes: 30, resourceCostBreakdown: [],
|
||||
}]
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(activitiesWithAccents), resources })
|
||||
expect(csv).toContain('Revisión y Análisis Crítico')
|
||||
})
|
||||
|
||||
it('nombre del proceso con ñ se preserva', () => {
|
||||
const process = makeProcess('USD', { name: 'Gestión de la Compañía' })
|
||||
const csv = generateCsvContent({ process, simulation: makeSimulation([]), resources })
|
||||
expect(csv).toContain('Gestión de la Compañía')
|
||||
})
|
||||
|
||||
it('actividad con nombre en blanco no rompe el CSV', () => {
|
||||
const activitiesBlank: SimulationResult['perActivity'] = [{
|
||||
activityId: 'a1', bpmnElementId: 't1', activityName: '',
|
||||
expectedDirectCost: 0, expectedIndirectCost: 0, expectedTotalCost: 0,
|
||||
percentOfTotal: 0, executionProbability: 1, expectedExecutions: 1,
|
||||
executionTimeMinutes: 0, resourceCostBreakdown: [],
|
||||
}]
|
||||
expect(() => generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(activitiesBlank), resources })).not.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Recursos vacíos ──────────────────────────────────────────────────────────
|
||||
describe('CSV — recursos vacíos', () => {
|
||||
it('actividad sin recursos → celda de recursos vacía (no rompe)', () => {
|
||||
const csv = generateCsvContent({ process: makeProcess('USD'), simulation: makeSimulation(mockActivities), resources: [] })
|
||||
// No debe crashear y el contenido es válido
|
||||
expect(csv.length).toBeGreaterThan(0)
|
||||
expect(csv).toContain('Recibir solicitud')
|
||||
})
|
||||
})
|
||||
88
tests/lib/export/measure-sizes.test.ts
Normal file
88
tests/lib/export/measure-sizes.test.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Medición de tamaños de CSV para los 3 sample BPMNs.
|
||||
* Este test calcula el tamaño en bytes del CSV generado para cada BPMN.
|
||||
*/
|
||||
import { describe, it } from 'vitest'
|
||||
import { readFileSync } from 'fs'
|
||||
import { resolve } from 'path'
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import { parseBpmnXml, extractActivityElements, extractGatewayElements } from '@/domain/bpmn-parser'
|
||||
import { runSimulation } from '@/domain/simulation'
|
||||
import { generateCsvContent } from '@/lib/export/csv-export'
|
||||
import { bpmnTypeToGatewayType } from '@/domain/types'
|
||||
import type { Activity, GatewayConfig, SimulationInput, Process, Simulation } from '@/domain/types'
|
||||
|
||||
function loadBpmn(name: string): string {
|
||||
return readFileSync(resolve(__dirname, '../../../public/sample-processes', name), 'utf-8')
|
||||
}
|
||||
|
||||
function buildInput(xml: string, directCost: number): SimulationInput {
|
||||
const graph = parseBpmnXml(xml)
|
||||
const actEls = extractActivityElements(graph)
|
||||
const gwEls = extractGatewayElements(graph)
|
||||
const processId = 'measure-proc'
|
||||
|
||||
const activities = new Map<string, Activity>(
|
||||
actEls.map((el) => [el.bpmnElementId, {
|
||||
id: uuidv4(), processId, bpmnElementId: el.bpmnElementId, name: el.name,
|
||||
type: el.type, directCostFixed: directCost, executionTimeMinutes: 30, assignedResources: [],
|
||||
}])
|
||||
)
|
||||
|
||||
const gateways = new Map<string, GatewayConfig>(
|
||||
gwEls.map((el) => {
|
||||
const gwType = bpmnTypeToGatewayType(el.gatewayType as any)
|
||||
return [el.bpmnElementId, {
|
||||
id: uuidv4(), processId, bpmnElementId: el.bpmnElementId, gatewayType: gwType,
|
||||
branches: el.outgoing.map((flowId) => ({
|
||||
flowId, targetElementId: graph.flows.get(flowId)?.targetRef ?? '',
|
||||
probability: gwType === 'parallel' ? 1.0 : 1 / el.outgoing.length,
|
||||
})),
|
||||
}]
|
||||
})
|
||||
)
|
||||
|
||||
return {
|
||||
processXml: xml, activities, gateways, resources: new Map(),
|
||||
globalSettings: { currency: 'USD', overheadPercentage: 0.2 },
|
||||
}
|
||||
}
|
||||
|
||||
describe('Medición de tamaños de CSV — 3 sample BPMNs', () => {
|
||||
const BPMNS = [
|
||||
{ file: 'simple-linear.bpmn', name: 'Proceso Lineal Simple', client: 'Demo' },
|
||||
{ file: 'medium-with-gateways.bpmn', name: 'Aprobación de Crédito', client: 'Banco ABC' },
|
||||
{ file: 'complex-with-loop.bpmn', name: 'Control de Calidad', client: 'Empresa XYZ' },
|
||||
]
|
||||
|
||||
for (const bpmn of BPMNS) {
|
||||
it(`${bpmn.file}: mide tamaño del CSV`, () => {
|
||||
const xml = loadBpmn(bpmn.file)
|
||||
const result = runSimulation(buildInput(xml, 1000))
|
||||
|
||||
const process: Process = {
|
||||
id: 'p1', name: bpmn.name, clientName: bpmn.client,
|
||||
bpmnXml: xml, currency: 'USD', overheadPercentage: 0.2,
|
||||
createdAt: 0, updatedAt: 0,
|
||||
}
|
||||
|
||||
const simulation: Simulation = {
|
||||
id: 's1', processId: 'p1',
|
||||
executedAt: new Date('2026-05-13T12:00:00Z').getTime(),
|
||||
result,
|
||||
}
|
||||
|
||||
const csv = generateCsvContent({ process, simulation, resources: [] })
|
||||
const bytes = new TextEncoder().encode(csv).length
|
||||
|
||||
console.log(`\n📊 ${bpmn.file}`)
|
||||
console.log(` Actividades: ${result.perActivity.length}`)
|
||||
console.log(` CSV size: ${bytes} bytes (${(bytes / 1024).toFixed(1)} KB)`)
|
||||
console.log(` CSV líneas de datos: ${result.perActivity.length} + 1 header + 7 meta`)
|
||||
console.log(` Costo total: $${result.totalCost.toFixed(2)}`)
|
||||
|
||||
// El CSV no debe ser vacío
|
||||
expect(bytes).toBeGreaterThan(100)
|
||||
})
|
||||
}
|
||||
})
|
||||
166
tests/lib/export/pdf-export.test.ts
Normal file
166
tests/lib/export/pdf-export.test.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* Smoke tests del export PDF.
|
||||
* jsPDF + autotable se mockean porque requieren canvas/DOM completo.
|
||||
* Se verifica: llamadas al builder, metadata, nombre de archivo, no-throw.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// ─── Mock de jsPDF ────────────────────────────────────────────────────────────
|
||||
const mockDoc = {
|
||||
setProperties: vi.fn(),
|
||||
setFont: vi.fn(),
|
||||
setFontSize: vi.fn(),
|
||||
setTextColor: vi.fn(),
|
||||
setFillColor: vi.fn(),
|
||||
setDrawColor: vi.fn(),
|
||||
setLineWidth: vi.fn(),
|
||||
text: vi.fn(),
|
||||
rect: vi.fn(),
|
||||
roundedRect: vi.fn(),
|
||||
line: vi.fn(),
|
||||
addImage: vi.fn(),
|
||||
addPage: vi.fn(),
|
||||
setPage: vi.fn(),
|
||||
save: vi.fn(),
|
||||
splitTextToSize: vi.fn().mockImplementation((text: string) => [text]),
|
||||
internal: { getNumberOfPages: vi.fn().mockReturnValue(3) },
|
||||
}
|
||||
|
||||
// Arrow functions no pueden ser constructoras — usar function() regular
|
||||
vi.mock('jspdf', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function MockJsPDF(this: any) { return mockDoc }
|
||||
return { jsPDF: MockJsPDF }
|
||||
})
|
||||
|
||||
vi.mock('jspdf-autotable', () => ({
|
||||
default: vi.fn(),
|
||||
}))
|
||||
|
||||
// ─── Fixtures ─────────────────────────────────────────────────────────────────
|
||||
|
||||
import type { Process, Simulation } from '@/domain/types'
|
||||
|
||||
const mockProcess: Process = {
|
||||
id: 'p1', name: 'Proceso de Aprobación de Crédito',
|
||||
clientName: 'Banco XYZ',
|
||||
bpmnXml: '', currency: 'USD',
|
||||
overheadPercentage: 0.2,
|
||||
createdAt: 0, updatedAt: 0,
|
||||
}
|
||||
|
||||
const mockSimulation: Simulation = {
|
||||
id: 'sim1', processId: 'p1',
|
||||
executedAt: new Date('2026-05-13T10:00:00Z').getTime(),
|
||||
result: {
|
||||
totalCost: 1200,
|
||||
totalDirectCost: 1000,
|
||||
totalIndirectCost: 200,
|
||||
totalTimeMinutes: 90,
|
||||
perActivity: [
|
||||
{
|
||||
activityId: 'a1', bpmnElementId: 'task1', activityName: 'Recibir solicitud',
|
||||
expectedDirectCost: 600, expectedIndirectCost: 120, expectedTotalCost: 720,
|
||||
percentOfTotal: 60, executionProbability: 1.0, expectedExecutions: 1.0,
|
||||
executionTimeMinutes: 30, resourceCostBreakdown: [],
|
||||
},
|
||||
{
|
||||
activityId: 'a2', bpmnElementId: 'task2', activityName: 'Procesar',
|
||||
expectedDirectCost: 400, expectedIndirectCost: 80, expectedTotalCost: 480,
|
||||
percentOfTotal: 40, executionProbability: 0.8, expectedExecutions: 0.8,
|
||||
executionTimeMinutes: 60, resourceCostBreakdown: [],
|
||||
},
|
||||
],
|
||||
perResource: [],
|
||||
warnings: [],
|
||||
},
|
||||
}
|
||||
|
||||
// ─── Tests ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('exportToPdf — smoke tests', () => {
|
||||
beforeEach(() => { vi.clearAllMocks() })
|
||||
|
||||
it('no lanza error con parámetros válidos y heatmap null', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
await expect(exportToPdf({
|
||||
process: mockProcess,
|
||||
simulation: mockSimulation,
|
||||
resources: [],
|
||||
heatmapImageData: null,
|
||||
})).resolves.not.toThrow()
|
||||
})
|
||||
|
||||
it('llama a doc.addPage al menos una vez (estructura multi-página)', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null })
|
||||
// El PDF tiene al menos 2 páginas (análisis + tabla)
|
||||
expect(mockDoc.addPage).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('llama a setProperties con metadata correcta', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null })
|
||||
expect(mockDoc.setProperties).toHaveBeenCalledWith(expect.objectContaining({
|
||||
title: expect.stringContaining('Proceso de Aprobación de Crédito'),
|
||||
author: 'Banco XYZ',
|
||||
subject: 'Simulación de proceso BPMN',
|
||||
}))
|
||||
})
|
||||
|
||||
it('llama a doc.save con nombre de archivo correcto', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null })
|
||||
const saveCall = mockDoc.save.mock.calls[0][0] as string
|
||||
expect(saveCall).toMatch(/proceso-de-aprobacion-de-credito/)
|
||||
expect(saveCall).toMatch(/banco-xyz/)
|
||||
expect(saveCall).toMatch(/\.pdf$/)
|
||||
})
|
||||
|
||||
it('NO llama a addImage cuando heatmapImageData es null', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null })
|
||||
expect(mockDoc.addImage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('llama a addImage cuando heatmapImageData está disponible', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
const fakeDataUrl = 'data:image/jpeg;base64,/9j/fake'
|
||||
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: fakeDataUrl })
|
||||
expect(mockDoc.addImage).toHaveBeenCalledWith(fakeDataUrl, 'JPEG', expect.any(Number), expect.any(Number), expect.any(Number), expect.any(Number))
|
||||
})
|
||||
|
||||
it('llama a addPageNumbers (setPage para el footer)', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null })
|
||||
// addPageNumbers itera setPage para cada página
|
||||
expect(mockDoc.setPage).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('llama a autoTable con head que contiene la moneda', async () => {
|
||||
const autoTable = (await import('jspdf-autotable')).default as ReturnType<typeof vi.fn>
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
await exportToPdf({ process: mockProcess, simulation: mockSimulation, resources: [], heatmapImageData: null })
|
||||
expect(autoTable).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
head: expect.arrayContaining([
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ content: expect.stringContaining('USD') }),
|
||||
]),
|
||||
]),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('con warnings en el resultado: no lanza error', async () => {
|
||||
const { exportToPdf } = await import('@/lib/export/pdf-export')
|
||||
const simWithWarnings = {
|
||||
...mockSimulation,
|
||||
result: { ...mockSimulation.result, warnings: ['Loop detectado en task1'] },
|
||||
}
|
||||
await expect(exportToPdf({
|
||||
process: mockProcess, simulation: simWithWarnings, resources: [], heatmapImageData: null,
|
||||
})).resolves.not.toThrow()
|
||||
})
|
||||
})
|
||||
83
tests/lib/export/slug.test.ts
Normal file
83
tests/lib/export/slug.test.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { slugify, buildFileName } from '@/lib/export/slug'
|
||||
|
||||
describe('slugify', () => {
|
||||
it('"Proceso de Compras" → "proceso-de-compras"', () => {
|
||||
expect(slugify('Proceso de Compras')).toBe('proceso-de-compras')
|
||||
})
|
||||
|
||||
it('"Análisis Año 2025" → "analisis-ano-2025"', () => {
|
||||
expect(slugify('Análisis Año 2025')).toBe('analisis-ano-2025')
|
||||
})
|
||||
|
||||
it('elimina la ñ → n', () => {
|
||||
expect(slugify('Gestión de Compañía')).toBe('gestion-de-compania')
|
||||
})
|
||||
|
||||
it('elimina acentos (á é í ó ú ü)', () => {
|
||||
expect(slugify('Ú ltimo Análisis Crítico')).toBe('u-ltimo-analisis-critico')
|
||||
})
|
||||
|
||||
it('caracteres especiales → guiones', () => {
|
||||
expect(slugify('Proceso #1 / Sub-proceso (test)')).toBe('proceso-1-sub-proceso-test')
|
||||
})
|
||||
|
||||
it('múltiples espacios → un solo guión', () => {
|
||||
expect(slugify('Proceso de ventas')).toBe('proceso-de-ventas')
|
||||
})
|
||||
|
||||
it('string vacío → string vacío', () => {
|
||||
expect(slugify('')).toBe('')
|
||||
})
|
||||
|
||||
it('solo números → se mantienen', () => {
|
||||
expect(slugify('2025')).toBe('2025')
|
||||
})
|
||||
|
||||
it('ya en minúsculas sin acentos → sin cambios relevantes', () => {
|
||||
expect(slugify('proceso-lineal')).toBe('proceso-lineal')
|
||||
})
|
||||
|
||||
it('limita a 60 caracteres', () => {
|
||||
const long = 'a'.repeat(100)
|
||||
expect(slugify(long)).toHaveLength(60)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildFileName', () => {
|
||||
// new Date(año, mes0, día) → fecha local sin ambigüedad de timezone
|
||||
const date = new Date(2026, 4, 13) // 13 de mayo de 2026, local time
|
||||
|
||||
it('genera filename con proceso + cliente + fecha', () => {
|
||||
const name = buildFileName('Proceso de Ventas', 'Banco ABC', date, 'pdf')
|
||||
expect(name).toBe('proceso-de-ventas_banco-abc_20260513.pdf')
|
||||
})
|
||||
|
||||
it('omite cliente si está vacío', () => {
|
||||
const name = buildFileName('Proceso de Ventas', '', date, 'csv')
|
||||
expect(name).toBe('proceso-de-ventas_20260513.csv')
|
||||
})
|
||||
|
||||
it('omite cliente si es undefined', () => {
|
||||
const name = buildFileName('Proceso', undefined, date, 'pdf')
|
||||
expect(name).toBe('proceso_20260513.pdf')
|
||||
})
|
||||
|
||||
it('extensión csv correcta', () => {
|
||||
const name = buildFileName('test', 'cliente', date, 'csv')
|
||||
expect(name).toMatch(/\.csv$/)
|
||||
})
|
||||
|
||||
it('extensión pdf correcta', () => {
|
||||
const name = buildFileName('test', 'cliente', date, 'pdf')
|
||||
expect(name).toMatch(/\.pdf$/)
|
||||
})
|
||||
|
||||
it('nombre con caracteres especiales queda limpio (sin #, paréntesis)', () => {
|
||||
const name = buildFileName('Análisis #1', 'Empresa S.A.', date, 'csv')
|
||||
// Verificar solo el slug (sin la extensión que tiene un punto legítimo)
|
||||
const slug = name.replace(/\.\w+$/, '')
|
||||
expect(slug).not.toMatch(/[#()]/)
|
||||
expect(name).toMatch(/analisis/)
|
||||
})
|
||||
})
|
||||
211
tests/lib/format.test.ts
Normal file
211
tests/lib/format.test.ts
Normal file
@@ -0,0 +1,211 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { formatCurrency, formatPercent, formatMinutes, formatSimulationTimestamp } from '@/lib/format'
|
||||
|
||||
// ─── formatCurrency ───────────────────────────────────────────────────────────
|
||||
describe('formatCurrency', () => {
|
||||
// USD
|
||||
it('USD: formatea 0 correctamente', () => {
|
||||
const result = formatCurrency(0, 'USD')
|
||||
expect(result).toMatch(/0/)
|
||||
expect(result).toMatch(/\$|USD/)
|
||||
})
|
||||
|
||||
it('USD: formatea 1 con 2 decimales', () => {
|
||||
const result = formatCurrency(1, 'USD')
|
||||
expect(result).toMatch(/1[.,]00/)
|
||||
})
|
||||
|
||||
it('USD: formatea 1000 con separador de miles', () => {
|
||||
const result = formatCurrency(1000, 'USD')
|
||||
// Debe tener separador (coma o punto) antes de los tres ceros
|
||||
expect(result).toMatch(/1[.,]000/)
|
||||
})
|
||||
|
||||
it('USD: formatea 1234567 con separadores', () => {
|
||||
const result = formatCurrency(1234567, 'USD')
|
||||
expect(result).toMatch(/1/)
|
||||
expect(result).toMatch(/234/)
|
||||
expect(result).toMatch(/567/)
|
||||
})
|
||||
|
||||
it('USD: formatea decimales correctamente', () => {
|
||||
const result = formatCurrency(1234.56, 'USD')
|
||||
expect(result).toMatch(/1[.,]234/)
|
||||
expect(result).toMatch(/56/)
|
||||
})
|
||||
|
||||
// PYG — el guaraní no tiene decimales centavos en la práctica
|
||||
it('PYG: devuelve una cadena con el valor', () => {
|
||||
const result = formatCurrency(1000000, 'PYG')
|
||||
expect(result).toBeTruthy()
|
||||
expect(typeof result).toBe('string')
|
||||
expect(result.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('PYG: 0 formatea sin crash', () => {
|
||||
expect(() => formatCurrency(0, 'PYG')).not.toThrow()
|
||||
})
|
||||
|
||||
it('PYG: número grande formatea sin crash', () => {
|
||||
expect(() => formatCurrency(1_234_567_890, 'PYG')).not.toThrow()
|
||||
const result = formatCurrency(1_234_567_890, 'PYG')
|
||||
expect(result).toMatch(/1/)
|
||||
})
|
||||
|
||||
// BRL
|
||||
it('BRL: formatea con símbolo correcto', () => {
|
||||
const result = formatCurrency(1000, 'BRL')
|
||||
expect(result).toBeTruthy()
|
||||
// El símbolo R$ puede aparecer o la abreviatura BRL
|
||||
expect(result).toMatch(/1/)
|
||||
})
|
||||
|
||||
// EUR
|
||||
it('EUR: formatea 1234.56 sin crash', () => {
|
||||
expect(() => formatCurrency(1234.56, 'EUR')).not.toThrow()
|
||||
const result = formatCurrency(1234.56, 'EUR')
|
||||
expect(result).toMatch(/1/)
|
||||
})
|
||||
|
||||
// Negativos — el reporte no debe tener valores negativos, pero la función no debe crashear
|
||||
it('No crashea con valores negativos', () => {
|
||||
expect(() => formatCurrency(-100, 'USD')).not.toThrow()
|
||||
const result = formatCurrency(-100, 'USD')
|
||||
expect(result).toMatch(/-|100/)
|
||||
})
|
||||
|
||||
// Múltiples monedas producen outputs distintos
|
||||
it('USD y PYG producen outputs distintos para el mismo número', () => {
|
||||
const usd = formatCurrency(1000, 'USD')
|
||||
const pyg = formatCurrency(1000, 'PYG')
|
||||
expect(usd).not.toBe(pyg)
|
||||
})
|
||||
})
|
||||
|
||||
// ─── formatMinutes ────────────────────────────────────────────────────────────
|
||||
describe('formatMinutes', () => {
|
||||
it('5 min → "5 min"', () => {
|
||||
expect(formatMinutes(5)).toBe('5 min')
|
||||
})
|
||||
|
||||
it('30 min → "30 min"', () => {
|
||||
expect(formatMinutes(30)).toBe('30 min')
|
||||
})
|
||||
|
||||
it('59 min → "59 min" (aún no llega a 1h)', () => {
|
||||
expect(formatMinutes(59)).toBe('59 min')
|
||||
})
|
||||
|
||||
it('60 min → "1h" (exactamente 1 hora)', () => {
|
||||
expect(formatMinutes(60)).toBe('1h')
|
||||
})
|
||||
|
||||
it('90 min → "1h 30min"', () => {
|
||||
expect(formatMinutes(90)).toBe('1h 30min')
|
||||
})
|
||||
|
||||
it('125 min → "2h 5min"', () => {
|
||||
expect(formatMinutes(125)).toBe('2h 5min')
|
||||
})
|
||||
|
||||
it('120 min → "2h" (horas exactas, sin fracción)', () => {
|
||||
expect(formatMinutes(120)).toBe('2h')
|
||||
})
|
||||
|
||||
it('1440 min → "24h" (un día completo)', () => {
|
||||
expect(formatMinutes(1440)).toBe('24h')
|
||||
})
|
||||
|
||||
it('0 min → "0 min"', () => {
|
||||
expect(formatMinutes(0)).toBe('0 min')
|
||||
})
|
||||
|
||||
it('No crashea con valores decimales', () => {
|
||||
expect(() => formatMinutes(90.7)).not.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
// ─── formatPercent ────────────────────────────────────────────────────────────
|
||||
// Nota: el locale es-PY usa coma como separador decimal → "23,4%" no "23.4%".
|
||||
// Los tests verifican estructura (contiene el valor y el símbolo) sin asumir separador.
|
||||
describe('formatPercent', () => {
|
||||
it('23.4 → contiene "23" y "4" y "%" con 1 decimal', () => {
|
||||
const result = formatPercent(23.4)
|
||||
expect(result).toContain('23')
|
||||
expect(result).toContain('4')
|
||||
expect(result).toContain('%')
|
||||
})
|
||||
|
||||
it('100 → contiene "100" y "%" con 1 decimal', () => {
|
||||
const result = formatPercent(100)
|
||||
expect(result).toContain('100')
|
||||
expect(result).toContain('%')
|
||||
})
|
||||
|
||||
it('0 → contiene "0" y "%" sin crash', () => {
|
||||
const result = formatPercent(0)
|
||||
expect(result).toContain('0')
|
||||
expect(result).toContain('%')
|
||||
})
|
||||
|
||||
it('el locale es-PY usa coma decimal: 23.4 → "23,4%"', () => {
|
||||
// Documenta el comportamiento real del locale configurado
|
||||
expect(formatPercent(23.4)).toBe('23,4%')
|
||||
})
|
||||
|
||||
it('100% con 0 decimales → "100%"', () => {
|
||||
expect(formatPercent(100, 0)).toBe('100%')
|
||||
})
|
||||
|
||||
it('20 con 0 decimales → "20%"', () => {
|
||||
expect(formatPercent(20, 0)).toBe('20%')
|
||||
})
|
||||
})
|
||||
|
||||
// ─── formatSimulationTimestamp ────────────────────────────────────────────────
|
||||
describe('formatSimulationTimestamp', () => {
|
||||
// Timestamp fijo para reproducibilidad: 13 de mayo de 2026, 09:45 UTC-4 (PY hora de verano)
|
||||
// Usamos una fecha conocida y verificamos la estructura del output sin depender de TZ del CI.
|
||||
const KNOWN_TS = new Date('2026-05-13T13:45:00Z').getTime() // UTC
|
||||
|
||||
it('devuelve objeto con date y time strings no vacíos', () => {
|
||||
const { date, time } = formatSimulationTimestamp(KNOWN_TS)
|
||||
expect(date.length).toBeGreaterThan(0)
|
||||
expect(time.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('date contiene el año 2026', () => {
|
||||
const { date } = formatSimulationTimestamp(KNOWN_TS)
|
||||
expect(date).toContain('2026')
|
||||
})
|
||||
|
||||
it('date contiene el número 13 (día)', () => {
|
||||
const { date } = formatSimulationTimestamp(KNOWN_TS)
|
||||
expect(date).toContain('13')
|
||||
})
|
||||
|
||||
it('date contiene "mayo" (nombre del mes en es-PY)', () => {
|
||||
const { date } = formatSimulationTimestamp(KNOWN_TS)
|
||||
expect(date).toMatch(/mayo/i)
|
||||
})
|
||||
|
||||
it('time tiene formato HH:mm (dos pares de dígitos separados por ":")', () => {
|
||||
const { time } = formatSimulationTimestamp(KNOWN_TS)
|
||||
expect(time).toMatch(/\d{1,2}:\d{2}/)
|
||||
})
|
||||
|
||||
it('no crashea con timestamp 0 (epoch)', () => {
|
||||
expect(() => formatSimulationTimestamp(0)).not.toThrow()
|
||||
const { date, time } = formatSimulationTimestamp(0)
|
||||
expect(date.length).toBeGreaterThan(0)
|
||||
expect(time.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('timestamps distintos producen salidas distintas', () => {
|
||||
const ts1 = new Date('2026-01-01T10:00:00Z').getTime()
|
||||
const ts2 = new Date('2026-06-15T18:30:00Z').getTime()
|
||||
const r1 = formatSimulationTimestamp(ts1)
|
||||
const r2 = formatSimulationTimestamp(ts2)
|
||||
expect(r1.date).not.toBe(r2.date)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user