VOOZH about

URL: https://www.geeksforgeeks.org/websites-apps/how-to-set-a-mock-date-in-jest/

⇱ How to Set a Mock Date in Jest? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Set a Mock Date in Jest?

Last Updated : 30 Sep, 2024

In developing unit tests frequently includes aspects where you must adjust or define specific environmental conditions. Mocking dates appear regularly in situations. Various systems and components rely on the present date and time; in testing that is reliable and repeatable, the current date must persist each time tests run. In your tests on Jest, you easily create mocks for dates due to its position among the superior JavaScript frameworks.

The guide explains how to establish and replicate a date in Jest addressing setup and real-life examples.

These are the following topics that we are going to discuss:

Why Mock Dates?

Dates are often used for time-sensitive features like:

  • Timestamps: Logging events or actions.
  • Scheduling: Performing functions or controls according to a specific time.
  • User Interfaces: Bringing up today's date or dates to come.

Fixing dates or counting on today's time could cause tests to either succeed or fail unpredictably as they are run. By using mocks for dates you can maintain test execution consistency and eliminate unexpected test outcomes.

Setting Up Jest for Mocking Dates

Let's examine how to set up a project that implements Jest for date jesting.

Step 1: Create a New Project

Begin by forming a fundamental Node.js project then introducing Jest.

  • Create a new directory for your project:
mkdir jest-mock-date-example
cd jest-mock-date-example
  • Initialize the project with npm:
npm init -y
  • Install Jest as a dev dependency:
npm install --save-dev jest

Project Structure:

πŸ‘ 1
Project Structure
  • Add test script in package.json file
 "scripts": {
"test": "jest"
},

Updated Dependencies:

{
"name": "jest-mock-date-example",
"version": "1.0.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^29.0.0"
}
}

Step 2: Write Code to Mock Date

Now, let’s create a simple code example where you will mock dates.

  • Create a date.js file in the src folder:
function getCurrentDate() {
return new Date();
}

module.exports = getCurrentDate;
  • Write the test in tests/date.test.js:
const getCurrentDate = require('../src/date');

describe('Mocking Date in Jest', () => {
beforeAll(() => {
const mockDate = new Date(2022, 0, 1); // Mock date: Jan 1, 2022
jest.spyOn(global, 'Date').mockImplementation(() => mockDate);
});

afterAll(() => {
jest.restoreAllMocks(); // Reset the Date object after tests
});

it('should return the mocked date', () => {
const currentDate = getCurrentDate();
expect(currentDate).toEqual(new Date(2022, 0, 1));
});
});

The Jest test suite will execute and show the results in the console.

Step 3: Step to run the code

npm run test

Output: Once the test runs, you should see an output like this:

PASS tests/date.test.js
Mocking Date in Jest
βœ“ should return the mocked date (1 ms)

Passing the test occurs as a result of the getCurrentDate returning the faked date for January 1st.

πŸ‘ 2

Common Pitfalls When Mocking Dates

  • Test Isolation: After completing each test ensure to refresh the mocks to avoid test disruptions. The afterEach or afterAll hooks from Jest support this task.
  • Time Zones: The system time zone affects JavaScript dates. Run your tests across diverse time zones or create a time zone replica in the tests.
  • Async Code: UseFakeTimers() from Jest allows you control the timing of tests when doing asynchronous work with dates or timers. In case of need remember to employ jest.advanceTimersByTime() to progress time manually.

Conclusion

To effectively test time-sensitive features; it is essential to mock dates in Jest. Incorporating time management in your test makes it trustworthy and repeatable at every phase from mocking just Date.now() to Jerusalem footing every state method with jest.useFakeTimers(). Treat forgotten reset of mocked objects as important so as not to disrupt future test runs.

Comment
Article Tags: