

Unit testing React components without a DOM - backoneagain
http://simonsmith.io/unit-testing-react-components-without-a-dom/

======
drcode
Though OP's approach has definite use cases, I'd recommend another approach in
most instances: Break down your React rendering into two steps: "state->JSON",
then "JSON->DOM".

So basically, try to come up with a JSON description for your UI that answers
the question "If I created a UI that only consisted of JSON, but had the same
information as my DOM UI, what would it look like?"

Chances are, 80% of your rendering code will be in the "state->JSON" part, and
that part of the code is SUPER easy to unit test.

Plus, when the day comes you want to adopt ReactNative, you already have the
perfect in-between data structures to add this, you simply need to write some
extra JSON->Native code.

~~~
masklinn
> Break down your React rendering into two steps: "state->JSON", then
> "JSON->DOM".

Er… that's exactly how React works in the first place, your "JSON" is react's
"VDOM". The point of the shallow renderer is to perform a single level of
rendering rather than recursively rendering all components to the final VDOM
(so sub-components will appear as sub-components, not as their rendered vdom)

~~~
zenojevski
He means to preprocess your props+state into a simple dictionary, so that you
have moved 90% of logic from `render()` to a different, more testable
function.

------
mkohlmyr
As an old interlopers.net member it's been really fun to keep happening upon
these little gem articles by Simon recently. This looks very interesting!

Simon, if you read this I regularly have the lyrics to one of your ancient
tunes pop into my head to this day. Stephen Hawking Need Not Apply.

------
GordyMD
Thanks for this. Noticed whilst testing that renderIntoDocument in
ReactTestUtils doesn't even render the ReactComponent into the DOM either and
is due to be renamed. [1] Shallow rendering looks like the correctly renamed
approach... I'll be updating my tests accordingly.

[1]
[https://github.com/facebook/react/blob/master/src/test/React...](https://github.com/facebook/react/blob/master/src/test/ReactTestUtils.js?source=c#L48)

------
benhue
How would you handle dom events with this method (such as click, hover etc.)?

~~~
dugmartin
There is a simulate event method in React TestUtils:
[https://facebook.github.io/react/docs/test-
utils.html](https://facebook.github.io/react/docs/test-utils.html)

