React Component testing implementation I use.

Zaharia Anton
2 min readJan 29, 2021

I know that ability to test your code is one of the skills needed in any web developer skillset.

While working with React I started to use Unit Testing to validate what my components are rendering.

To do so I needed a couple of other frameworks:

Mocha npm install mocha

Mocha-Jsdom npm install -D mocha-jsdom

Chai npm install -D Chai

Babel Register npm install -D babel-register babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0

I also added some files needed for this testing implementation.

In the root directory, I’ve created a .babelrc with the following content:

{
"presets": ["react", "es2015", "stage-0"]
}

Now I was ready to start building my test file. When I started the project using the npx create-react-app app-name , a file App.test.js was also created. Here I am going to implement the tests for the App component.

Firstly I need to import React and ReactDOM from react and respectively react-dom, and define a global variable to mock the DOM where the tests will run.

const jsdom = require("mocha-jsdom")
global.document = jsdom({ url: "http://localhost:3000/" });

Now I need to create and import the component that I am going to test.

Back to our App.test.js we import the component and define a root variable which we are going to use in the next step.

I am going to use two hooks that will run before and after every test case in my script.

Before each test, I am going to create a div element, assign it to the root element earlier created it and append those to the mock of the DOM from the previous step.

Now, for the actual test, I need to import two functions.

import { act } from "react-dom/test-tils;
import { expect } from "chai";

Writing the tests is the same syntax as any other JavaScript test.

Firstly rendering the App component to the mock DOM, finding first div element and then checking if there is the text that we expect.

To run the test in my terminal I write:

./node_modules/.bin/mocha --require babel-register ./src/App.test.js

And that is all. I try to implement this template to any component I create in React JS.

--

--