How to mock moment.utc() for unit tests?
If you just want to override the utc function and nothing else is working, try adding this in your test suite
moment.prototype.utc = sinon.stub().callsFake(() => new Date(1970, 1, 1, 0, 0));
or
moment.prototype.utc = jest.fn().mockReturnValue(new Date(1970, 1, 1, 0, 0));
Moment lets you Change Time Source
If you want to change the time that Moment sees, you can specify a method that returns the number of milliseconds since the Unix epoch (January 1, 1970).
The default is:
moment.now = function () { return +new Date(); }
This will be used when calling
moment()
, and the current date used when tokens are omitted fromformat()
. In general, any method that needs the current time uses this under the hood.
So you can redefine moment.now
to get the custom output when you code executes moment.utc()
.