I need to have Jest unit test coverage for different date ranges, but could not find a proper way to let the Jest mock the date. It always run the source code and get system time, than the mocked one.
I have two files:
date.js
:
export function isDateBetween(startDate, endDate) {
const today = new Date();
return today >= startDate && today <= endDate;
}
getContent.js
:
let result;
if(isDateBetween('01-01', '01-05'))
{
result = 1;
}
else if (isDateBetween('01-06', '01-08'))
{
result = 2;
}
else if (isDateBetween('01-09', '05-11'))
{
result = 3;
}
export default result;
Now I am writing the unit test for getContent.js
.
I have tried:
beforeAll(() => {
jest.setSystemTime(new Date('2025-01-1'));
});
describe('getContent', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2025-01-1'));
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
it('should return correct content during 01-01 <=> 01-05', () => {
expect(result).toEqual(1);
});
});
but it won't pass, by debugging, I found it always run into date.js
file, and get system current date, which is March 17, the mock date won't affect the result.