Member-only story

Mastering Jest: Day 4 — Mocking Functions and Modules

Introduction

Skyz Walker
2 min readJul 22, 2024
Photo by Lavi Perchik on Unsplash

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');
});
Skyz Walker
Skyz Walker

Written by Skyz Walker

I am a passionate and dedicated Web & CloudEng with a strong focus on both frontend and backend technologies. I specialize in creating stylish, modern websites.

No responses yet

Write a response