samdlc

Getting started with TypeScript and Jest

December 11, 2018

In this post I’ll be explaining how to set up a new TypeScript project, and add automated testing with Jest. I recently found myself going through the same steps repeatedly when setting up new projects for various katas, so I hope this will save some time for others in a similar position.

To start off with, create a directory for your new project.

mkdir my-project
cd my-project

Next you should initialise an empty git repo and package.json.

git init
npm init -y

Then add TypeScript to your project, and initialise with tsc.

npm i -D typescript
npx tsc --init

You may want to configure where transpiled JavaScript files are saved to in your tsconfig.json.

// uncomment and set this to wherever you prefer
"outDir": "./dist"
npm i -D @types/jest jest ts-jest
npx jest init

Edit your jest.config.js to make use of ts-jest and pick up TypeScript test files

module.exports = {
  coverageDirectory: 'coverage',
  globals: {
    'ts-jest': {
      tsConfig: 'tsconfig.json',
    },
  },
  moduleFileExtensions: [
    'js',
    'ts',
    'tsx',
  ],
  testEnvironment: 'node',
  testMatch: [
    'src/**/__tests__/*.+(ts|tsx)',
  ],
  testPathIgnorePatterns: ['/node_modules/'],
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
  },
  preset: 'ts-jest',
}

You can now start writing your TypeScript code and tests under the src directory.

mkdir -p src/__tests__
touch src/index.ts src/__tests__/index.ts

To run your tests, just use npm

npm run test

I’ve published a repo on GitHub for use as a simple boilerplate project, if you want to skip the setup and get straight into the coding. You can find it here

Happy TypeScripting!


Sam Delacruz

Written by Sam Delacruz
I'm a Software Engineer from London, building useful things.