Jest Driven Development

Test driven development with Facebook's Javascript testing framework

2014-09-11 — Rylan Santinon

Jest

Jest is a testing framework for Javascript web applications. It is built on top of Jasmine so it should be easy to use for anyone already familiar with that and Jest automatically mocks some JS modules.

Since Jest automatically mocks depedencies, it is simple to use for existing code.

Test Driven Development

Kent Beck, the man credited with popularizing TDD, claims that TDD makes for simplified code. It seems like everyone has their own reason for doing TDD including code qualtity and code correctness.

The basic workflow of test driven development is:

  • Write a failing test
  • Write enough code to make that test pass
  • Repeat

Installation

In order to install, you can use the npm command:
$ npm install jest-cli --save-dev

The --save-dev is to make Jest appear in your devDependencies.

And then add this to package.json:

  "scripts": {
    "tests": "jest"
  }

Write The Test

The example code that I'm going to be presenting is basically a small statistics library for doing calculations on lists of data.

Write a test for the avg function in __tests__/avg-test.js:

jest.dontMock('../statistics');

describe('Average', function() {
 it('four numbers to equal 2.0', function() {
   var avg = require('../statistics');
   var list = [1.2, 4.4, 1.1, 1.3];
  
   expect(avg(list)).toBeCloseTo(2.0, 12);
 });
});

Since Jest is configured to automatically mock objects, I need the jest.dontMock call in order to prevent my code from getting mocked out. This code is mostly self-explanatory but I'll point out that since I'm testing floating point numbers, I need to specify the precision which in this case is 10-12.

Write The Code

In the parent directory of __tests__, I'll make a file called statistics.js and write the following:

function avg(list){
  if(list.length === 0) throw new Error("List length is zero");
  var avg = 0.0;
  for(var i = 0; i < list.length; i++){
    avg = avg + list[i];
  }
  return (avg/list.length);
}

module.exports = avg;

Run The Test

Now that the code and the test have been written, invoke the test runner:

$ npm test