Getting started Jest with Typescript

Goal

Write unit test with Jest and Typescript

Agenda

  1. Step 1: Simplest start set
  2. Step 2: Add Babel for ES2015
  3. Step 3: Add Typescript

* Each steps can be seen in Github brances
https://github.com/hoehoetester/hello-jest

Step 1: Simplest start set

Create a directory and install jest

1
2
3
mkdir hello-jest
cd hello-jest
yarn add -D jest

Create a js file to be tested named sum.js

1
2
3
4
5
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;

Create a test js file to test named sum.test.js

1
2
3
4
5
6
// sum.test.js
const sum = require("./sum");

it("add 3 + 4 to be 7", () => {
expect(sum(3, 4)).toBe(7);
});

Add scripts to package.json

1
2
3
4
5
6
// package.json
~~
"scripts": {
"test": "jest --watchAll"
}
~~

Open terminal and run test

1
yarn test

step1

Step 2: Add ES2015

Add babel dev moduels follow

  • @babel/core
  • @babel/polyfill
  • @babel/preset-env
1
yarn add -D @babel/core @babel/polyfill @babel/preset-env

Create a .babelrc file

1
2
3
4
// .babelrc
{
"presets": ["@babel/preset-env"]
}

Updates js files with ES2015 syntax

1
2
3
4
5
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
1
2
3
4
5
6
// sum.test.js
const sum = require("./sum");

it("add 3 + 4 to be 7", () => {
expect(sum(3, 4)).toBe(7);
});

Step 3: Add Typescript

Add typescript dev moduels follow

  • @babel/preset-typescript
  • @types/jest
  • babel-jest
1
yarn add -D @babel/preset-typescript @types/jest babel-jest

Update .babelrc file

1
2
3
4
// .babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-typescript"]
}

Change js files to typescritp files

  • sum.js –> sum.ts
  • sum.test.ts –> sum.test.ts

Update sum.ts files with typescript

1
2
3
4
5
// sum.ts
function sum(a: number, b: number): number {
return a + b;
}
export { sum };

References