Skip to content Skip to sidebar Skip to footer

Jest Mock Moment() To Return Specific Date

I know this question has been asked multiple times. But I could not find the correct one for my case. I would like to mock the moment() to return a specific date. First, I mock by

Solution 1:

Mock the moment() function and its returned value. Use jest.requireActual('moment') to get the original module. Copy its properties and methods to the mocked one.

E.g.

index.js:

import moment from 'moment';

export function main() {
  const date = moment().format();
  console.log('date: ', date);
  const duration = moment.duration(2, 'minutes').humanize();
  console.log('duration: ', duration);
}

index.test.js:

import { main } from '.';
import moment from 'moment';

jest.mock('moment', () => {
  const oMoment = jest.requireActual('moment');
  const mm = {
    format: jest.fn(),
  };
  const mMoment = jest.fn(() => mm);
  for (let prop in oMoment) {
    mMoment[prop] = oMoment[prop];
  }
  return mMoment;
});

describe('68209029', () => {
  it('should pass', () => {
    moment().format.mockReturnValueOnce('2021-01-01T00:00:00.000Z');
    main();
  });
});

test result:

 PASS  examples/68209029/index.test.js (8.914 s)
  68209029
     should pass (20 ms)

  console.log
    date:  2021-01-01T00:00:00.000Z

      at Object.main (examples/68209029/index.js:5:11)

  console.log
    duration:  2 minutes

      at Object.main (examples/68209029/index.js:7:11)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.726 s

Take a look at the logs, we mocked the returned value of moment().format() correctly and keep using the original implementation of moment.duration(2, 'minutes').humanize() method.


Solution 2:

Additional to @slideshowp2's answer.

Just wanted to add another way for this:

jest.mock("moment", () => {
  // Require actual moment
  const actualMoment = jest.requireActual("moment");

  // Mocking moment func: 
  // moment() => return specific date, and it won't affect moment(date) with param.
  const mockMoment: any = (date: string | undefined) =>
    actualMoment(date || "2021-01-01T00:00:00.000Z");

  // Now assign all properties from actual moment to the mock moment, so that they can be used normally
  for (let prop in actualMoment) {
    mockMoment[prop] = actualMoment[prop];
  }
  return mockMoment;
});

Post a Comment for "Jest Mock Moment() To Return Specific Date"