dev-tools
Glossary ↗Unit Test
A unit test is an automated test that verifies a single, small unit of code — typically one function or method — behaves correctly in isolation, independent of the rest of the system (external dependencies like a database or network call are usually replaced with a "mock" or "stub" so the test is fast and deterministic). Unit tests sit at the base of the "testing pyramid": lots of fast, cheap unit tests catching most bugs, fewer integration tests verifying components work together, and even fewer slow end-to-end tests verifying the whole system works from a user's perspective. Frameworks include Jest and Vitest (JavaScript), pytest (Python), JUnit (Java), and Go's built-in `testing` package. Why it matters for AI/SaaS builders: unit tests are what makes fast, confident iteration possible — a well-tested codebase lets a developer (or an AI coding agent) make a change and know within seconds whether it broke something, rather than manually clicking through the application to check. They're also the single biggest practical safety net for AI-generated code: an agent can generate a plausible-looking implementation, but a test suite objectively verifies it against the actual expected behavior, catching hallucinated edge-case handling or subtly wrong logic that a human skimming the diff might miss. How it works: a unit test sets up a known input, calls the function under test, and asserts the output matches an expected value — following an "Arrange, Act, Assert" structure. A test suite runs automatically via `npm test`, `pytest`, etc., locally in seconds and again in CI on every push, reporting a clear pass/fail per test with a stack trace on failure. Worked example: a developer writes a `calculateShippingCost(weightKg, destination)` function. The corresponding unit test file includes several cases: `expect(calculateShippingCost(2, "domestic")).toBe(5.99)`, `expect(calculateShippingCost(2, "international")).toBe(24.99)`, and an edge case `expect(() => calculateShippingCost(-1, "domestic")).toThrow("Weight must be positive")`. Running the test suite executes all three in milliseconds; if a later refactor accidentally breaks the international pricing logic, the second assertion fails immediately with a clear message ("expected 24.99, received 19.99"), pinpointing exactly what broke before the change is ever merged or deployed. Because the whole suite runs in well under a second, the developer gets this feedback almost instantly after saving the file, rather than discovering the regression hours or days later through a bug report from a confused customer. This tight loop — write code, get near-instant pass/fail feedback — is also what makes unit tests so valuable for AI coding agents specifically: an agent can run the same test suite after generating a change and self-correct within its own tool-use loop the moment a test fails, without needing a human to notice and report the regression first.
Related terms