最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jest setSystemTime not working with global scope, always get system date first, ignore the mock date - Stack Overfl

programmeradmin4浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论