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
Loading Code Playground...
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?