Notes on Jest, JavaScript Testing

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:

npm i jest -D

Run it with npm test by adding jest --watchAll in the package.json file.

3 ways to add test files:

  1. Put all the test files in __tests__ directory within the project folder
  2. Add files with .test.js
  3. 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();

Leave a Reply

Your email address will not be published. Required fields are marked *