Code That Checks Code
Unit tests automatically verify that individual small functions (units) work correctly. They are your project's safety net.
Why Write Tests?
- Catch regressions: Change code in one place, tests instantly tell you if something broke elsewhere.
- Confidence to refactor: Restructure code fearlessly, knowing tests will catch any mistakes.
- Living documentation: Tests show exactly how a function is supposed to behave.
Popular Tools
- Jest: Industry standard from Meta. Widely used in React projects.
- Vitest: Modern, ultra-fast alternative (built for Vite projects).
// sum.js
export function sum(a, b) { return a + b; }
// sum.test.js (Vitest)
import { test, expect } from 'vitest';
import { sum } from './sum.js';
test('adds two positive numbers', () => {
expect(sum(2, 3)).toBe(5);
});
test('handles negative numbers', () => {
expect(sum(-1, 1)).toBe(0);
});
test('handles zero', () => {
expect(sum(0, 0)).toBe(0);
});
Note
Writing tests takes time upfront but saves weeks of debugging later. Professional development is impossible without a testing strategy.