Welcome to your final project! 🎉
In this capstone, you will apply everything you learned about unit testing in JavaScript using Jest.
The project contains several small but realistic modules — your job is to write comprehensive tests for them.
advanced-unit-testing/
│── package.json # Project setup with Jest
│── jest.config.js # Jest configuration
│── README.md # Instructions (this file)
│
├── src/utils # Source code (functions/classes to test)
│ ├── math.js
│ ├── stringUtils.js
│ ├── userService.js
│ ├── asyncService.js
│ └── eventEmitter.js
│
└── tests/ # Your test files (currently empty)
├── math.test.js
├── stringUtils.test.js
├── userService.test.js
├── asyncService.test.js
└── eventEmitter.test.js
Your goal is to write Jest tests inside the tests/ folder.
Each source file in src/ has a corresponding empty test file.
The challenge is to test:
- Pure functions (no dependencies, just logic).
- Async functions (Promises, async/await).
- Class methods with dependencies (mocking).
- Event-driven behavior (event emitters).
Functions: add, divide, factorial
👉 What to test:
- ✅ Normal cases (e.g.,
add(2, 3) → 5) - ✅ Edge cases (e.g.,
divide by zeroshould throw an error) - ✅ Recursion & boundaries (e.g.,
factorial(0) → 1, negative numbers should throw)
Functions: capitalize, sanitize, reverse
👉 What to test:
- ✅ Capitalization of lowercase & mixed case words
- ✅
sanitizeremoves HTML tags (but leaves plain text) - ✅
reverseworks with normal & special characters
Class: UserService (depends on a database object)
👉 What to test:
- ✅
createUsercreates a valid user object - ✅ Throws error if input is missing
- ✅
getUsercalls database and returns result - ✅ Use mocks (Jest
fn()orjest.mock) instead of a real database
Function: fetchData(url)
👉 What to test:
- ✅ Resolves with correct response for a valid URL
- ✅ Rejects with an error for invalid URL
- ✅ Works with
async/awaitand.then/.catch
Class: MyEmitter (extends EventEmitter)
👉 What to test:
- ✅ Event listeners (
messageevent should receive the message) - ✅ Error handling (
errorevent emits errors) - ✅ Multiple listeners get called correctly
Install dependencies:
npm installRun all tests:
npm run test Run only one file:
npm run test math.test.js