TypeScript jest (ts-jest)


Example

jest is painless JavaScript testing framework by Facebook, with ts-jest can be used to test TypeScript code.

To install jest using npm run command

npm install --save-dev jest @types/jest ts-jest typescript

For ease of use install jest as global package

npm install -g jest

To make jest work with TypeScript you need to add configuration to package.json

//package.json
{
...
"jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": ["ts", "tsx", "js"]
  }
}

Now jest is ready. Assume we have sample fizz buz to test

//fizzBuzz.ts
export function fizzBuzz(n: number): string {
    let output = "";
    for (let i = 1; i <= n; i++) {
        if (i % 5 && i % 3) {
            output += i + ' ';
        }
        if (i % 3 === 0) {
            output += 'Fizz ';
        }
        if (i % 5 === 0) {
            output += 'Buzz ';
        }
    }
    return output;
}

Example test could look like

//FizzBuzz.test.ts
/// <reference types="jest" />

import {fizzBuzz} from "./fizzBuzz";
test("FizzBuzz test", () =>{
    expect(fizzBuzz(2)).toBe("1 2 ");
    expect(fizzBuzz(3)).toBe("1 2 Fizz ");
});

To execute test run

jest

In output you should see

 PASS  ./fizzBuzz.test.ts
  ✓ FizzBuzz test (3ms)

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

Code coverage

jest supports generation of code coverage reports.

To use code coverage with TypeScript you need to add another configuration line to package.json.

{
...
  "jest": {
  ...
    "testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js"
  }
}

To run tests with generation of coverage report run

jest --coverage

If used with our sample fizz buzz you should see

 PASS  ./fizzBuzz.test.ts
  ✓ FizzBuzz test (3ms)

-------------|----------|----------|----------|----------|----------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-------------|----------|----------|----------|----------|----------------|
All files    |    92.31 |     87.5 |      100 |    91.67 |                |
 fizzBuzz.ts |    92.31 |     87.5 |      100 |    91.67 |             13 |
-------------|----------|----------|----------|----------|----------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.857s
Ran all test suites.

jest also created folder coverage which contains coverage report in various formats, including user friendly html report in coverage/lcov-report/index.html

jest html report