Skip to main content

Module 08: Unit Testing

Duration: 2-3 hours | Difficulty: Intermediate

Unit tests are the foundation of your testing pyramid. They're fast, focused, and provide immediate feedback on your code's correctness.


What You'll Learn

  • Setting up Jest/Vitest for unit testing
  • Writing effective unit tests
  • Mocking dependencies
  • Testing async code
  • Achieving meaningful coverage

Module Lessons

LessonTopicDuration
08.1 SetupInstalling and configuring Jest30 min
08.2 Writing TestsYour first unit tests45 min
08.3 MockingIsolating code with mocks45 min
08.4 Async TestingTesting promises and async/await30 min
08.5 CoverageMeasuring test coverage30 min

Unit Test Characteristics

Speed:        ⚡ Fast (milliseconds)
Count: 📊 Many (hundreds/thousands)
Scope: 🎯 Single function/class
Dependencies: 🔧 Mocked
Cost: 💰 Cheap to write/maintain

Example Unit Test

describe('calculateDiscount', () => {
it('should apply 10% discount for orders over $100', () => {
// Arrange
const orderTotal = 150;
const discountRate = 0.1;

// Act
const result = calculateDiscount(orderTotal, discountRate);

// Assert
expect(result).toBe(15);
});

it('should return 0 for orders at $100 or below', () => {
expect(calculateDiscount(100, 0.1)).toBe(0);
expect(calculateDiscount(50, 0.1)).toBe(0);
});
});

Prerequisites

Before starting:

  • ✅ Completed Module 07
  • ✅ Node.js project initialized
  • ✅ Comfortable with JavaScript functions

Let's Begin

Ready to write your first unit tests?

Start Lesson 08.1: Setup