How to mock moment() and moment().format using Jest?

Sometimes, we want to mock moment() and moment().format using Jest.

In this article, we’ll look at how to mock moment() and moment().format using Jest.

How to mock moment() and moment().format using Jest?

To mock moment() and moment().format using Jest, we can call jest.mock.

For instance, we write

const moment = require('moment');

jest.mock('moment', () => {
  return () => jest.requireActual('moment')('2022-01-01T00:00:00.000Z');
});

const tomorrow = () => {
  const now = moment();
  return now.add(1, 'days');
};

describe('tomorrow', () => {
  it('should return the next day in a specific format', () => {
    const date = tomorrow().format('YYYY-MM-DD');
    expect(date).toEqual('2022-01-02');
  });
});

to call jest.mock to mock the moment by passing in a function that returns a function that returns the result of call moment with the given date.

We use requireActual to import moment into our test code.

In the test, we call tomorrow to return the moment date object from the mocked function and call format with the given date.

And then we call expect to check the date string.

Conclusion

To mock moment() and moment().format using Jest, we can call jest.mock.