Learn the concept
Unit Testing Fundamentals
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');
});
});Writing unit tests to verify that the function handles all expected inputs, edge cases (e.g., null, empty strings, invalid formats), and produces the correct output, ensuring its reliability across the application.
Creating unit tests for the component to check its rendering with different props, state changes, and event emissions, ensuring it behaves consistently and correctly in various parts of the application.
Having a comprehensive suite of unit tests allows developers to make changes to the internal implementation with confidence, knowing that if any existing behavior is accidentally altered, the tests will catch it immediately.
Write a JavaScript function for a basic calculator (add, subtract, multiply, divide) and create unit tests for each operation using a testing framework like Jest.
Develop a set of validation functions for a web form (e.g., email format, password strength, required fields) and write unit tests to ensure each validator works as expected.
Airbnb uses unit testing extensively for its React components and utility functions to ensure UI and business logic correctness across its large codebase, facilitating safe updates and feature development.
Stripe, known for its robust APIs, relies heavily on unit tests for its backend and frontend code to maintain high reliability and prevent regressions in critical financial transaction logic.