Skip to content

Testing & QA

Unit Tests (One Piece in Isolation)

O(number of cases) to run — each case is one quick function call, so hundreds of unit tests still finish in a blink.

The idea, in plain English

A unit test checks one small piece of code — usually a single function — all by itself, with nothing else attached. Think of testing one light bulb by screwing it into a lamp you know works, rather than flipping the whole house's breaker and guessing. Because a unit test touches only one function, when it fails you know precisely where the problem is. Unit tests are tiny, fast, and you write lots of them.

How it works

  1. 1Pick one function that takes inputs and returns a result, with no hidden dependencies.
  2. 2Write several cases: normal inputs, edge cases, and the boundaries where behavior changes.
  3. 3For each case, call the function and compare its output to the expected value.
  4. 4Count passes. A green run means that one unit behaves correctly across every case you thought of.

When you'd use it

Use unit tests for pure logic: calculations, formatting, validation, parsing — anything that takes inputs and returns outputs without reaching out to a database or network. They're the broad base of most test suites because they're cheap and fast.

Common beginner mistakes

  • Testing only one 'happy' input. The bugs hide at the edges — zero percent, one hundred percent, empty, negative — so cover those explicitly.
  • Letting the unit secretly depend on the outside world (a clock, a database). If it does, it isn't really a unit test anymore, and it'll fail for reasons unrelated to your logic.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
10% off 100 = 90 -> PASS
50% off 50 = 25 -> PASS
0% off 80 = 80 -> PASS
3/3 unit tests passed

Not sure this is the right topic? See the learning paths → or where this leads →