What is unit testing?
Unit testing is a testing method in which the smallest parts of a program (units) are checked: individual functions, methods or modules. The goal is to make sure that each part works correctly and predictably in isolation from the rest of the code.
Why it is needed
Unit tests help with:
- Early bug detection - a bug is caught right away in a small fragment, not in a huge system.
- Confidence in changes - you can safely refactor code knowing that the tests will catch a mistake.
- Reliability and stability of the project - fewer unexpected breakages.
- Documentation of behavior - the tests show how a function is supposed to work.
What it looks like in a simple example
There is a function:
js
function sum(a, b) {
return a + b;
}Unit test:
js
test("sum adds 2 + 3 to equal 5", () => {
expect(sum(2, 3)).toBe(5);
});If the function breaks, the test shows it right away.
What exactly gets tested in unit tests
- the correct result
- behavior with invalid data
- behavior at boundaries (0, empty strings, large numbers, etc.)
- absence of side effects
How unit tests differ from other tests
| Test type | Scope of the check |
|---|---|
| Unit | a small function → does it work correctly? |
| Integration | several modules → do they work correctly together? |
| E2E (end-to-end) | the whole product → does it pass a real user scenario? |
Summary
Unit testing is an automated check of individual functions and modules to make sure that every small piece of a program works the way it should.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.