JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
Next

Learn the concept

Unit Testing Fundamentals

testing
junior
basics

What is unit testing and why is it important?

unit-testing
basics
jest
testing-fundamentals
Quick Answer

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.

Detailed Explanation

What Unit Tests Do:

  • Test smallest pieces of code in isolation
  • Verify expected inputs produce expected outputs
  • Run automatically and repeatedly
  • Provide fast feedback on code changes

Benefits:

  1. Catch Bugs Early: Find issues before deployment
  2. Safe Refactoring: Change code confidently
  3. Documentation: Tests show how code should work
  4. Design Feedback: Hard-to-test code often needs redesign
  5. Regression Prevention: Ensure fixes don't break existing functionality

Testing Pyramid:

  • Many unit tests (fast, isolated)
  • Some integration tests (test components together)
  • Few E2E tests (slow, test full flow)

Code Examples

Simple unit test exampleJavaScript
// 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');
  });
});

Real-World Applications

Use Cases

Developing a complex utility function for data manipulation (e.g., date formatting, currency conversion)

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.

Building a reusable UI component (e.g., Button, Input field) in a component library

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.

Refactoring a critical piece of business logic without introducing new bugs

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.

Mini Projects

Unit Test a Simple Calculator

beginner

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.

Unit Test a Form Validator

beginner

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.

Industry Examples

Airbnb (Enzyme/Jest)

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 (Jest)

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.

Resources

Jest Getting Started

docs

JavaScript Testing Best Practices

article

Related Questions

How do you use beforeEach, afterEach, beforeAll, and afterAll in Jest?

junior
setup
Next
What are the most commonly used Jest matchers?
Next