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