skip to Main Content

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


  1. Here is an alternative you can try:

    import * as math from '../math';
    
    beforeEach(() => {
      // Spy on and mock only the add method
      jest.spyOn(math, 'add').mockImplementation((a, b) => a + b);
    });
    
    afterEach(() => {
      // Restore the original implementation after each test if needed
      jest.restoreAllMocks();
    });
    

    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.

    Login or Signup to reply.
  2. Jest documentation recommends to use __esModule: true property:

    jest.mock('../math', () => ({
      __esModule: true,
      ...jest.requireActual('../math'),
      add: jest.fn(),
    }));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search