Member-only story
Mastering Jest: Day 4 — Mocking Functions and Modules
Introduction
Welcome to Day 4 of our Jest journey! Yesterday, we explored testing asynchronous code. Today, we’ll delve into mocking functions and modules, a crucial aspect of unit testing that ensures your tests are isolated and reliable.
Why Mocking Matters
In real-world applications, functions often depend on external services, modules, or functions. Mocking allows you to replace these dependencies with controlled substitutes, ensuring your tests are fast and deterministic.
Mocking Functions with Jest
Jest provides powerful tools to mock functions. Here’s a simple example:
// user.js
const fetchData = require('./fetchData');
async function getUserData(userId) {
const data = await fetchData(userId);
return data.user;
}
module.exports = getUserData;
To test getUserData
, we need to mock fetchData
:
// user.test.js
const getUserData = require('./user');
const fetchData = require('./fetchData');
jest.mock('./fetchData'); // Mock the fetchData module
test('returns user data', async () => {
fetchData.mockResolvedValue({ user: 'John Doe' });
const user = await getUserData(1);
expect(user).toBe('John Doe');
});