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

后端 未结 7 2103
暗喜
暗喜 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:33

    Here is the solution:

    index.ts:

    import moment from 'moment';
    
    export function main() {
      return {
        currentDateMoment: moment().format(),
        currentDateFormatted: moment()
          .format('MM-DD-YYYY')
          .valueOf()
      };
    }
    

    index.spec.ts:

    import { main } from './';
    import moment from 'moment';
    
    jest.mock('moment', () => {
      const mMoment = {
        format: jest.fn().mockReturnThis(),
        valueOf: jest.fn()
      };
      return jest.fn(() => mMoment);
    });
    
    describe('main', () => {
      test('should mock moment() and moment().format() correctly ', () => {
        (moment().format as jest.MockedFunction)
          .mockReturnValueOnce('2018–01–30T12:34:56+00:00')
          .mockReturnValueOnce('01–30-2018');
        expect(jest.isMockFunction(moment)).toBeTruthy();
        expect(jest.isMockFunction(moment().format)).toBeTruthy();
        const actualValue = main();
        expect(actualValue).toEqual({ currentDateMoment: '2018–01–30T12:34:56+00:00', currentDateFormatted: '01–30-2018' });
      });
    });
    

    Unit test result with 100% coverage:

     PASS  src/stackoverflow/55838798/index.spec.ts
      main
        ✓ should mock moment() and moment().format() correctly  (7ms)
    
    ----------|----------|----------|----------|----------|-------------------|
    File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    ----------|----------|----------|----------|----------|-------------------|
    All files |      100 |      100 |      100 |      100 |                   |
     index.ts |      100 |      100 |      100 |      100 |                   |
    ----------|----------|----------|----------|----------|-------------------|
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        3.795s, estimated 8s
    

    Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55838798

提交回复
热议问题