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.
npm install jest-date-mockVerified import paths — ran on the pinned version, not inferred.
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.
Ensure `jest-date-mock` is listed in the `setupFiles` array within your `jest` configuration in `package.json` or linked via a setup file. Example: `"jest": { "setupFiles": ["jest-date-mock"] }`.If your tests depend on mocking `setTimeout` or other timers, use `jest.useFakeTimers()` in conjunction with, or instead of, `jest-date-mock`. Consider `jest.setSystemTime()` and `jest.advanceTimersByTime()` for Jest's native date mocking.
Upgrade `jest-date-mock` to version `1.0.8` or newer to ensure `Date.name` is correctly preserved as 'Date'.
Always ensure your mock state is reset between tests. Use `advanceTo()` at the beginning of each test or in a `beforeEach` hook to establish a consistent starting point, rather than solely relying on `clear()`.
Set a consistent timezone for your Jest tests. Add `process.env.TZ = 'UTC';` (or your desired timezone) to your Jest `setupFiles` or directly in your `jest.config.js` to standardize date calculations.
Verify that `jest-date-mock` is listed in `jest.setupFiles` in your `package.json` or that the custom setup file requiring it is correctly path-referenced.
Ensure `jest-date-mock` is correctly set up globally, and use `advanceTo(new Date(someValue))` at the beginning of each test or in a `beforeEach` hook to ensure a consistent starting date for every test. Explicitly use `clear()` in an `afterEach` only if you re-initialize the mock in `beforeEach`.
Upgrade `jest-date-mock` to version `1.0.8` or newer to resolve the `Date.name` inconsistency.
Upgrade `jest-date-mock` to version `1.0.9` or higher. If `performance` is still an issue, ensure your test environment (e.g., JSDOM in Jest) supports `window.performance`.