{"id":15343,"library":"jest-date-mock","title":"Jest Date Mock","description":"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.","status":"active","version":"1.0.10","language":"javascript","source_language":"en","source_url":"https://github.com/hustcc/jest-date-mock","tags":["javascript","mock","jest","jest-date","Date","datetime","timestamp","typescript"],"install":[{"cmd":"npm install jest-date-mock","lang":"bash","label":"npm"},{"cmd":"yarn add jest-date-mock","lang":"bash","label":"yarn"},{"cmd":"pnpm add jest-date-mock","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is a development dependency specifically designed for use with the Jest testing framework to mock `Date` objects during unit tests.","package":"jest","optional":false}],"imports":[{"note":"While CommonJS `require` works for the main setup file, named imports are preferred for API functions in modern Jest/TypeScript setups.","wrong":"const { advanceTo } = require('jest-date-mock');","symbol":"advanceTo","correct":"import { advanceTo } from 'jest-date-mock';"},{"note":"ESM named imports are the idiomatic way to access utility functions.","wrong":"require('jest-date-mock').advanceBy;","symbol":"advanceBy","correct":"import { advanceBy } from 'jest-date-mock';"},{"note":"For Jest's `setupFiles`, both ESM `import` and CommonJS `require` statements are supported directly within the setup file. The library provides TypeScript types.","wrong":"require('jest-date-mock');","symbol":"setupFiles","correct":"import 'jest-date-mock';"}],"quickstart":{"code":"import { advanceBy, advanceTo, clear } from 'jest-date-mock';\n\ndescribe('Date mocking', () => {\n  // Set the date to a fixed point in time\n  beforeEach(() => {\n    advanceTo(new Date(2023, 10, 21, 10, 0, 0)); // November 21, 2023, 10:00:00 AM\n  });\n\n  // Clear the mock after each test to ensure isolation\n  afterEach(() => {\n    clear();\n  });\n\n  test('should return the mocked date and allow advancing time', () => {\n    const initialTimestamp = Date.now();\n    expect(new Date().getFullYear()).toBe(2023);\n    expect(new Date().getMonth()).toBe(10); // November is month 10\n    expect(new Date().getDate()).toBe(21);\n    expect(Date.current()).not.toBe(initialTimestamp); // Date.current() gets the actual system time\n\n    advanceBy(5000); // Advance time by 5 seconds\n    expect(Date.now() - initialTimestamp).toBe(5000);\n\n    advanceBy(60 * 1000); // Advance time by 1 minute\n    expect(new Date().getMinutes()).toBe(1);\n\n    advanceTo(new Date(2024, 0, 1, 0, 0, 0)); // Reset to Jan 1, 2024\n    expect(new Date().getFullYear()).toBe(2024);\n  });\n\n  test('performance.now() should also be mocked and advance', () => {\n    const initialPerformanceNow = performance.now();\n    advanceBy(100);\n    expect(performance.now() - initialPerformanceNow).toBe(100);\n  });\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"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\"] }`.","message":"Forgetting to add `jest-date-mock` to Jest's `setupFiles` configuration will prevent `Date` from being mocked, leading to tests failing due to incorrect time values.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"`jest-date-mock` specifically mocks `Date` and `performance.now()`. It does not mock other time-related functions like `setTimeout`, `setInterval`, or `requestAnimationFrame`. For these, Jest's built-in `jest.useFakeTimers()` is typically required.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade `jest-date-mock` to version `1.0.8` or newer to ensure `Date.name` is correctly preserved as 'Date'.","message":"Prior to version 1.0.8, `jest-date-mock` incorrectly set `Date.name` to an empty string, which could break third-party libraries (e.g., Mongoose) that rely on `Date.name === 'Date'`. This was a silent behavior change.","severity":"breaking","affected_versions":"<1.0.8"},{"fix":"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()`.","message":"Calling `clear()` permanently shuts down the mock system for the current test scope. If not properly managed (e.g., by calling `advanceTo()` or reloading the mock in subsequent tests or `beforeEach` blocks), subsequent tests may unexpectedly receive real date values or encounter errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"Timezone differences can cause inconsistent date test results across different environments (local machine vs. CI/CD).","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"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.","cause":"`jest-date-mock` was not correctly configured in Jest's `setupFiles`, or the setup file itself was not properly loaded.","error":"TypeError: Date.now is not a function"},{"fix":"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`.","cause":"The `Date` object was not mocked or was reset unexpectedly, causing tests to use the actual system time. This can also happen if `clear()` was called without a subsequent `advanceTo()` in a later test.","error":"Expected date to be ... but received ... (time difference)"},{"fix":"Upgrade `jest-date-mock` to version `1.0.8` or newer to resolve the `Date.name` inconsistency.","cause":"Using an older version of `jest-date-mock` (prior to v1.0.8) which incorrectly altered the `Date.name` property, affecting libraries that check this for type validation.","error":"The value of `Date.name` is not 'Date'."},{"fix":"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`.","cause":"`performance.now()` mocking was added in version 1.0.9. Older versions do not mock this API. Alternatively, `performance` might not be defined in the test environment.","error":"performance.now() returns real time or is undefined."}],"ecosystem":"npm"}