Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock using jest moment().format is returning current date instead of mocked date

I am trying to mock moment library's format function using jest. I have following code in my test file.

app.spec.js:

jest.mock('moment', () => {
    const moment = () => ({
        format: () => mockedTime
    });
    moment.tz = {
        setDefault: () => {}
    };
    moment.tz.setDefault('Asia/Singapore');
    return moment;
});

app.js:

moment.tz.setDefault(TIMEZONE);
moment().format('YYYYMMDD');

it is generating following output:

 - "date": "20190825", // mocked date
 - "date": "20190827", // result value

the expected output should be:

 - "date": "20190825", // mocked date
 - "date": "20190825", // result value

Can anyone help me point out what's wrong with the code?

Thanks.

like image 743
asfandahmed1 Avatar asked Nov 15 '25 14:11

asfandahmed1


2 Answers

Mocking 'moment-timezone' instead of 'moment fixed it.

jest.mock('moment-timezone', () => {
    const moment = () => ({
        format: () => mockedTime
    });
    moment.tz = {
        setDefault: () => {}
    };
    moment.tz.setDefault('Asia/Singapore');
    return moment;
});
like image 111
asfandahmed1 Avatar answered Nov 17 '25 05:11

asfandahmed1


The available answers did not work for my case. Mocking the underlying Date.now function however did as this answer suggests: https://stackoverflow.com/a/61659370/6502003

Date.now = jest.fn(() => new Date('2020-05-13T12:33:37.000Z'));
like image 44
protoEvangelion Avatar answered Nov 17 '25 03:11

protoEvangelion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!