1

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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
user1283776
  • 19,640
  • 49
  • 136
  • 276
  • You can't. Either move a function to another module, or refer it exclusively as object method where it's used, or treat these functions as a single unit. – Estus Flask Dec 16 '20 at 00:20

0 Answers0