Home

Published

- 2 min read

Setting up TypeScript and Jest

img of Setting up TypeScript and Jest

We will take a quick look at how to set up a project using TypeScript and Jest. By adding Jest to the project from the beginning this should encourage test driven development – or at least that developers have minimal effort

Init Project

npm init -y
npm i -D typescript ts-node
tsc --init

npm i -D jest ts-jest @types/jest
npx ts-jest config:init

mkdir src
mkdir dist

Configure Project

tsconfig.json

For TypeScript you need to adjust a couple of variables like:

  • outDir = “./dist”
  • rootDir = “./src”
  • (optional) target: “es2017” (if you are not supporting IE11)
  • (optional) module: “esnext”
{
	"compilerOptions": {
		"target": "es2017",
		"module": "esnext",
		// ...
		"outDir": "./dist",
		"rootDir": "./src"
		// ...
	}
}

package.json

the only thing that remains is to add a couple of scripts to make development easier.

{
    "main": "./dist/index.js",
    "scripts": {
        "start": "ts-node ./src/index.ts",
        "test": "jest --watch",
        "build": "tsc"
    },
}

Init git

It is always the best practice to use version control for coding projects – even if you are the only developer. Running Jest in “–watch” mode requires that the code is stored in a git repository.

.gitignore

You need to tell git to exclude the node_modules folder. (This is done as the dependencies can be restored by running npm install). Create a file called “.gitignore” and add following line:

/node_modules

First commit

Now you can create your first commit, it will exclude the node_modules folder

git init
git add .
git commit -m "Initial Commit"

Start Development

Demo Files

Create the files:

  • ./src/index.ts
  • ./src/index.test.ts

index.ts

export const greeting = () => {
	return 'Hello World!'
}

index.test.ts

import { greeting } from './index'

it('greets you', () => {
	expect(greeting()).toBe('Hello World!')
})

Run Demo / Start Development

Now you can start development by running npm test This will start jest and run your tests as soon as you change your code.