Test with Jest

Monday, Aug 10, 2020
JavaScript

Jest can be used to test our code. Let's see how to set it up:

  1. Install Jest globally so we can run it directly from cli:
npm install jest --global
  1. Write our cool functions:
// funs.js

function joinWithHyphen(strOne, strTwo){
    return `${strOne}-${strTwo}`;
}

module.exports = joinWithHyphen;
  1. Create our test script:
// funs.test.js

const joinWithHyphen = require("./funs");

test('hello and js gives hello-js', () => {
    expect(joinWithHyphen("hello", "js")).toBe("hello-js");
});
  1. Create package.json for our project (if doesn't exist already) and add the following:
{
    "scripts": {
      "test": "jest"
    }
}
  1. Run all tests simply running jest from command line:
jest
 PASS  ./funs.test.js
   hello and js gives hello-js (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.783 s, estimated 1 s
Ran all test suites.

Some options

If you want to skip a test, use xtest instead of test:

...
xtest('skip for now', () => {...});
...

Use toEqual for objects and arrays:

const myObj = () => {
  return {x:1, y:2};
}

test('return the correct object', () => {
    expect(myObj()).toEqual({x:1, y:2});
});

For more options, see jest-cli page.