This commit is contained in:
OMGiTzPomPom 2024-03-29 12:15:51 +01:00
parent e61ce661f5
commit 98edde4a8f
2 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,57 @@
import { NumberValidation } from "./index";
describe("Test NumberValidation", () => {
const numberValidator = new NumberValidation();
it.each([
{ input: "123", expected: 123 },
{ input: "123.45", expected: 123.45 },
{ input: "-123", expected: -123 }
])(
"should validate number %s correctly",
({ input, expected }) => {
const result = numberValidator.validateNumber(input);
expect(result).toEqual(expected);
console.log(`Test with input = ${input}, expected = ${expected}, result = ${result}`);
}
);
it.each([
{ input: "123", expected: 123 },
{ input: "-123", expected: -123 }
])(
"should validate integer %s correctly",
({ input, expected }) => {
const result = numberValidator.validateInteger(input);
expect(result).toEqual(expected);
console.log(`Test with input = ${input}, expected = ${expected}, result = ${result}`);
}
);
it.each([
{ input: "123", expected: 123 },
{ input: "123.45", expected: 123.45 }
])(
"should validate positive number %s correctly",
({ input, expected }) => {
const result = numberValidator.validatePositive(input);
expect(result).toEqual(expected);
console.log(`Test with input = ${input}, expected = ${expected}, result = ${result}`);
}
);
it("should throw a validation exception when input is not a number", () => {
const input = "abc";
expect(() => numberValidator.validateNumber(input)).toThrowError("La valeur doit représenter un nombre");
});
it("should throw a validation exception when input is not an integer", () => {
const input = "123.45";
expect(() => numberValidator.validateInteger(input)).toThrowError("La valeur doit représenter un nombre entier");
});
it("should throw a validation exception when input is not a positive number", () => {
const input = "-123";
expect(() => numberValidator.validatePositive(input)).toThrowError("La valeur doit représenter un nombre positif");
});
});

View File

@ -0,0 +1,32 @@
export class ValidationException extends Error {
constructor(message: string) {
super(message);
this.name = 'ValidationException';
}
}
export class NumberValidation {
validateNumber(input: string): number {
const num = parseFloat(input);
if (isNaN(num)) {
throw new ValidationException('La valeur doit représenter un nombre');
}
return num;
}
validateInteger(input: string): number {
const num = this.validateNumber(input);
if (!Number.isInteger(num)) {
throw new ValidationException('La valeur doit représenter un nombre entier');
}
return num;
}
validatePositive(input: string): number {
const num = this.validateNumber(input);
if (num <= 0) {
throw new ValidationException('La valeur doit représenter un nombre positif');
}
return num;
}
}