0
0
Node.jsframework~5 mins

Mocking modules and functions in Node.js

Choose your learning style9 modes available
Introduction

Mocking helps you test code by replacing real parts with fake ones. This way, you can check how your code works without using the real modules or functions.

When you want to test a function that calls another module without running the real module.
When the real module depends on slow or external services like databases or APIs.
When you want to simulate different responses from a function to see how your code handles them.
When you want to isolate a part of your code to find bugs easily.
When you want to avoid side effects like sending emails or writing files during tests.
Syntax
Node.js
import { jest } from '@jest/globals';

// Mock a whole module
jest.mock('module-name');

// Mock a specific function
import * as module from 'module-name';
jest.spyOn(module, 'functionName').mockImplementation(() => fakeValue);

jest.mock() replaces the whole module with a mock version.

jest.spyOn() lets you replace just one function inside a module.

Examples
This replaces the entire 'fs' module with a mock version for testing.
Node.js
jest.mock('fs');
This mocks only the 'add' function from the 'math' module to always return 10.
Node.js
import * as math from './math';
jest.spyOn(math, 'add').mockImplementation(() => 10);
This mocks the 'axios' module's 'get' method to return a fake resolved promise.
Node.js
jest.mock('axios', () => ({
  get: jest.fn(() => Promise.resolve({ data: 'mocked data' }))
}));
Sample Program

This example shows how to mock the fetchData function from a module. Instead of returning 'real data', it returns 'mocked data' during the test.

Node.js
import { jest } from '@jest/globals';

// Original module
export function fetchData() {
  return 'real data';
}

// Test file
import * as dataModule from './dataModule';

// Mock fetchData function
jest.spyOn(dataModule, 'fetchData').mockImplementation(() => 'mocked data');

console.log(dataModule.fetchData());
OutputSuccess
Important Notes

Always reset mocks after tests to avoid interference using jest.resetAllMocks().

Mocking helps keep tests fast and reliable by avoiding real external calls.

Use mocks carefully to not hide real bugs in your code.

Summary

Mocking replaces real modules or functions with fake ones for testing.

Use jest.mock() for whole modules and jest.spyOn() for specific functions.

Mocking helps test code in isolation and avoid slow or unreliable dependencies.