As I am relatively new to unit testing, my primary objective is to employ function mocking, specifically for the add()
function. But I have encountered difficulties in achieving this goal.
// math.js
export const add = (a, b) => {
console.log("Original implementation");
return a + b;
}
// myModule.js
import { add } from './math';
export const multiplyAndAdd = (a, b, c) => {
const result = add(a, b);
return result * c;
};
// myModule.test.js
import { jest } from '@jest/globals';
import * as math from '../math';
import { multiplyAndAdd } from '../myModule';
// Mock the 'add' function
jest.mock('../math', () => ({
...jest.requireActual('../math'), // Use the actual implementation
add: jest.fn(),
}));
describe('multiplyAndAdd', () => {
it('multiplies and adds using the original add function', () => {
// Set up the mock implementation for 'add'
math.add.mockImplementation((a, b) => {
console.log("Fake calling...");
return a + b;
});
// Call the function you want to test
const result = multiplyAndAdd(2, 3, 4);
// Assert the result
expect(result).toBe(20);
});
});
Error: TypeError: math.add.mockImplementation is not a function
2
Answers
Here is an alternative you can try:
If you want to mock specific methods of an object or module exports while keeping the rest of the object’s original implementation, you can use jest.spyOn().
This approach lets you mock individual functions without affecting the rest of the module’s exports, providing more granular control over what is mocked.
Jest documentation recommends to use
__esModule: true
property: