Unit Testing — Explained with Examples
Unit testing is a software testing method that verifies individual components or functions in isolation to ensure they work correctly.
Unit testing focuses on the smallest testable parts of an application — functions, methods, or classes — tested independently from the rest of the system. Each unit test should have no external dependencies (databases, networks, files).
Why Unit Tests Matter
Unit tests catch bugs early, document expected behavior, enable safe refactoring, and serve as executable specifications. When a unit test passes, you know that specific piece of logic works in isolation.
Example: Unit Testing in JavaScript (Jest)
// Function to test
function calculateTotal(items) {
return items
.filter(item => !item.taxExempt)
.reduce((total, item) => {
const tax = item.price * (item.taxRate || 0.1);
return total + item.price + tax;
}, 0);
}
// Unit tests
describe('calculateTotal', () => {
test('calculates total with default 10% tax', () => {
const items = [{ price: 100 }];
expect(calculateTotal(items)).toBe(110);
});
test('applies custom tax rates', () => {
const items = [{ price: 100, taxRate: 0.2 }];
expect(calculateTotal(items)).toBe(120);
});
test('excludes tax-exempt items from tax', () => {
const items = [
{ price: 100, taxExempt: true },
{ price: 50 }
];
expect(calculateTotal(items)).toBe(155); // 100 + 50 + 5
});
test('returns 0 for empty array', () => {
expect(calculateTotal([])).toBe(0);
});
});Expected output: All 4 tests pass.
The AAA Pattern
Every unit test follows the Arrange-Act-Assert pattern:
test('discount applies for orders over $100', () => {
// Arrange — set up the test data
const order = { total: 150, customer: 'vip' };
// Act — execute the function under test
const result = applyDiscount(order);
// Assert — verify the expected outcome
expect(result.discountedTotal).toBe(135); // 10% off
});Real-World Analogy
Unit testing is like testing each part of a car engine individually before assembling it. You test the pistons separately, the valves separately, the fuel injector separately. If a piston fails, you know exactly which part is broken and can fix it without disassembling the whole engine.
Related Terms
TDD, Mock vs Stub, Integration Testing, Code Coverage, BDD
Related Tutorial
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro