JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
Next
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 example
// 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');
  });
});

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?