8

I'm really not sure that I'm doing this the right way!

I have a module under test and a test script. There are 2 functions in the MUT and one makes use of the other. I've tried to mock the module to replace the actual support function with a mock but it doesn't appear to be being called. Am I doing this right or can you not do this because of referential equality?

MUT

const total_users = 100;

export function getRandomIntInclusive(min=0, max=0) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive
}

export default function getUsername(name='user'){
  return `${name}_${getRandomIntInclusive(1, total_users)}`;
}

Test code:

import getUsername, {getRandomIntInclusive} from "../generateUsername";

const randomSpy = jest.spyOn(Math, 'random');


jest.mock('../generateUsername', () => {
  const originalModule = jest.requireActual('../generateUsername');

  return {
    __esModule: true,
    ...originalModule,
    getRandomIntInclusive: jest.fn((min=0, max=0) => 5), // <-- mock
  };
});

describe("The 'randomNumber' function", () => {
  beforeEach(() => {
    randomSpy.mockClear();
  });
  
  it("Generates a random number between 2 values (inclusive)", () => {
    randomSpy.mockReturnValue(0.9);
    expect(getUsername('john')).toBe(`john_91`);
    expect(randomSpy).toBeCalledTimes(1);
    expect(getRandomIntInclusive).toHaveBeenCalled(); // <-- execution of mock. Test fails here
  });

  it.todo('Throws an error if no name is passed')
});

Result:
     expect(jest.fn()).toHaveBeenCalled()

        Expected number of calls: >= 1
        Received number of calls:    0
user1775718
  • 1,499
  • 2
  • 19
  • 32
  • 4
    You can't mock a function that is defined in the same module it's used. Either move it to separate module for testability reasons, or consider these functions a single unit. – Estus Flask Oct 08 '21 at 06:43
  • Possible duplicate of https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest – Estus Flask Oct 08 '21 at 06:44
  • This worked for me: https://stackoverflow.com/a/45007792/2073774 – josebui Nov 25 '21 at 18:35
  • This worked for me: https://dev.to/rafaf/mock-imported-modules-in-jest-26ng – Rafa Romero Apr 25 '23 at 08:41

0 Answers0