简体   繁体   中英

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? IE the setState is setting the right values?

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. You can pass a handler for this event as a prop .

For example, let's say that, everytime you type something on an input , the state should change. You could pass an onInputChange handler as a prop that is executed every time the state finished changing due to an input change. This event I mentioned only makes sense for uncontrollable components. 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.

As for tests, unit tests are not necessarily synchronous.. Actually, in my case, I use the done callback a lot. Like this:

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

The above example would work on karma and mocha , for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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