Skip to main content

> Jitrak Blog

>_ How to mock Datetime in Jest

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

@ Yosapol Jitrak | 5 Oct 2025 11:00

ผมเชื่อว่าหลายคนเวลาเขียน 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 เลย และดูง่ายที่สุด ไม่ต้องวุ่นวายอะไรมากครับ

— EOF —

Post feedback

~/feedback

Comments

~/shortcuts

> Keyboard shortcuts

  • Toggle this help?H
  • Back to topT
  • Hold to scroll downJ
  • Hold to scroll upK
  • Forward (newer post or next page)F
  • Back (older post or previous page)B
  • Close helpEsc

Navigation

  • Blog (post list)L
  • AboutA
  • PlayP
  • Tags,