Mocking External Dependencies Practice
What you'll build
A user service module that fetches user data from an API and saves to a database, with a full test suite that mocks both the API client and database to test the service logic in isolation.
Goals
- Create a user service that depends on an API and database
- Mock the API client using jest.mock()
- Mock the database module with custom implementations
- Verify that mocks are called with correct arguments
- Test both success and error scenarios
Prerequisites
- Completed Project 1 (Unit Test Suite) or equivalent Jest experience
- Understanding of modules and require/import
- Basic knowledge of async/await
Steps
- 1
Create the API and database modules
Create
api.jswith a fetchUser function anddb.jswith a saveUser function. These are the dependencies we will mock.Code// api.js async function fetchUser(id) { const res = await fetch(`/api/users/${id}`); return res.json(); } module.exports = { fetchUser }; // db.js async function saveUser(user) { // saves to database } module.exports = { saveUser };Expected result
Both modules are created and export their functions.
- 2
Create the user service
Create
userService.jsthat uses both dependencies to fetch a user and save it.Codeconst { fetchUser } = require('./api'); const { saveUser } = require('./db'); async function getUserAndSave(id) { const user = await fetchUser(id); await saveUser(user); return user; } module.exports = { getUserAndSave };Expected result
userService.js imports and uses both dependencies.
- 3
Mock the dependencies in tests
Create
userService.test.jsand use jest.mock() to replace both modules with mocks.Codejest.mock('./api'); jest.mock('./db'); const { fetchUser } = require('./api'); const { saveUser } = require('./db'); const { getUserAndSave } = require('./userService'); test('fetches and saves user', async () => { fetchUser.mockResolvedValue({ id: 1, name: 'Alice' }); const user = await getUserAndSave(1); expect(user).toEqual({ id: 1, name: 'Alice' }); expect(fetchUser).toHaveBeenCalledWith(1); expect(saveUser).toHaveBeenCalledWith({ id: 1, name: 'Alice' }); });Expected result
Test passes with mocked dependencies.
- 4
Test error scenarios
Add a test for when the API throws an error, verifying the service propagates it correctly.
Codetest('propagates API errors', async () => { fetchUser.mockRejectedValue(new Error('Network error')); await expect(getUserAndSave(1)).rejects.toThrow('Network error'); expect(saveUser).not.toHaveBeenCalled(); });Expected result
Error test passes — service correctly propagates API errors.
- 5
Add boundary test cases
Add boundary-value cases to the test suite: empty array, zero, maximum value, null/undefined. Boundaries are where bugs most often hide, so they must be explicitly covered.
Codedescribe("boundary cases", () => { it("handles empty array", () => { expect(func([])).toEqual([]); }); it("handles zero", () => { expect(func(0)).toBe(0); }); it("handles null", () => { expect(() => func(null)).toThrow(); }); it("handles max value", () => { expect(func(Number.MAX_SAFE_INTEGER)).toBeDefined(); }); });Expected result
All boundary cases pass with no uncaught exceptions.
Try it yourself
What you learned
You learned how to mock module dependencies with jest.mock(), configure mock return values with mockResolvedValue/mockRejectedValue, and verify mock calls with toHaveBeenCalledWith. Mocking is essential for testing code with external dependencies in isolation.
Related Resources
Related Lessons
- Mocking
Using mocks to isolate code.
- Stubs and Spies
Understanding test doubles.
Related Practice
- Mocking Exercises
Practice mocking concepts.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.