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.
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;
});
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With