[英]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. 例如,假设您每次在input
上input
,状态都会改变。 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. 例如,以上示例适用于karma
和mocha
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.