Gary Sieling

Using Jest with TypeScript

Jest1 is something like one of a hundred different unit testing frameworks for Javascript. I’ve set it up, because the React team is using it.

npm install --save-dev jest-cli
typings install 'dt!jest' --ambient --save

I set this up with TypeScript, but found it required some time fiddling to get it to work.

First, I set up tsconfig.json to put the compiled Javascript files somewhere out of the way, and in CommonJS:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": false,
        "sourceMap": false,
        "outDir": "dist"
    },
    "exclude": [
        "node_modules"
    ]
}

Your package.json needs a “jest” section added as well – once you set it up, this is what it should look like:

{
  "name": "books",
  "version": "1.0.0",
  "description": "",
  "main": "import-editions.ts",
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "testPathDirs": [
      "dist/"
    ],
    "testRegex": "__tests__/.*$"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "jest-cli": "^13.2.3"
  }
}

Your code can just go in it’s own file, like you’d normally expect (this is import-editions.ts):

function parseLine(line: string) {
  return 'abc'
}

export { parseLine }

Then you can write a test file (put this in __tests__/import-editions-tests.ts):

import { parseLine } from '../import-editions';

jest.unmock('../import-editions');
describe('parseLine', () => {
  it('parses the header part of the line', () => {
    expect(parseLine('test data')).toBe('abc');
  });
});

Once you compile the tests, you can run them without issue.

There are some people out there who use babel as a preprocessor, but I haven’t seen a way to make this work with TypeScript. Some people also use webpack – this is probably the way to go, if you don’t like my approach.

  1. https://facebook.github.io/jest/ []
Exit mobile version