Jest Date Mock

1.0.10 · active · verified Tue Apr 21

jest-date-mock is a lightweight utility library for mocking the global `Date` object within Jest unit tests, simplifying the testing of time-sensitive logic. Currently at version 1.0.10, the library provides a minimalistic API to control the current time, allowing users to advance time by milliseconds (`advanceBy`), set the time to a specific timestamp (`advanceTo`), and clear the mock (`clear`). It also provides `Date.current()` to access the true system time while mocked. Releases are frequent for minor fixes and improvements, with version 1.0.9 adding support for `performance.now()` and version 1.0.8 ensuring `Date.name` remains 'Date' for compatibility with other libraries. Its key differentiator is its focused scope on `Date` and `performance.now()` mocking without interfering with other timers, contrasting with Jest's built-in `useFakeTimers` which handles a broader set of time-related APIs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting a fixed date, advancing time, resetting the date, and verifying both `Date.now()` and `performance.now()` are mocked, with `Date.current()` for real time access.

import { advanceBy, advanceTo, clear } from 'jest-date-mock';

describe('Date mocking', () => {
  // Set the date to a fixed point in time
  beforeEach(() => {
    advanceTo(new Date(2023, 10, 21, 10, 0, 0)); // November 21, 2023, 10:00:00 AM
  });

  // Clear the mock after each test to ensure isolation
  afterEach(() => {
    clear();
  });

  test('should return the mocked date and allow advancing time', () => {
    const initialTimestamp = Date.now();
    expect(new Date().getFullYear()).toBe(2023);
    expect(new Date().getMonth()).toBe(10); // November is month 10
    expect(new Date().getDate()).toBe(21);
    expect(Date.current()).not.toBe(initialTimestamp); // Date.current() gets the actual system time

    advanceBy(5000); // Advance time by 5 seconds
    expect(Date.now() - initialTimestamp).toBe(5000);

    advanceBy(60 * 1000); // Advance time by 1 minute
    expect(new Date().getMinutes()).toBe(1);

    advanceTo(new Date(2024, 0, 1, 0, 0, 0)); // Reset to Jan 1, 2024
    expect(new Date().getFullYear()).toBe(2024);
  });

  test('performance.now() should also be mocked and advance', () => {
    const initialPerformanceNow = performance.now();
    advanceBy(100);
    expect(performance.now() - initialPerformanceNow).toBe(100);
  });
});

view raw JSON →