UI (React) Unit Testing
What should we test in our React components
A proposal by Mihail Gaberov
Tests should test only the render logic, i.e. test what the user will be seeing and interacting with, without caring about the internal implementation.
No lifecycle methods - dīvide et imperā
Tests should not test lifecycle methods, they are supposed to be covered by React itself. If we have some logic that needs to be tested in such methods, we should try to extract it in another testable place and only use it in there.
Tests should not test interaction with outside world - API, DB, etc.
Small, smaller, easier
Tests should be small and easy to read - if we need to test big component with a lot of dependencies we need to consider splitting it to smaller testable pieces.
If we need to use big mocks, we need to extract them out of the test and only use them by importing, in order to avoid polluting the test file.
But we don't care about the internal implementation of the click handler!
- Given a simple component containing a button and a text field
- We should test what the user sees - rendering, and what the user can do - user interaction
- If there is visual change after clicking - test for it
- If there is a value returned after clicking - test for it