Mocking moment() and moment().format using jest

后端 未结 7 2104
暗喜
暗喜 2021-02-12 19:46

I\'m unable to mock moment() or moment().format functions. I have states where, currentDateMoment and currentDateFormatted ar

7条回答
  •  孤独总比滥情好
    2021-02-12 20:23

    You can mock Moment to return a specific date, then format don't have to be mocked.

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

    By doing so, any call to Moment() will always return a moment object with date set to 2020-01-01 00:00:00

    Here is an example with a function that return the date of tomorrow and the test for this function.

    const moment = require('moment');
    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('2020-01-02');
      });
    });
    

提交回复
热议问题