Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setState in react-testing-library

Overview:

  • I refactoring script tests before I was used Enzyme to test, but now, I want to use @testing-library/react

Problem:

  • I can't find a solution for setState in @testing-library/react
like image 908
Huy Ho Avatar asked Jul 06 '19 11:07

Huy Ho


People also ask

How do you set setState in react?

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.

Which is better enzyme or react testing library?

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.

How do you do testing on react?

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


1 Answers

Using setState is dangerous approach regardless testing library used.

  1. It depends on implementation details(say, property names inside the state) so it becomes much harder to maintain tests - more tests to change, easy to get test broken when app is fine etc.
  2. You cannot call that once you convert class component to functional one with hooks. So you depends on implementation details even more.
  3. And finally direct state manipulation may end with state you would never get in real world. This means your component will be broken because it's impossible to reach some state but your tests with direct initialization will be fine.

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.

like image 75
skyboyer Avatar answered Oct 06 '22 04:10

skyboyer