Last Updated on
Jest is from Facebook, it comes pre-installed in Create React App.
It’s a good idea to install Jest globally since I will be using it from now on.
npm i jest -g
Or install as a dev dependency:
Looking for a Node.JS course recommendation? Check out The complete Node Developer course by Rob Percival - see others
npm i jest -D
Run it with npm test by adding jest --watchAll
in the package.json file.
3 ways to add test files:
- Put all the test files in __tests__ directory within the project folder
- Add files with .test.js
- Add files with .spec.js
I like to add .spec.js inside each of my React component files. Each test per component stays on their component folder.
For tesing general JavaScript, I will put them in __tests__ folder.
With jest –watchAll we can type p to select the specific file to run the tests.
Testing:
Import the function or component to be tested:
import Component from './component';
or common JS:
const sort = require('./sort');
Then use the function:
describe('insertionSort', () => { test('should sort a small array', () => { expect(insertionSort([4, 2, 1, 3])).toEqual([1, 2, 3, 4]); });
That’s the basic usage and so far I am getting used to it.
I am yet to learn how to test React components, DOM elements and Node/Express APIs.
So far, testing makes life a lot more easier. I can just return the result from a function and leave the module as is. Then use Jest to test all the cases. No more messing with console.log();