Recently whilst writing some unit tests in Jest, I had to test some code that took ISO date strings and converted them to formatted date strings, then code that converts them back to ISO strings before it’s sent to the server.
My first attempt was to use jest.mock
and mock each individual method. For some of the uses of moment where simple dates are being converted, it is easy enough to mock format
and other methods, but once you start chaining Moment methods, things get tricky from a mocking perspective.
This is some code that would be a nightmare to mock in Jest:
moment.utc().add('1', 'years').format('YYYY')
It turns out there is a much easier way to “mock” moment, without actually mocking it at all. You get a fully functional (well in my use case) version of Moment that actually converts dates and allows you to use chaining features.
jest.mock('moment', () => { const moment = jest.requireActual('moment'); return {default: moment }; });
You use the jest.requireActual
method to require the real Moment package, then you return it inside of an object. I am having to return it with default
because moment is being included in my application like this:
import moment from 'moment';
It’s a surprisingly simple, functional and elegant solution. It requires no absurd nested mock functions and code. If for whatever reason you need to override certain Moment methods, you can do so either inside of the mock declaration or on a per-use basis.
what if I want to mock moment() to set it to a specific date?
@Hugo,
You would mock the date underneath the hood that Moment uses, something like this:
“`
Date.now = jest.fn().mockReturnValue(new Date(‘2020-05-13T12:33:37.000Z’));
“`
Thank you, I had the same problem and this is elegant solution.