Overview:
Problem:
The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
However, there are limitations to react-testing-library, such as not being able to access component state (which might be intentional because you shouldn't be doing that in theory). However, if you feel like you really need that, then Enzyme may be a better option.
There are a few ways to test React components. Broadly, they divide into two categories: Rendering component trees in a simplified test environment and asserting on their output. Running a complete app in a realistic browser environment (also known as “end-to-end” tests).
Using setState
is dangerous approach regardless testing library used.
So what you better do? Provide props, change props, call props(wrapper.find('button').filter(button => button.text() === 'Cancel').props().onClick()
for enzyme, fireEvent.click(getByText(/Cancel/i))
for RTL) and verify against what's rendered.
This way your tests will be shorter, most actual and need less changes after you update component under test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With