skip to Main Content
import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns";

export class DateService {

  public getDaysInMonth(month?: Date) {
    return getDaysInMonth(month || new Date());
  }

How do I test it? How can I access the function implementation?

2

Answers


  1. jest
      .useFakeTimers()
      .setSystemTime(new Date('2020-01-01'));
    
    describe("DateService", () => {
      test("getDaysInmonth", () => {
        // arrange
        const dateService = new DateService();
        const expected = new Date('2020-01-01');
    
        // act
        const actual = dateService.getDaysInMonth();
        
        // assert
        expect(actual).toEqual(expected);
      }
    })
    
    Login or Signup to reply.
  2. import the class:

    import { DateService } from "./DateService";
    

    setup your describe block and instantiate the DateService

    describe("DateService", () => {
      const dateService = new DateService();
    

    And then test results:

     it("should return the number of days", () => {
      const month = new Date(2022, 4); // May 2022
      const daysInMonth = dateService.getDaysInMonth(month);
      expect(daysInMonth).toBe(31);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search