Using AirBnB's enzyme, we can setState of a ponent:
const loginComponent = shallow(<Login />);
loginComponent.setState({ error: true });
I want to do same thing using react-testing-library.
Thanks!
Using AirBnB's enzyme, we can setState of a ponent:
const loginComponent = shallow(<Login />);
loginComponent.setState({ error: true });
I want to do same thing using react-testing-library.
Thanks!
Share Improve this question asked Jan 9, 2019 at 6:46 RishabhRishabh 1011 silver badge4 bronze badges 1- react-testing-library is intended for blackbox testing, i.e. a test shouldn't be aware of ponent internals. If this doesn't suit your case, use Enzyme instead. – Estus Flask Commented Jan 9, 2019 at 7:08
1 Answer
Reset to default 21You can't do that with react-testing-library. This is because RTL wants you to test your ponent as a user would.
What does this mean? In real life, your ponent will change the state after something happens. Maybe the user entered wrong data or the API returned an error code.
Rather than changing the state directly, you should try to reproduce the set of actions that change the state.
This approach is a bit harder to implement than what Enzyme offers but your tests will be more robust. That's because you're going to test the whole flow instead of just focusing on what gets rendered when a particular state occurs.
On top of that say you refactor your code and change how the state works. RTL tests won't care as long as the way users interact with your application is the same. An Enzyme test would fail though because it doesn't know how to interact with the internals of your ponent anymore.