How to Run Jest Unit Tests in a Typescript Project

dorinandreidragan - Aug 9 - - Dev Community

How To Run Jest Unit Tests In a Typescript Project

Follow these steps to set up Jest unit tests in a TypeScript project.

IMPORTANT

This guide uses the ts-jest npm library to simplify the setup. As described on the npm page, ts-jest is a Jest transformer with source map support that allows you to use Jest to test projects written in TypeScript.

Step 1 - Create your project folder and initialize npm

Run the following commands to create a new project folder and initialize npm. Replace my-project with the name of your project.

mkdir my-project
cd my-project

npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2 - Install prerequsites

Run the following command to install the necessary npm packages.

npm install --save-dev typescript jest ts-jest @types/jest
Enter fullscreen mode Exit fullscreen mode

Step 3 - Setup the typescript project

Run the following command to create a tsconfig.json file in your project folder.

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Step 4 - Configure Jest

Run the following command to create a Jest configuration file that is compatible with Typescript.

npx ts-jest config:init
Enter fullscreen mode Exit fullscreen mode

This command will create the jest.config.js file in your project folder.

Step 5 - Create some code and unit tests

Create the src/calculator.ts file as below:

export function add(a: number, b: number): number {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Create the tests for the calculator in the test/calculator.spec.ts file as below:

import { add } from "../src/calculator";

describe("Calculator tests", () => {
    it("should add two numbers", () => {
        expect(add(1, 2)).toBe(3);
    });
})
Enter fullscreen mode Exit fullscreen mode

Step 6 - Run the tests

Run the tests from the command line as below:

npx jest
Enter fullscreen mode Exit fullscreen mode

You should see these results in the console:

❯ npx jest
 PASS  test/calculator.spec.ts
  Calculator tests
    ✓ should add two numbers (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.385 s, estimated 2 s
Ran all test suites.
Enter fullscreen mode Exit fullscreen mode

Step 7 - Add test script in package.json file

To run the tests via the npm test command you can change the scripts section in the package.json file to look like this:

"scripts": {
    "test": "jest"
}
Enter fullscreen mode Exit fullscreen mode

Now you should be able to run the tests with the npm test command and get the same output in the console.

.
Terabox Video Player