Perryn Fowler
Perryn Fowler

Reputation: 2232

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?

Upvotes: 7

Views: 868

Answers (1)

Jared Dykstra
Jared Dykstra

Reputation: 3626

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

Upvotes: 1

Related Questions