The other answers tell you how to mock moment, but you don't need to mock moment to test that code. You probably shouldn't, in fact; it's a complicated third party interface you don't own and mocking it couples your tests to it, you end up testing implementation rather than behaviour.
Rather than calling moment()
without any arguments, call it with the current date (per https://momentjscom.readthedocs.io/en/latest/moment/01-parsing/01-now/ moment()
is basically moment(new Date())
). Then that current date comes from a function you do own:
const { getCurrentDate } = require('path/to/utils');
export const createSomething =() => ({
currentDateMoment: moment(getCurrentDate()),
currentDateFormatted: moment(getCurrentDate()).format('MM-DD-YYYY'),
});
so you can trivially mock that out in the tests:
const { createSomething } = require('path/to/impl');
const { getCurrentDate } = require('path/to/utils');
jest.mock('path/to/utils');
it('formats the data correctly', () => {
getCurrentDate.mockReturnValue(new Date(2021, 3, 29));
const { currentDateFormatted } = createSomething();
expect(currentDateFormatted).toEqual('2021-04-29');
});
Now the test doesn't refer to moment, which has become an implementation detail, at all. If there's a breaking future change to the moment API you'll find out about it, because your tests will fail; they'd misleadingly pass if it was mocked. If you want to switch to a different library you can do so, confident that the tests mean the behaviour is still correct (here's an example doing the same thing with DayJS).
moment
,Date
) you don't own, and treat time as a dependency. – Disoblige