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": [

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": [
    "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';

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. []

2 Replies to “Using Jest with TypeScript”

  1. When I mocked the below class, only the inherited properties are available on the mocked object. The ones defined in the class are not available and when tried to spyOn the methods, an exception is thrown that “x” is not a property.
    class B extends A {
    public foo() {
    class A {
    public bar() {}

    // SomeOtherTest.js
    const mockedB = new B();
    spyOn(mockedB, “foo”); // exception at this line.

    I wanted to know why is jest not able to properly mock the objects.

Leave a Reply

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