Typescript and Unit Testing with Jest
#typescript #jest #javascript #unittesting

Typescript and Unit Testing with Jest

In this article, I'll cover setting up a simple Typescript project and configuring Jest to provide unit testing and code coverage for the project.

I going to create a simple calculator ES6 class that will implement a basic calculator interface for the following: add, subtract, multiple and divide. The project will be named basic-calculator but as you know Typescript is a superset of JavaScript and therefore can be named anything.

Requirements:

  • Node
  • VSCode

Create a new directory

mkdir basic-calculator && cd basic-calculator && code .

Note: code . ('code space .') will open VSCode at the basic-calculator folder location if VSCode is installed and configured.

From the terminal in VSCode, run npm init to setup the new npm package

npm init --y

Note: this will create a package.json file in the directory accepting the basic defaults for the project.

Install the project development dependencies:

npm install --save-dev @types/jest @types/node jest ts-jest tsconfig-paths typescript

Open the package.json file in VSCode, add the following jest configuration to the bottom of the file. Place a comma after the closing curly bracket for devDependencies.

"jest": {
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "ts",
      "tsx"
    ],
    "rootDir": "src",
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
    "transform": {
      "^.+\\.(t|j)sx?$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
}

Next: create the src folder. This is where the Typescript code files will go for the project.

In the root project directory create the tsconfig.json file, this will provide Typescript with the build instructions for the project.

{
    "compilerOptions": {
        "declaration": true,
        "module": "commonjs",
        "strict": true,
        "removeComments": true,
        "noLib": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es6",
        "sourceMap": true,
        "outDir": "./dist",
        "rootDir": "./src",
        "skipLibCheck": true
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts",
        "**/*.test.ts"
    ]
}

With that out of the way, time to write some code. Create the following files in a src directory "index.ts", "index.spec.ts", "calculator.interface.ts"

Open the calculator.interface.ts file:

export interface ICalculator {
    add(a:number, b:number): number;
    subtract(a:number, b:number): number;
    multiple(a:number, b:number): number;
    divide(a:number, b:number): number;
}

Next open the index.ts file:

import { ICalculator } from './calculator.interface';

export class BasicCalculator implements ICalculator {
  add(a: number, b: number): number {
      return a + b;
  }
  subtract(a: number, b: number): number {
      return a - b;
  }
  multiple(a: number, b: number): number {
      return a * b;
  }
  divide(a: number, b: number): number {
      return a/b;
  }
}

Next open the index.spec.ts file:

import { BasicCalculator } from './index';


describe('BasicCalulator Testing', () => {
    let calc: BasicCalculator = new BasicCalculator();


    test('should return an instance of a basic calculator', () => {
        expect(calc).toEqual(<BasicCalculator>{});
    });


    test('should return the addition of a + b', () => {
        expect(calc.add(1,3)).toEqual(4);
    });


    test('should return the subtraction of a - b', () => {
        expect(calc.subtract(1,3)).toEqual(-2);
    });


    test('should return the multple of a * b', () => {
        expect(calc.multiple(1,3)).toEqual(3);
    });


    test('should return the divide of a / b', () => {
        expect(calc.divide(1,3)).toEqual(1/3);
    });
});


One last bit of configuration for the package.json file. Update the scripts section of the file as follows:

"scripts": {
    "build": "tsc -p tsconfig.json",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand"
}

Now we are ready to "jest" test... I couldn't help it. lol...

To run the test suite defined in the index.spec.ts file

From the terminal, type npm run test

To run the test suite with code coverage in the index.spec.ts file

From the terminal, type npm run test:cov

And that is it. Thanks. I hope this helps you.


Igor Cherny

Software System Engineer AT&T

1y

In 2024 this code doesn't work since you have to add and configure the Babel to the project.

Monikaben Lala

Founder | Product MVP Expert | Fiction Writer | Find me @Dubai Trade Show

2y

Dexter, thanks for sharing!

Like
Reply
Dhara Mishra

Join our 14 November Global B2B Conference

2y

Dexter, thanks for sharing!

Like
Reply
Santhosh Kumar Konda

Software Development Engineer

4y

Thanks . Great content

Like
Reply
Kc Elma

Student at Texas A&M University

4y

This is great where can I find more ?

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore topics