Skip to content

Instantly share code, notes, and snippets.

@giopunt
Last active September 6, 2018 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giopunt/bfca696bf60837439e6a3b49fe4fcaa2 to your computer and use it in GitHub Desktop.
Save giopunt/bfca696bf60837439e6a3b49fe4fcaa2 to your computer and use it in GitHub Desktop.
JS Unit Tests 101

JS UNIT TESTS 101 ๐Ÿ‘

Create a basic project

Let's start by opening a new console/terminal window from a convenient working directory and type:

$ mkdir js-unit-test-101
$ cd js-unit-test-101

From inside the folder we can initialise a new project by typing:

$ npm init -y

This will create a package.json file and fill in some default values (-y).

Install jest

Before we start juggling letโ€™s see why Jest is good for the task:

  • It works out of the box
  • Automatically finds tests
  • Automatically mocks function dependencies
  • Itโ€™s blazing fast ๐Ÿ”ฅ

To get started we need to install Jest as one of our dev dependencies using npm:

$ npm install jest --save-dev

Jest works out of the box so place the tests in a folder named tests, or name the test files with the .spec.js or .test.js extension.

Letโ€™s add the test command in our package.json

๐Ÿ“ package.json

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

Let's write some tests

In the same folder let's add a test file called sum.spec.js

๐Ÿ“ sum.spec.js

const sum = require('./sum');

test("it sums 1 to 2", () => {
  const result = sum(1, 2);
  expect(result).toBe(3);
});

Now we can use npm test from the terminal to run our unit tests.

IT FAILED!

Let's write some code

Let's create a simple function called sum, go on and create a new file sum.js

๐Ÿ“ sum.js

function sum(a, b) {
  return a + b;
}

module.exports = sum;

run the tests and... SUCCESS! ๐Ÿฅ‡! The test should be passing.

Let's add a new test and make sure that even if we pass two number as a string it still making the sum:

๐Ÿ“ sum.spec.js

const sum = require('./sum');

test("it sums 1 to 2", () => {
  const result = sum(1, 2);
  expect(result).toBe(3);
});

// new test
test("it sums `1` to `2`", () => {
  const result = sum("1", "2");
  expect(result).toBe(3);
});

If we run npm test again it should be failing, this is because a + b in our code will simply concatenate the two arguments if they are strings, let's fix it:

Go back to sum.js and use Number to parse the inputs into numbers (if possible)

๐Ÿ“ sum.js

function sum(a, b) {
  return Number(a) + Number(b);
}

module.exports = sum;

Then run the tests again and voilร !

BONUS CONTENT 1: How to watch the unit tests

When in development mode, we are likely to watch the tests running. This means we donโ€™t need to rerun the process every time we make changes and our test command will restart automatically.

We easily do that by executing Jest with the --watch flag, our package.json should look like this now:

๐Ÿ“ package.json

{
  ...
  "scripts": {
    "test": "jest test",
    "test:watch": "jest test --watch"
  }
  ...
}

BONUS CONTENT 2: Produce a coverage report

Producing a converage report can help you identify uncovered scenarios. Automating this task can help us achieve safer code and avoid human errors.

Simply add a new command to the scripts section of package.json

๐Ÿ“ package.json

{
  ...
  "scripts": {
    "test": "jest test",
    "test:watch": "jest test --watch",
    "test:report": "jest test --coverage"
  },
  "jest": {
    "collectCoverageFrom": [
      "*.js"
    ],
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ]
  }
  ...
}

Now my favourite part, if you run npm run test:report and then open this file:

$ open coverage/lcov-report/index.html

You can interactively navigate through your repository and clearly see in your code any uncovered area.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment