这是解决方案:
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<any>)
.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' });
});
});
100% 覆盖率的单元测试结果:
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
源代码:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55838798