mercredi 4 mars 2015

How can I unit test public methods of a React component

All the information I've seen about how to test React components is based on rendering the component with certain props to the DOM (renderIntoDocument) then making assertions about the resulting elements.


What I want to do is write unit tests for public methods on the component instance. The type that you can access from a parent component like so:



this.refs.childComponent.somePublicMethod()


This is an approach recommended by Facebook: http://ift.tt/1jo7pPy


The problem is that, when you instantiate a React component directly you get a ReactElement instance which doesn't provide access to those public methods. The only way they seem to be available is via refs.


Is it possible to instantiate a React component in such a way that I can invoke its public methods and make test assertions about the result?


I realise some of this can be achieved indirectly by triggering fake events on the component, effectively an integration test at the component level. However if you have a public method on some class it seems natural to me to want to write a unit test for it. I'm thinking of Reusable components that have fairly complex internal state management and a number of public methods with non-trivial implementation.


Aucun commentaire:

Enregistrer un commentaire