Unit testing involves testing individual units of code (functions, methods, components) in isolation to verify they work correctly. It's important for catching bugs early, enabling safe refactoring, documenting behavior, and building confidence in code quality.
What Unit Tests Do:
Benefits:
Testing Pyramid:
// Function to test
function add(a, b) {
return a + b;
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// Unit tests using Jest
describe('add', () => {
test('adds two positive numbers', () => {
expect(add(2, 3)).toBe(5);
});
test('adds negative numbers', () => {
expect(add(-1, -2)).toBe(-3);
});
test('adds zero', () => {
expect(add(5, 0)).toBe(5);
});
});
describe('capitalize', () => {
test('capitalizes first letter', () => {
expect(capitalize('hello')).toBe('Hello');
});
test('handles already capitalized string', () => {
expect(capitalize('Hello')).toBe('Hello');
});
test('handles single character', () => {
expect(capitalize('a')).toBe('A');
});
});