0

I have a Create React App project that uses React Testing Library for testing, and has some fairly large legacy class components. These components have methods on them to accomplish various tasks (sometimes not directly related to rendering); they need to compute various functions of moderate complexity based on data structures in the component's React state.

I see these different component class methods as "units" that are worth having tests for in their own right. But React Testing Library's developers seem to want to stop me from testing these component class methods. Based on this question, the Testing Library Guiding Principles, and what they say about not providing a migration path for Enzyme tests for component class methods, I'm not supposed to be able to use Testing Library to unit test a method on a React class component because the Testing Library developers say that is not part of the component's contract and should not be part of a test for that component.

If I am a component author and I am writing a component, and I want to organize the work of my component beyond a single monolithic JavaScript function, how am I meant to test those individual pieces or sub-units under React Testing Library?

The migration guide seems to boil down to "test the component as a whole". But if I test the component as a whole and it doesn't work, how do I eliminate possibilities and say, for example, "I know the binary search logic works, but there is a bug in the logic that translates between the data structures used in the props and those used in the state"?

2
  • Refactoring, basically. If they're "not directly related to rendering", just dealing with vanilla JS data, you don't need RTL for that part at all. If you find the component's too unwieldy to test in one go and get decent triangulation of errors, decompose it into smaller pieces. Commented Jan 22, 2024 at 18:08
  • So if my component takes data in a particular format in props but needs it represented differently in state, I should create a new piece of my application not logically part of that component that does that translation, and I should write tests for that piece. So a component with a lot of machinery to let it do what it does it might have several auxiliary code files next to it for widgets that it needs, each with their own tests? And then the "component" is just view and glue code. Commented Jan 22, 2024 at 19:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.