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

后端 未结 7 2105
暗喜
暗喜 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:36

    To Mock Moment().format(),startOf() , isValid() or isAfter() etc. Can refer below example.

    jest.mock('moment', () => {
        
        const momentParams = {
            format: jest.fn(() => '10/04/2020'),
            startOf: jest.fn().mockReturnThis(),
            isAfter: jest.fn().mockReturnValue(true),
            isValid: jest.fn().mockReturnValue(true)
        };
    
       const fn = jest.fn(newMoment => {
            momentParams.format = jest.fn(() => newMoment);
            return momentParams;
       });
    
       return fn;
    });
    

    And last you can write a test case like this. eg.

     test('should returned mocked value for isAfter()', async () => {
        jest.spyOn(moment(), 'isAfter').mockReturnValue(false);
        const response = moment().isAfter();
        expect(response).toBe(false)
    })
    

提交回复
热议问题