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;
});