Age

class Age {
  private static readonly MIN_VALUE = 1;
  private static readonly MAX_VALUE = 180;
  private value: number;
 
  constructor(value: number) {
    this.validate(value);
    this.value = value;
  }
 
  getValue(): number {
    return this.value;
  }
 
  private validate(value: number): void {
    if (value < Age.MIN_VALUE || value > Age.MAX_VALUE) {
      throw new Error(
        `Age must be between ${Age.MIN_VALUE} and ${Age.MAX_VALUE}.`
      );
    }
  }
}
 
// Example usage
const age = new Age(20);
console.log(age.getValue()); // 20

Specs

import { Age } from "./Age"; // Import the Age class
 
describe("Age", () => {
  describe("constructor", () => {
    it("should create a valid Age instance with a value within the valid range", () => {
      const ageValue = 30;
      const age = new Age(ageValue);
      expect(age.getValue()).toBe(ageValue);
    });
 
    it("should throw an error for a value below the valid range", () => {
      const invalidValue = Age.MIN_VALUE - 1;
      expect(() => new Age(invalidValue)).toThrowError(
        `Age must be between ${Age.MIN_VALUE} and ${Age.MAX_VALUE}.`
      );
    });
 
    it("should throw an error for a value above the valid range", () => {
      const invalidValue = Age.MAX_VALUE + 1;
      expect(() => new Age(invalidValue)).toThrowError(
        `Age must be between ${Age.MIN_VALUE} and ${Age.MAX_VALUE}.`
      );
    });
  });
});