Bird
Raised Fist0
Node.jsframework~20 mins

Mocking modules and functions in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of Mocking Modules
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when mocking a module function with Jest?
Consider the following Node.js module and test code using Jest. What will be the output of the test?
Node.js
// math.js
export function add(a, b) {
  return a + b;
}

// math.test.js
import * as math from './math';

test('mock add function', () => {
  jest.spyOn(math, 'add').mockImplementation(() => 42);
  const result = math.add(1, 2);
  console.log(result);
});
A42
B3
Cundefined
DTypeError: math.add is not a function
Attempts:
2 left
💡 Hint
Think about what jest.spyOn with mockImplementation does to the original function.
📝 Syntax
intermediate
2:00remaining
Which option correctly mocks a default export function in Jest?
Given a module with a default export function, which Jest mock syntax correctly mocks it?
Node.js
// greet.js
export default function greet(name) {
  return `Hello, ${name}!`;
}

// greet.test.js
import greet from './greet';

jest.mock('./greet', () => {
  // Fill in the mock implementation
});
Areturn { greet: jest.fn(() => 'Hi!') };
Breturn jest.fn(() => 'Hi!');
Creturn { default: jest.fn(() => 'Hi!') };
D;)'!iH' >= )((nf.tsej nruter
Attempts:
2 left
💡 Hint
Default exports are properties named 'default' in the mock object.
🔧 Debug
advanced
2:00remaining
Why does this Jest mock not replace the imported function?
Look at this test code. Why does the mock not replace the original function when called?
Node.js
// utils.js
export function fetchData() {
  return 'real data';
}

// app.js
import { fetchData } from './utils';
export function getData() {
  return fetchData();
}

// app.test.js
import { getData } from './app';
import * as utils from './utils';

jest.mock('./utils');
test('mock fetchData', () => {
  utils.fetchData.mockReturnValue('mocked data');
  const result = getData();
  console.log(result);
});
ABecause utils.fetchData is not imported correctly.
BBecause fetchData is not a mock function and cannot use mockReturnValue.
CBecause jest.mock must be called at the top level, not inside the test.
DBecause getData imports fetchData before the mock is applied, so it uses the original.
Attempts:
2 left
💡 Hint
Consider when the module is imported and when the mock is applied.
❓ state_output
advanced
2:00remaining
What is the output after resetting mocks in Jest?
Given this test code, what will be the output of the console.log statements?
Node.js
const utils = {
  getNumber: () => 5
};

jest.mock('./utils', () => ({
  getNumber: jest.fn(() => 10)
}));

import { getNumber } from './utils';

console.log(getNumber());

getNumber.mockReset();

console.log(getNumber());
A
10
5
B
10
undefined
C
10
10
D
5
undefined
Attempts:
2 left
💡 Hint
What does mockReset do to the mock function's implementation?
🧠 Conceptual
expert
3:00remaining
Which statement about mocking ES modules with Jest is true?
Select the correct statement about mocking ES modules and their functions in Jest.
AYou can mock named exports by replacing the entire module with jest.mock and returning an object with the named exports as jest.fn().
Bjest.spyOn cannot be used on ES module functions because they are read-only.
CTo mock a default export, you must always use jest.fn() directly without wrapping in an object.
DJest automatically mocks all ES module functions without any configuration.
Attempts:
2 left
💡 Hint
Think about how jest.mock replaces modules and how named exports are mocked.

Practice

(1/5)
1. What is the main purpose of mocking modules or functions in Node.js testing?
easy
A. To replace real modules or functions with fake ones for isolated testing
B. To speed up the production code execution
C. To permanently change the behavior of modules in the app
D. To automatically generate documentation for modules

Solution

  1. Step 1: Understand mocking concept

    Mocking means replacing real code with fake versions to test parts independently.
  2. Step 2: Identify purpose in testing

    This helps avoid slow or unreliable dependencies and focuses tests on the code itself.
  3. Final Answer:

    To replace real modules or functions with fake ones for isolated testing -> Option A
  4. Quick Check:

    Mocking = isolated testing [OK]
Hint: Mocking means faking parts to test code alone [OK]
Common Mistakes:
  • Thinking mocking speeds up production code
  • Believing mocking changes app behavior permanently
  • Confusing mocking with documentation generation
2. Which of the following is the correct syntax to mock an entire module named utils using Jest?
easy
A. jest.spyOn('utils')
B. jest.fake('utils')
C. jest.mock('utils')
D. mock('utils')

Solution

  1. Step 1: Recall Jest mocking syntax

    Jest uses jest.mock('moduleName') to mock entire modules.
  2. Step 2: Match syntax to options

    Only jest.mock('utils') uses the correct jest.mock() function with the module name.
  3. Final Answer:

    jest.mock('utils') -> Option C
  4. Quick Check:

    jest.mock() mocks modules [OK]
Hint: Use jest.mock('moduleName') to mock whole modules [OK]
Common Mistakes:
  • Using jest.spyOn for whole modules instead of functions
  • Trying mock() or jest.fake() which don't exist
  • Passing module name incorrectly as a variable
3. Given the code below, what will be the output of console.log(fetchData()) after mocking?
import * as api from './api';

jest.mock('./api', () => ({
  fetchData: () => 'mocked data'
}));

console.log(api.fetchData());
medium
A. 'real data'
B. 'mocked data'
C. undefined
D. Error: fetchData is not a function

Solution

  1. Step 1: Understand jest.mock replacement

    The jest.mock call replaces the entire './api' module with the provided object.
  2. Step 2: Check the mocked function return

    The mocked fetchData returns the string 'mocked data'.
  3. Final Answer:

    'mocked data' -> Option B
  4. Quick Check:

    Mocked function returns mocked data [OK]
Hint: Mocked functions return what you define in jest.mock [OK]
Common Mistakes:
  • Expecting original function output
  • Assuming undefined because of mocking
  • Confusing import and mock timing
4. What is wrong with this Jest mocking code snippet?
import * as math from './math';

jest.spyOn(math, 'add');

math.add.mockReturnValue(10);

console.log(math.add(2, 3));
medium
A. No error, the code works and logs 10
B. mockReturnValue cannot be used on spy without mockImplementation
C. The spy is created correctly, but math.add is not mocked properly
D. jest.spyOn should be called after calling math.add

Solution

  1. Step 1: Understand jest.spyOn usage

    jest.spyOn creates a mock function that can be controlled.
  2. Step 2: Check mockReturnValue usage

    Calling mockReturnValue(10) on the spy sets the return value to 10.
  3. Final Answer:

    No error, the code works and logs 10 -> Option A
  4. Quick Check:

    spyOn + mockReturnValue works [OK]
Hint: spyOn returns a mock you can control directly [OK]
Common Mistakes:
  • Thinking spyOn needs mockImplementation first
  • Believing spyOn must be after function call
  • Assuming spyOn does not mock return values
5. You want to mock only the sendEmail function from the notifications module to return true during tests, but keep other functions real. Which is the best approach?
hard
A. Use jest.mock('notifications') and redefine all functions manually
B. Replace the entire module with a fake object returning true for sendEmail
C. Import sendEmail separately and overwrite it directly
D. Use jest.spyOn(notifications, 'sendEmail').mockReturnValue(true)

Solution

  1. Step 1: Understand partial mocking need

    We want to mock only one function, not the whole module.
  2. Step 2: Use jest.spyOn for specific function

    jest.spyOn allows mocking a single function while keeping others real.
  3. Final Answer:

    Use jest.spyOn(notifications, 'sendEmail').mockReturnValue(true) -> Option D
  4. Quick Check:

    spyOn mocks single function only [OK]
Hint: Use jest.spyOn to mock one function, not whole module [OK]
Common Mistakes:
  • Mocking entire module unnecessarily
  • Trying to overwrite imported functions directly
  • Not using spyOn for partial mocks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard