Currently, I am in the process of creating unit tests using Jest to simulate various parts of the code that rely on the moment.js library. Just to provide some context, this is a Node+Express project developed in TypeScript with a supporting moment.d.ts
file.
The specific import and code block under scrutiny are:
import moment from 'moment';
const durationSinceLastEmail = moment.duration(moment(new Date())
.diff(moment(user.passwordRecoveryTokenRequestDate)));
The type information provided for the imported moment reference displays two actual items:
(alias) function moment(inp?: moment.MomentInput, format?: moment.MomentFormatSpecification, strict?: boolean): moment.Moment (+1 overload)
(alias) namespace moment
import moment
My implementation uses both forms: moment.duration
for the namespace and moment(...params)
for the function.
In general, my Jest mocking approach has not been very successful so far. For example:
jest.mock('moment', () => {
return jest.fn().mockImplementation( () => {
return {
duration: (...params) => mockDuration(...params)
};
});
});
I have managed to mock the duration function by directly substituting the duration method in a more forceful manner.
const originalDuration: Function = moment.duration;
mockDuration.mockImplementation((...params) => {
const original = originalDuration(...params);
// Apply mocks on returning object here
// or supply entirely new mock object
return original;
});
moment.duration = mockDuration;
To be honest, the code is quite messy, but it does help me reach halfway as it enables me to track calls to moment.duration(...params)
. However, all the methods attempted to mock the moment(...)
call have either failed or clashed with the above approach (and also failed).
The root of my issues seems to stem from the naming conflict. Therefore, my question would be:
1) Is there any way to separate these different references so they can be handled independently?
or
2) Is there an efficient approach for me to separately mock them or alternatively provide mocking for both the function and the namespace within a single mock object?