React Course
React
/
Intermediate

Unit Testing

Definition

Unit testing isolates a single piece of code (like a utility function or a pure React component) and tests its behavior independently from the rest of the application.

Explain Like I'm New

Imagine testing a car. Unit testing is taking the engine out, putting it on a workbench, and making sure the pistons fire correctly. You aren't testing the steering wheel or the brakes; you are only testing the engine.

Real World Example

Testing a `formatCurrency(amount)` function to ensure `formatCurrency(1000)` returns `'$1,000.00'`.

Common Use Cases

  • Testing pure utility functions
  • Testing custom hooks using `@testing-library/react-hooks`
  • Testing Presentational/Dumb components that just accept props and render UI

Interactive Example

// math.js
export const multiply = (a, b) => a * b;

// math.test.js
import { multiply } from './math';

test('multiplies positive numbers', () => {
  // Arrange
  const num1 = 5;
  const num2 = 10;
  
  // Act
  const result = multiply(num1, num2);
  
  // Assert
  expect(result).toBe(50);
});

Interview Questions

basic

  • What is a Unit Test?
  • Why are pure functions easier to unit test?

intermediate

  • How do you unit test a Custom Hook?
  • What is Code Coverage?

advanced

  • Why is it discouraged to unit test every single internal React component?
  • What is the AAA pattern?

Flash Cards

Question

Why are pure functions easier to test?

Click to reveal answer
Answer

Because they have no side effects (like database calls or random numbers) and their output is completely determined by their input. You don't need to set up complicated mocks.

Question

What is the AAA pattern?

Click to reveal answer
Answer

Arrange, Act, Assert. Arrange: Set up the data and render the component. Act: Click the button or call the function. Assert: Check if the result matches your expectations.