📎 Webclip
How I Write Testable Code | Khalil's Simple Methodology | Khalil Stemmler
The article says testability starts with how a class depends on other code. If a dependency makes tests slow or hard, the code becomes harder to test, especially when it brings heavy collaborators like a database connection or network calls.
It presents a simple rule for deciding whether to import a dependency when testability matters, and shows how interfaces, abstract classes, dependency inversion, and HOCs can keep front-end and back-end code testable.
Reading notes#
- A source class becomes dependent on another class, function, or variable as soon as it imports or even names it.
- Directly creating a
UserRepoinsideUserControllercreates a hard source-code dependency. - That direct dependency makes unit tests harder because
UserRepoalso brings the database connection. - Dependency inversion inserts an abstraction between the source class and the dependency.
- Interfaces or abstract classes can serve as the abstraction.
- With an
IUserRepointerface,UserControllercan accept any implementation that follows the contract, including a mock object. - The methodology starts by asking whether future tests against the source class matter.
- If testability does matter, a dependency is acceptable only if it is an abstraction, comes from the same layer or an inner layer, or is a stable dependency.
- If a dependency breaks those rules, dependency inversion can fix the situation.
- The same idea applies on the front end.
- A
ProfileContainerthat depends directly on aProfileServicecannot be tested without making real API calls. - The fix is to define an
IProfileServiceinterface and haveProfileServiceimplement it. - The container should receive
IProfileServiceas a prop rather than createProfileServiceitself. - A HOC can supply either the real profile service or a mock profile service.
- The article ends by showing
ProfileContainercomposed with the real service or the mock service.
