简体   繁体   English

ReactJS:如何测试状态更改

[英]ReactJS: How to test a state change

Quick question for this.setState(...) is obviously an asynchronous action and unit testing is synchronous, so how exactly are you ensuring that the result of a setsState in testing occurs successfully? 关于this.setState(...)快速问题显然是异步操作,并且单元测试是同步的,那么如何确保在测试中成功发生setsState的结果呢? IE the setState is setting the right values? IE浏览器的setState设置正确的值?

Are you doing it via a callback? 您是否通过回调来完成? Spy / Stub? 间谍/存根?

Just trying to figure out the best approach. 只是试图找出最佳方法。

Thank you 谢谢

setState receives an optional callback that is called once the setState method has finished. setState接收一个可选回调,一旦setState方法完成,该回调将被调用。 You can pass a handler for this event as a prop . 您可以将此事件的处理程序作为prop传递。

For example, let's say that, everytime you type something on an input , the state should change. 例如,假设您每次在inputinput ,状态都会改变。 You could pass an onInputChange handler as a prop that is executed every time the state finished changing due to an input change. 您可以将onInputChange处理程序作为prop传递,该状态每次由于输入更改而完成更改时都会执行。 This event I mentioned only makes sense for uncontrollable components. 我提到的该事件仅对于uncontrollable组件有意义。 If the component was controllable , the event would fire as I type, and it would be responsability of the controller-component to rerender the component as the result of an input change. 如果组件是可controllable ,则事件将在我键入时触发,并且由于输入更改的结果, controller-component有责任重新呈现controller-component

As for tests, unit tests are not necessarily synchronous.. Actually, in my case, I use the done callback a lot. 至于测试,单元测试不一定是同步的。实际上,就我而言,我done使用done回调。 Like this: 像这样:

it('test something', (done) => { myModule.doSomething((error, success) => done()); });

The above example would work on karma and mocha , for example. 例如,以上示例适用于karmamocha

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM