Jest Mock Moment() To Return Specific Date
I know this question has been asked multiple times. But I could not find the correct one for my case. I would like to mock the moment() to return a specific date. First, I mock by
Solution 1:
Mock the moment()
function and its returned value. Use jest.requireActual('moment')
to get the original module. Copy its properties and methods to the mocked one.
E.g.
index.js
:
import moment from'moment';
exportfunctionmain() {
const date = moment().format();
console.log('date: ', date);
const duration = moment.duration(2, 'minutes').humanize();
console.log('duration: ', duration);
}
index.test.js
:
import { main } from'.';
import moment from'moment';
jest.mock('moment', () => {
const oMoment = jest.requireActual('moment');
const mm = {
format: jest.fn(),
};
const mMoment = jest.fn(() => mm);
for (let prop in oMoment) {
mMoment[prop] = oMoment[prop];
}
return mMoment;
});
describe('68209029', () => {
it('should pass', () => {
moment().format.mockReturnValueOnce('2021-01-01T00:00:00.000Z');
main();
});
});
test result:
PASSexamples/68209029/index.test.js(8.914s)68209029✓shouldpass(20ms)console.logdate:2021-01-01T00:00:00.000ZatObject.main(examples/68209029/index.js:5:11)console.logduration:2minutesatObject.main(examples/68209029/index.js:7:11)Test Suites:1passed,1totalTests:1passed,1totalSnapshots:0totalTime:9.726s
Take a look at the logs, we mocked the returned value of moment().format()
correctly and keep using the original implementation of moment.duration(2, 'minutes').humanize()
method.
Solution 2:
Additional to @slideshowp2's answer.
Just wanted to add another way for this:
jest.mock("moment", () => {
// Require actual momentconst actualMoment = jest.requireActual("moment");
// Mocking moment func: // moment() => return specific date, and it won't affect moment(date) with param.constmockMoment: any = (date: string | undefined) =>actualMoment(date || "2021-01-01T00:00:00.000Z");
// Now assign all properties from actual moment to the mock moment, so that they can be used normallyfor (let prop in actualMoment) {
mockMoment[prop] = actualMoment[prop];
}
return mockMoment;
});
Post a Comment for "Jest Mock Moment() To Return Specific Date"