lets you render a component "one level deep" and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.

As you can see in the post mentioned at the end of this one, the actual code to test some components might seem a bit longer that what you might expect.

Thankfully, someone created something pretty cool: react-element-to-jsx-string. As the name of the package says, this library helps to render a react component into a JSX string.

Now things start to become interesting: with those two things in mind (shallow render and react components as JSX strings), we can easily add some basic unit tests for some components.

There are others techniques to test React components, and most of those involve the DOM. This means you will need to run your tests in the browser (or using jsdom): your tests will be slower than the following method (which is more real unit testing since you execute less code and do not require a huge environment).

Easy unit testing React components (without a DOM)

Let's do this with the following (dumb) component:

// web_modules/Picture/index.js

importReactfrom"react";

import{PropTypes}from"react";

constComponent=({ img, title, Loader, Title })=>(

<div>

{(!img ||!img.src)&& Loader &&<Loader />}

{img &&img.src&&<img src={img.src} alt={img.alt}/>}

{title && Title &&<Title text={title}/>}

</div>

);

Component.propTypes={

img:PropTypes.object,

title:PropTypes.string,

Loader:PropTypes.func.isRequired,

Title:PropTypes.func.isRequired

};

Component.displayName="Picture";

exportdefaultComponent;

This component displays an image with a title component. If the image data is not ready yet, it can display a loader component.

This example contains all the commands and dependencies (defined in the package.json) that you might need.

What about testing events like onClick?

You don't need to reproduce the entire click.

Your tests don't need to check that your onClick prop will be executed when you click on a DOM element.React probably have tests to cover this.

You only need to test that the onClick prop value will do what you want. So if you have something like onClick={ yourCallback }, just call directly yourCallback() in your test just before your comparison. That's enough!