The file I am writing tests for is exporting the following
module.exports = {
groupProducts,
test: {
getNow,
},
};
I know how to mock getNow
when I am calling it from my test:
describe('groupProducts', () => {
it('groups productInfo ids into today or future date groups', () => {
// Arrange
const expectedResult = {};
const nowSpy = jest.spyOn(test, 'getNow').mockReturnValue(dayjs('2001-02-03T04:05:06.007Z'));
// Act
const dateToIds = groupProducts(productInfos, test.getNow());
// Expect
expect(dateToIds).toEqual(expectedResult);
// Restore
nowSpy.mockRestore();
});
});
But how do I mock getNow
when it is called from the exercised function and not from the test?
describe('groupProducts', () => {
it('groups productInfo ids into today or future date groups', () => {
// Arrange
const expectedResult = {};
const nowSpy = jest.spyOn(test, 'getNow').mockReturnValue(dayjs('2001-02-03T04:05:06.007Z'));
// Act
const dateToIds = groupProducts(productInfos);
// Expect
expect(dateToIds).toEqual(expectedResult);
// Restore
nowSpy.mockRestore();
});
});
groupProducts
calls real getNow
. The spy doesn't work as I had intended.