close

How do I set a mock date in Jest?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How do I set a mock date in Jest? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How do I set a mock date in Jest ?

  1. How do I set a mock date in Jest ?

    do I set a mock date in Jest Since momentjs uses Date internally, you can just overwrite the Date.now function to always return the same moment.

  2. do I set a mock date in Jest

    do I set a mock date in Jest Since momentjs uses Date internally, you can just overwrite the Date.now function to always return the same moment.

Method 1

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())

Method 2

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.restoreAll()
});

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment