Lets Add a Test File with Jest in 30 Seconds to Your Create-React-App Project

Mohammed Chisti
2 min readMay 15, 2017

--

If you’re like me, you dread TDD because you it kind of feels like more work then it needs to be, but we all know that TDD can make sure you don’t forget what your project guidelines are if their put in place. If I wanted my project to have a single button on the screen and then ended up 3 buttons instead, test code I’ve written will remind me that I’ve got 2 more buttons then I had originally hoped for. Aside from when you’re solo, this is extremely beneficial to your team who will also be working on the project with you. If you’ve been working on a React project then I’ll show you how you can make it a TDD ready project.

Step 1

If you’ve been using npm’s create-react-app then you’ve already got Jest installed on your project, Step 1' s already finished!

Step 2

Go to your scripts on your package.js file and type/edit the following :

"scripts": {
...
"test": "jest" ...
}

Step 3

Create a folder in your src folder called __test__. It’s usually convention to have your test folder named test followed after double underscore dashes and then also followed after with double underscore dashes. With in the __test__ folder add a file named test.js in it.

Step 4

Copy and paste the following code to your test.js file. Replace Foo with any component you have in your folder:

import React from 'react';

import Foo from '../components/Foo';

describe('<Foo />', () => {
it('Some possible tests', () => {});
});

Step 5

Run the following line in your terminal :

$ npm run test

Finished!

You should see a test that was complete in your terminal. If want to see some better examples of TDD, they checkout Airbnb’s examples here. Be sure to npm i any libraries like enzyme to your project.

--

--