Jitrak Blog

How to mock Datetime in Jest

วิธีจำลอง Datetime ใน Jest

05 Oct 2025 11:00

Written by: Yosapol Jitrak

Use fake timers
Tags:

Datetime

Jest

Test double

TypeScript

ผมเชื่อว่าหลายคนเวลาเขียน Test ด้วย Jest น่าจะเคยเจอปัญหาเรื่องการ Mock Datetime ซึ่งถ้าเรา Search Google เราจะเจอหลายวิธีมาก สามารถไปดูตัวอย่างได้ที่:

ตั้งแต่ Jest 26 เป็นต้นมา เราสามารถ Stub Datetime ได้ง่าย ๆ แล้ว

Production code:

// getCurrentDatetime.ts
export const getCurrentDatetime = () => {
  return new Date();
};

Test code:

// getCurrentDatetime.spec.ts
import { getCurrentDatetime } from './getCurrentDatetime';

describe('mock global', () => {
  const currentDate = new Date('2021-01-01T00:00:00.000Z');
  jest.useFakeTimers();
  jest.setSystemTime(currentDate);

  afterAll(() => {
    jest.useRealTimers();
  });

  it('should be same date', () => {
    const datetime = getCurrentDatetime();
    expect(datetime).toEqual(currentDate);
  });
});

ผมว่าวิธีนี้เป็นวิธี Official จาก Jest เลย และดูง่ายที่สุด ไม่ต้องวุ่นวายอะไรมากครับ