This commit is contained in:
OMGiTzPomPom 2024-03-29 12:15:44 +01:00
parent b47e3608b5
commit e61ce661f5
2 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,29 @@
import { AgeValidation } from "./index";
describe("Test AgeValidation", () => {
const ageValidator = new AgeValidation();
it.each([
{ input: "30", expected: 30 },
{ input: "25", expected: 25 },
{ input: "50", expected: 50 },
])(
"should validate age %s correctly",
({ input, expected }) => {
const result = ageValidator.validateAge(input);
expect(result).toEqual(expected);
console.log(`Test with input = ${input}, expected = ${expected}, result = ${result}`);
}
);
it.each([
{ input: "17", expectedErrorMsg: "L'âge doit être compris entre 18 et 130 ans" },
{ input: "131", expectedErrorMsg: "L'âge doit être compris entre 18 et 130 ans" },
{ input: "abc", expectedErrorMsg: "L'âge doit représenter un nombre entier positif" },
])(
"should throw a validation exception for invalid age %s",
({ input, expectedErrorMsg }) => {
expect(() => ageValidator.validateAdult(input)).toThrowError(expectedErrorMsg);
}
);
});

View File

@ -0,0 +1,40 @@
export class AgeValidation {
validateAge(input: string): number {
try {
const age = this.validateNumber(input);
if (!Number.isInteger(age) || age < 0) {
throw new ValidationException("L'âge doit représenter un nombre entier positif");
}
return age;
} catch (error) {
if (error instanceof ValidationException) {
throw new ValidationException("L'âge doit représenter un nombre entier positif");
} else {
throw error;
}
}
}
validateAdult(input: string): number {
const age = this.validateAge(input);
if (age < 18 || age > 130) {
throw new ValidationException("L'âge doit être compris entre 18 et 130 ans");
}
return age;
}
private validateNumber(input: string): number {
const num = parseFloat(input);
if (isNaN(num)) {
throw new ValidationException('La valeur doit représenter un nombre');
}
return num;
}
}
export class ValidationException extends Error {
constructor(message: string) {
super(message);
this.name = 'ValidationException';
}
}