3

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.

xx1xx
  • 1,834
  • 17
  • 16
asfandahmed1
  • 462
  • 5
  • 23
  • Possible duplicate of: https://stackoverflow.com/questions/55838798/mocking-moment-and-moment-format-using-jest – Tymek Aug 27 '19 at 12:27
  • why do you use `doMock`in favor of `.mock`? first one does not affect code been already `import`ed – skyboyer Aug 27 '19 at 12:32

3 Answers3

4

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;
});
asfandahmed1
  • 462
  • 5
  • 23
2

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'));
protoEvangelion
  • 4,355
  • 2
  • 29
  • 38
0

You call format not on moment, but on the result of moment().

    jest.doMock('moment', () => {
        const moment = () => ({
            format: () => mockedTime,
        })

        moment.tz = { // prevent 'Cannot read property of undefined'
            setDefault: () => {},
        }

        return moment
    });

Is this OK, or do you need more complicated mock in you app, including timezone?

Tymek
  • 3,000
  • 1
  • 25
  • 46