Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a mock date in Jest?

People also ask

How do you mock a date with Jest?

import { advanceBy, advanceTo } from 'jest-date-mock'; test('usage', () => { advanceTo(new Date(2018, 5, 27, 0, 0, 0)); // reset to date time. const now = Date.

How do you mock date a Jest class?

You can use jasmine's spyOn (jest is built on jasmine) to mock Date's prototype for getDate as follows: spyOn(Date. prototype, 'setDate').

How do you mock a constructor like a new date?

To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime method. beforeAll(() => { jest. useFakeTimers("modern"); jest. setSystemTime(new Date(2022, 3, 1)); }); afterAll(() => { jest.

What does mock date mean?

Introducing Mock DatesTalk, flirt, practice asking for a second date -- just about everything you would do on a usual date. Afterwards, spend another 50-minutes debriefing the date in private, reviewing your dating strengths and weaknesses.


Since momentjs uses Date internally, you can just overwrite the Date.now function to always return the same moment.

Date.now = jest.fn(() => 1487076708000) //14.02.2017

or

Date.now = jest.fn(() => new Date(Date.UTC(2017, 1, 14)).valueOf())

As of Jest 26 this can be achieved using "modern" fake timers without needing to install any 3rd party modules: https://jestjs.io/blog/2020/05/05/jest-26#new-fake-timers

jest
  .useFakeTimers()
  .setSystemTime(new Date('2020-01-01').getTime());

If you want the fake timers to be active for all tests, you can set timers: 'modern' in your configuration: https://jestjs.io/docs/configuration#timers-string

EDIT: As of Jest 27 modern fake timers is the default, so you can drop the argument to useFakeTimers.


jest.spyOn works for locking time:

let dateNowSpy;

beforeAll(() => {
    // Lock Time
    dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => 1487076708000);
});

afterAll(() => {
    // Unlock Time
    dateNowSpy.mockRestore();
});

MockDate can be used in jest tests to change what new Date() returns:

var MockDate = require('mockdate');
// I use a timestamp to make sure the date stays fixed to the ms
MockDate.set(1434319925275);
// test code here
// reset to native Date()
MockDate.reset();

For those who want to mock methods on a new Date object you can do the following:

beforeEach(() => {
    jest.spyOn(Date.prototype, 'getDay').mockReturnValue(2);
    jest.spyOn(Date.prototype, 'toISOString').mockReturnValue('2000-01-01T00:00:00.000Z');
});

afterEach(() => {
    jest.restoreAllMocks()
});