close

How to mock a constructor like new Date()

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to mock a constructor like new Date() in javascript. So Here I am Explain to you all the possible methods here.

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

How to mock a constructor like new Date() ?

  1. How to mock a constructor like new Date() ?

    mock a constructor like new Date()
    You can use jasmine's spyOn (jest is built on jasmine) to mock Date's prototype for getDate as follows:
    spyOn(Date.prototype, 'setDate').and.returnValue(DATE_TO_TEST_WITH);

  2. mock a constructor like new Date()

    mock a constructor like new Date()
    You can use jasmine's spyOn (jest is built on jasmine) to mock Date's prototype for getDate as follows:
    spyOn(Date.prototype, 'setDate').and.returnValue(DATE_TO_TEST_WITH);

Method 1

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

spyOn(Date.prototype, 'setDate').and.returnValue(DATE_TO_TEST_WITH);

SpyOn will also clean up after it’s self and only lasts for the scope of the test.

Method 2

I’m using Typescript and the easiest implementaion I found was doing the following:

const spy = jest.spyOn(global, 'Date');  // spy on date
const date = spy.mock.instances[0];      // gets the date in string format

and then use new Date(date) for your tests

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