StoryNovember 13, 20253 min read

🧩 Mocking Modules and Dependencies in Jest — Expense Tracker Edition

Our Expense Tracker is growing like a startup that just got funding.


🧩 Mocking Modules and Dependencies in Jestā€Šā€”ā€ŠExpense TrackerĀ Edition

Designed by Author usingĀ Figma

Our Expense Tracker is growing like a startup that just got funding.

It has logic, tests, even spies watching its every move.

But now, it is hiring new ā€œemployeesā€ helpers, modules, and third-party tools.

And like every team in the world, not all new hires behave. šŸ˜…

Some work perfectly on day one.

Some break things the moment you’re not watching.

And some refuse to come to work at all.

That’s why we need mocking for modulesā€Šā€”ā€Ša way to test your code without trusting your teammates too much.

šŸ’” The Problem with Dependencies

Image generated byĀ ChatGPT

Let’s be honest.

No developer ever said,

ā€œWow, I love debugging this third-party library I did not write!ā€

Your code might depend on something tinyā€Šā€”ā€Šlike a utility that converts currency,

but if that utility breaks, your tests explode like fireworks.

So instead of letting those modules run wild, we replace them with perfect clones that behave exactly how we want.

That’s Jest mockingā€Šā€”ā€Šor as I like to call it:

ā€œProfessional-level lying for good reasons.ā€ šŸ˜Ž

āš™ļø Step 1ā€Šā€”ā€ŠMeet the NewĀ Employee

šŸ“ currencyConverter.js

exports.convertToINR = (usd) => {
  // Imagine this calls an external API
  console.log('Converting USD to INR...');
  return usd * 83;
};

And here’s the main code that uses it:

šŸ“ expenseCurrency.js

const { convertToINR } = require('./currencyConverter');

exports.calculateExpenseInINR = (usdAmount) => {
  const inr = convertToINR(usdAmount);
  return { usd: usdAmount, inr };
};

This looks fine, until one day the API crashes or returns undefined.

Your tests fail. Your morning coffee tastes bitter. ā˜•

We can fix that.

🧪 Step 2ā€Šā€”ā€ŠFire the Real One, Hire a MockĀ šŸ˜

šŸ“ expenseCurrency.test.js

jest.mock('./currencyConverter', () => ({
  convertToINR: jest.fn(),
}));

const { calculateExpenseInINR } = require('./expenseCurrency');
const { convertToINR } = require('./currencyConverter');

test('should use mocked convertToINR', () => {
  convertToINR.mockReturnValue(8300);

  const result = calculateExpenseInINR(100);
  expect(convertToINR).toHaveBeenCalledWith(100);
  expect(result.inr).toBe(8300);
});

āœ… We just replaced the real convertToINR with a fake one that always behaves.

It never forgets, never breaks, never calls the internet.

It’s like the world’s best intern.

Imagine Explaining This to aĀ Non-Dev

Image generated byĀ ChatGPT
ā€œSo, you fired your real function and replaced it with a fake one that pretends to do the job?ā€
ā€œExactly!ā€
ā€œAnd this makes you trust your code more?ā€
ā€œYes.ā€
ā€œYou’re insane.ā€

Welcome to testing. šŸ˜Ž

🧠 Step 3ā€Šā€”ā€ŠMocking Third-Party Packages

Let’s take it up a notch.

Say your app uses axios for API calls.

You don’t want your test waiting for the internetā€Šā€”ā€Šso you replace it too.

šŸ“ expenseApi.test.js

jest.mock('axios');
const axios = require('axios');
const { fetchExpenses } = require('./expenseApi');

test('should mock axios get call', async () => {
  axios.get.mockResolvedValue({ data: [{ id: 1, amount: 500 }] });

  const result = await fetchExpenses();
  expect(result.length).toBe(1);
});

Boom šŸ’„

you just controlled axios itself.

You told it what to say, and it obeyed like a polite bot.

āš™ļø Step 4ā€Šā€”ā€ŠThe Jedi Trick: PartialĀ Mocking

Sometimes you don’t want to replace the whole module, just one noisy function inside it.

That’s where partial mocking comes in.

jest.mock('./currencyConverter', () => {
  const originalModule = jest.requireActual('./currencyConverter');
  return {
    ...originalModule,
    convertToINR: jest.fn().mockReturnValue(9000),
  };
});

Now, you keep everything else real, but replace one part.

It’s like hiring a clone who’s just a little smarter at one thing.

🧩 Step 5ā€Šā€”ā€ŠDon’t Forget to Clean theĀ Mess

After every test, always restore order:

afterEach(() => {
  jest.resetAllMocks();
});

It’s like telling your test suite,

ā€œAlright team, break’s overā€Šā€”ā€Šback to normal behavior!ā€

This keeps your next tests clean and drama-free.

āœ… Summary

Image generated byĀ ChatGPT

Today,

Our Expense Tracker learned how to manage its relationships like a pro.

It now knows which functions to trust, which to replace, and when to keep things real.

We mocked:

  • Our own modules
  • Third-party libraries like Axios
  • And even learned partial mocking for finer control

In short,

our code stopped chasing bad dependenciesā€Šā€”ā€Šit hired replacements that never fail. šŸ˜Ž

In the next Part we will see Mocking Configurations and Chained Dependencies in Jestā€Šā€”ā€Šwhere your app will start mocking its own brain.


šŸ’¬ Comment which part made you laugh (or cry) the mostā€Šā€”ā€ŠI read them all.

Thanks forĀ reading.

If this added value, follow me for more clear and practical posts.
— Alkesh Jethava