I\'m unable to mock moment()
or moment().format
functions. I have states where, currentDateMoment
and currentDateFormatted
ar
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