最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set component's local state while testing using jest and react-testing-library? - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 21

You 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论