Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test parent react components that call methods on children

Under 'Tips' in the react documentation they describe a pattern for communicating between components where a parent component calls a method on the child (via a ref).

See https://facebook.github.io/react/tips/expose-component-functions.html

I am using a third party react component that requires me to use this approach.

I would like to unit test my component and check that it calls the child's method (with the right parameters) under the right circumstances, but I'm having trouble figuring out how...

For the example in the Facebook documentation, how would I write a test that checks Todos calls animate on the last Todo when it should?

like image 476
Perryn Fowler Avatar asked Nov 04 '15 01:11

Perryn Fowler


People also ask

How do you communicate between parent and child components in React?

In the parent component, create a callback function. This callback function will retrieve the data from the child component. Pass the callback function to the child as a props from the parent component. The child component calls the parent callback function using props and passes the data to the parent component.


1 Answers

Consider using Facebook's Flux pattern. By using this pattern, you'll have separated UI components from state management; state management is facilitated with "stores". The stores end up coordinating state between components. Now your views don't communicate directly. In addition, data only flows one way.

Flux Pattern

Note that there are many Flux implementations you can use, such as reFlux. You can find many of these by searching available NPM packages

...So, how to test this?

Once you've settled on a pattern, you can google a lot of resources, blogs, and examples for testing. Currently, there are two main approaches for unit testing: Jest and Jasmine. Facebook recommends using Jest:

For a unit test to operate on a truly isolated unit of the application, we need to mock every module except the one we are testing. Jest makes the mocking of other parts of a Flux application trivial.

...

Flux stores often receive a great deal of formal unit test coverage, as this is where the application state and logic lives. Stores are arguably the most important place in a Flux application to provide coverage

like image 150
Jared Dykstra Avatar answered Oct 02 '22 01:10

Jared Dykstra