Reputation: 101
Using AirBnB's enzyme, we can setState of a component:
const loginComponent = shallow(<Login />);
loginComponent.setState({ error: true });
I want to do same thing using react-testing-library.
Thanks!
Upvotes: 10
Views: 9241
Reputation: 27098
You can't do that with react-testing-library. This is because RTL wants you to test your component as a user would.
What does this mean? In real life, your component 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 component anymore.
Upvotes: 21