Labs ICT
Pro Login

Mocking Modules

Replacing entire modules in tests.

Mocking Modules

Here is the thing about real applications. Your functions depend on other modules. They call APIs, read databases, send emails. You do not want your unit tests doing any of that. Module mocking lets you replace entire modules with fakes.

Trust me, once you understand jest.mock, your tests will become way more reliable and way faster.

Basic Module Mocking

jest.mock replaces an entire module with an automatic mock. Every function in that module becomes a jest.fn().


jest.mock('./database');

const db = require('./database');

db.getUser.mockReturnValue({ id: 1, name: 'Alice' });

it('fetches user from database', () => {
  const user = db.getUser(1);
  expect(user.name).toBe('Alice');
  expect(db.getUser).toHaveBeenCalledWith(1);
});
    

When you call jest.mock at the top of your test file, Jest replaces that module everywhere it is imported. Your code thinks it is talking to the real database, but it is talking to your mock.

Manual Mocks

Sometimes you want more control over what the mock does. You can create a __mocks__ folder next to your module and define the mock manually.


// __mocks__/database.js
module.exports = {
  getUser: jest.fn(),
  saveUser: jest.fn(),
  deleteUser: jest.fn()
};

// In your test file
jest.mock('./database');
const db = require('./database');

db.getUser.mockReturnValue({ id: 1, name: 'Alice' });
    

Partial Mocking

What if you only want to mock one function from a module and keep the rest real? Use jest.fn().mockImplementation to override specific methods.


jest.mock('./utils', () => ({
  ...jest.requireActual('./utils'),
  formatDate: jest.fn().mockReturnValue('2025-01-01')
}));

const utils = require('./utils');

it('uses mocked formatDate', () => {
  expect(utils.formatDate(new Date())).toBe('2025-01-01');
  expect(utils.calculateTotal(10, 2)).toBe(20);
});
    

See how we spread jest.requireActual to keep all the real functions and only override formatDate? That is partial mocking in action.

Try it Yourself →

Key Takeaways

  • jest.mock replaces entire modules with automatic mocks
  • Place manual mocks in a __mocks__ folder next to the module
  • Partial mocking lets you override specific functions while keeping others real
  • Module mocks prevent your tests from hitting real services
  • Use jest.requireActual to access the real module inside a partial mock