Test Levels
Unit Testing
Testing isolation, Mocking, and Assertions.
Unit Testing
The foundation. A unit test checks the smallest testable part of an application (a function, a class).
The 3 Laws (FIRST)
- Fast: Should run in milliseconds.
- Isolated: Should not touch the DB, Network, or File System.
- Repeatable: Always produces the same result.
- Self-Validating: Pass/Fail. No manual check.
- Timely: Written with or before the code.
Mocking vs. Stubbing
To keep tests isolated, we fake dependencies.
- Stub: Returns hardcoded data. ("When
getUser()is called, return{'name': 'Bob'}"). Used for state verification. - Mock: Verifies behavior. ("Expect
sendEmail()to be called exactly once").
Don't Mock Types
In TypeScript, don't just cast objects as User to silence the compiler.
Use libraries like deep-mock or build proper test factories to ensure your mocks align with reality.