Monday, May 20, 2024
131
rated 0 times [  135] [ 4]  / answers: 1 / hits: 7286  / 5 Years ago, tue, august 27, 2019, 12:00:00

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.


More From » unit-testing

 Answers
2

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

[#6447] Friday, August 23, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Fri, Jan 25, 19, 00:00, 5 Years ago
;