DEV Community

Discussion on: Testing React Hook State Changes

Collapse
 
igokul777 profile image
Igor Ku • Edited

IMHO your approach is legit but describes a creation of brittle tests - you are trying to test implementation and not the behaviour: if you decide to eventually change implementation (use class component and the real setState method on it), your test will fail and you will have to adjust it accordingly, which should be avoided. On the other hand, I do not propose a solution, because Enzyme does not propose it - they still have to catch up with hooks. One may consider switching to React Testing Library if the hooks in the app are used extensively (I recently realised that there is no need for class components any longer given the hooks have been introduced a year ago) - it has much better support for hooks and is a React-recommended testing library. If, on the other hand, it is an application that extensively uses class components, then, I guess, one should not switch to hooks for the sake of having Enzyme continue a good job of testing the state values and not their implementation.
P.S. Actually testing a state in general is a bad idea - it is better to test what is being rendered, thereby completely focusing on the result and not implementation details, as well as making my above comments valid but obsolete and the problem non-existent :-)