Recently I have been learning Facebook’s React library for a four week thesis project that I am doing at Hack Reactor Remote. One of the takeaways of this project is TDD, test driven development, which provides a way to document expected behavior of the software, provides a safety net for performing refactoring and catches errors early before the code is deployed. With that in mind I embarked upon learning a new testing framework created by Facebook for React called Jest.

Jest was originally created by Facebook to write fast reliable tests for their web chat application. Jest sits on top of the well-known testing suite called Jasmine. What’s unique about Jest is that it allows for automatic mocking using JSDom for running tests in the terminal instead of in the browser. Automatic mocking is useful because it allows you to test your components in in isolation to other components and dependencies and all your dependencies can be mocked.

With all that said I want to walk through a very basic setup and example. To get started, you will first need to create a new directory in you terminal.

mkdir jestExample && cd jestExample

We then need to create a package.json file inside of jestExample, so in the terminal type in:

npm init

Press enter at all the prompts. Next you will need to install the jest command line tool.

npm install --save-dev jest-cli

Now you want to create a simple javascript file to test later. In the terminal type:

touch product.js

Now open up jestExample in your code editor and type the following code in.

function product(x,y) {

return x * y;

};

module.exports = product;

Back in your terminal make a new directory called __tests__ and create a new file called product-test.js

mkdir __tests__ && cd __tests__

touch product-test.js

We create the __tests__ directory so that when you run your tests, Jest knows where to look for them.

Now inside of your product-test.js file write the following code.

jest.dontmock('../product); describe('product', function() {

it('multiplies 5 * 6 to be equal to 30' function(){

var product = require('../product);

expect(product(5,6)).toBe(30);

});

});

To run this test, the first thing we need to do is open our package.json file and change

“test”: “echo \”Error: no test specified\” && exit 1"

to the following:

“test”: “jest”

Now back in your terminal type in the following:

npm test

The result should look like this:

And that is it you have created your very first Jest test for React.