Files
Investidor-V2/tests/frontend/decimal-input.test.mjs
T
Claude 4745331ebd
tests / ci (push) Canceled after 0s
Simulador: os campos numéricos aceitam «25.000», «1 500» e «1500,50»
O campo numérico do navegador segue a língua do navegador: «25.000» era
lido como 25 e a vírgula decimal podia ser recusada, pelo que o investidor
via o valor mudar ou não conseguia escrever. Os campos de montantes do
simulador, do plano de negócio e do orçamento inicial passam a usar um
campo de texto decimal que lê os números como se escrevem em Moçambique,
mostra «Lido como …» quando reinterpreta e deixa o texto inválido chegar à
validação, que o explica.

Os campos inteiros (horizonte, prazo de entrega, vida útil, mês económico)
deixam de saltar para 1 quando se apaga para reescrever; se o valor escrito
não for aceite, ao sair do campo volta o valor em vigor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
2026-12-04 23:01:57 +02:00

153 lines
4.7 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
normalizeDecimalInput,
presentDecimal,
} from '../../resources/js/lib/decimal-input.ts';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
/** The real field, with state kept between calls as React would keep it. */
function field(initial, emitted, accepts = () => true) {
const memory = [];
let cursor = 0;
let value = initial;
const hooks = {
...React,
useId: () => 'decimal-hint',
useEffect() {},
useRef(start) {
const id = cursor++;
if (!(id in memory)) memory[id] = { current: start };
return memory[id];
},
useState(start) {
const id = cursor++;
if (!(id in memory)) memory[id] = start;
return [memory[id], (next) => (memory[id] = next)];
},
};
const module = { exports: {} };
compileFunction(
ts.transpileModule(
fs.readFileSync(
'resources/js/components/decimal-input.tsx',
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText,
['require', 'module', 'exports'],
)(
(id) =>
id === 'react'
? hooks
: id === '@/lib/decimal-input'
? { normalizeDecimalInput, presentDecimal }
: require(id),
module,
module.exports,
);
const render = () => {
cursor = 0;
const tree = module.exports.DecimalInput({
value,
onValueChange(next) {
emitted.push(next);
if (accepts(next)) value = next;
},
});
return [tree.props.children].flat().filter(Boolean);
};
return {
input: () => render()[0],
hint: () => render()[1],
type(text) {
render()[0].props.onChange({ target: { value: text } });
},
};
}
test('numbers are read as written in Mozambique, never silently changed (Criar Hotel: campos que não aceitam introdução)', () => {
for (const [typed, stored] of [
['25.000', '25000'],
['1.500.000', '1500000'],
['1 500', '1500'],
['1 500', '1500'],
['1500,50', '1500.50'],
['1.500,25', '1500.25'],
[',5', '0.5'],
['1500.50', '1500.50'],
['0.125', '0.125'],
['1.5', '1.5'],
['120', '120'],
['-25.000', '-25000'],
['', ''],
[' ', ''],
])
assert.equal(normalizeDecimalInput(typed), stored, typed);
for (const invalid of [
'abc',
'1,2,3',
'1.234.5',
'12.34,5.6',
'1e5',
'--1',
])
assert.equal(normalizeDecimalInput(invalid), null, invalid);
assert.equal(presentDecimal('1500000.5'), '1 500 000,5');
assert.equal(presentDecimal('-25000'), '-25 000');
});
test('the simulator field takes «25.000» and «1 500,50» as typed, says how it read them and keeps the text while it is being written', () => {
const emitted = [];
const f = field('', emitted);
assert.equal(f.input().type, 'input');
assert.equal(f.input().props.type, 'text');
assert.equal(f.input().props.inputMode, 'decimal');
f.type('25.000');
assert.equal(emitted.at(-1), '25000');
assert.equal(f.input().props.value, '25.000');
assert.match(
renderToStaticMarkup(f.hint()),
/Lido como 25(\s|&nbsp;| )000/,
);
f.type('1 500,50');
assert.equal(emitted.at(-1), '1500.50');
f.type('abc');
assert.equal(emitted.at(-1), 'abc', 'invalid text reaches validation');
f.type('');
assert.equal(emitted.at(-1), '');
});
test('an integer field emptied while retyping shows again the value still in force', () => {
const emitted = [];
// Like the horizon: the plan only accepts a number.
const f = field(12, emitted, (next) => /^\d+$/.test(next));
assert.equal(f.input().props.value, '12');
f.type('');
assert.equal(f.input().props.value, '');
f.input().props.onBlur({});
assert.equal(f.input().props.value, '12');
f.type('1,5');
f.input().props.onBlur({});
assert.equal(
f.input().props.value,
'12',
'a fraction of a month is not kept',
);
f.type('24');
f.input().props.onBlur({});
assert.equal(f.input().props.value, '24');
});