我如何用Jest测试这个方法?

vybvopom  于 2023-03-16  发布在  Jest
关注(0)|答案(2)|浏览(165)
import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns";

export class DateService {

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

我如何测试它?我如何访问函数实现?

kmb7vmvb

kmb7vmvb1#

导入类:

import { DateService } from "./DateService";

设置描述块并示例化DateService

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

然后测试结果:

it("should return the number of days", () => {
  const month = new Date(2022, 4); // May 2022
  const daysInMonth = dateService.getDaysInMonth(month);
  expect(daysInMonth).toBe(31);
});
atmip9wb

atmip9wb2#

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);
  }
})

相关问题