0
0
Node.jsframework~30 mins

Mocking modules and functions in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Mocking Modules and Functions in Node.js
📖 Scenario: You are building a simple Node.js app that fetches user data from an external module. To test your app without calling the real external module, you will learn how to mock modules and functions.
🎯 Goal: Create a test file that mocks a user data module and its function to return fixed data. This helps you test your app code without relying on the real module.
📋 What You'll Learn
Create a module called userData.js exporting a function getUser that returns a user object.
Create a test file app.test.js that mocks userData.js.
Mock the getUser function to return a fixed user object.
Write a test that uses the mocked function and checks the returned user data.
💡 Why This Matters
🌍 Real World
Mocking modules and functions is essential for testing Node.js applications without relying on external services or complex dependencies.
💼 Career
Understanding mocking is a key skill for backend developers and testers to write reliable unit tests and maintain code quality.
Progress0 / 4 steps
1
Create the userData module
Create a file called userData.js that exports a function named getUser. This function should return an object with id set to 1 and name set to 'Alice'.
Node.js
Need a hint?

Use export function getUser() and return the object { id: 1, name: 'Alice' }.

2
Set up the test file and import the module
Create a file called app.test.js. Import the getUser function from ./userData.js. Also, import jest for mocking.
Node.js
Need a hint?

Use ES module import syntax to import getUser and jest.

3
Mock the getUser function to return fixed data
Use jest.mock to mock the ./userData.js module. Inside the mock, replace getUser with a jest mock function that returns { id: 2, name: 'Bob' }.
Node.js
Need a hint?

Use jest.mock with a factory function returning an object with getUser mocked.

4
Write a test using the mocked getUser function
Write a test named 'returns mocked user' using test(). Inside, call getUser() and check that the returned object has id equal to 2 and name equal to 'Bob' using expect and toEqual.
Node.js
Need a hint?

Use test() with a callback that calls getUser() and asserts the returned object.