Project Setup: Node, TS with Jest
2 min readMay 5, 2021
A simple project setup walkthrough to get you up and running with Jest on a Node project using Typescript.
Install dependencies
// Create directory
mkdir <project-name>// Install node
npm init -y// Install dependencies
npm i -D nodemon rimraf typescript ts-node ts-jest jest @types/jest @types/node1) nodemon - restart the project when files change
2) rimraf - help deep delete files
3) typescript - typescript compiler
4) ts-node - run TS without compile and 'then' a run
5) ts-jest - TS and Jest
6) jest - test framework
7) @types/jest - Typescript Types for Jest
8) @types/node - Typescript Types for Node
Setup package.json
// package.json
{
"name": "node-typescript-jest-starter",
"version": "0.0.1",
"description": "",
"main": "dist/index.js",
"scripts": {
"build": "rimraf dist && tsc",
"start": "node dist/index.js",
"dev": "nodemon --exec ts-node src/index.ts --watch src",
"test": "jest --watch",
"coverage": "jest --coverage"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/jest": "^23.3.11",
"@types/node": "^10.12.18",
"jest": "^23.6.0",
"nodemon": "^1.18.9",
"rimraf": "^2.6.3",
"ts-jest": "^23.10.5",
"ts-node": "^7.0.1",
"typescript": "^3.2.2"
}
}
Add git
git init
But don’t add everything to git
// .gitignore
node_modules
dist
coverage
Add Typescript Configuration
- Include only ts files in src folder, i.e. not dist (your compiled javascript)
// create config file
tsc --init// .tsconfig
{
"include": [
"src/**/*.ts"
], "exclude": [
"src/**/*/test.ts"
], "compilerOptions": {
"target": "ESNEXT",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Add Jest Configuration
// create config file
jest --init// jest.congig.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node'
};
Create src and dist directories
touch dist src
Create a test
// src/blackjack.test.ts
import { score } from "./blackjack";describe("blackjack", () => {
describe("determine the score of a hand", () => {
it('calculates a score correctly', () => {
let hand = 2;
expect(score(hand)).toEqual(2);
})
});
});
Run the test — which will run your test, and watch for changes.
npm run test
Write some Typescript — to pass the test
export const score = (hand: number) => {
return hand;
};
… write some better tests and better code!