Skip to content Skip to sidebar Skip to footer

How Do I Mock Date.tolocaledatestring In Jest?

I have this codepiece in my React component, which renders an HTML in the end: new Date(createDate).toLocaleDateString() My local machine and our build machine have different loca

Solution 1:

I may be a bit late but hope it helps someone

let mockDate;

beforeAll(() => {
  mockDate = jest.spyOn(Date.prototype, 'toLocaleTimeString').mockReturnValue('2020-04-15');
});

afterAll(() => {
  mockDate.mockRestore();
});

Solution 2:

Can you wrap

newDate(createDate).toLocaleDateString()

in a function, pass it as prop to component and then mock it?

Solution 3:

Would the below code work well for you? I am mocking the date object this way.

const realDateToLocaleDateString = Date.prototype.toLocaleDateString.bind(global.Date);
const toLocaleDateStringStub = jest.fn(() =>'2020-04-15');
global.Date.prototype.toLocaleDateString = toLocaleDateStringStub;

const date = newDate();
console.log(date.toLocaleDateString()); // returns 2020-04-15global.Date.prototype.toLocaleDateString = realDateToLocaleDateString;

Post a Comment for "How Do I Mock Date.tolocaledatestring In Jest?"