How to write tests with Typescript and jest

RMAG news

Step 1: Set Up Your TypeScript Project

Create a new folder

mkdir test
cd test

Create a new TypeScript project.

Initialize your project and create a package.json file if you don’t have one already:

pnpm init

pnpm init -y

Install TypeScript and Jest as development dependencies:

npm i jest typescript ts-jest ts-node @types/jest @types/node -D

pnpm add jest typescript ts-jest ts-node @types/jest @types/node -D

Step 2: Configure TypeScript

Create a tsconfig.json file to configure TypeScript.
You can use the tsc –init command or create it manually.

{
“compilerOptions”: {
“target”: “ES6”,
“module”: “CommonJS”,
“outDir”: “./dist”,
“rootDir”: “./src”
}
},
“include”: [
“src”
]

Create a jest.config.ts file to configure Jest

pnpm create jest
import type {Config} from ‘jest’;

const config: Config = {
collectCoverage: true,
coverageProvider: “v8”,
preset: ‘ts-jest’,
roots: [
“<rootDir>”
],
testEnvironment: “node”,
verbose: true,
transform: {}
}

Create a src directory for your TypeScript source files and a tests directory for your test files.

Creates a file insider the folder src you migh named operation.ts

export function Sum(a: number, b: number): number {
return a + b;
}

import the file we created in the test location into a new file named operation.test.ts or operation.spec.ts

import { Sum} from “../src/operation”;

describe(“Math functions”, () => {
test(“should add two numbers correctly”, () => {
expect(add(1, 2)).toEqual(3);
});
});

Step 3: Run Your Tests

Add a script to your package.json to run the tests:

“scripts”: {
“test”: “jest”
}

Run your tests using:

npm run test

pnpm run test

Leave a Reply

Your email address will not be published. Required fields are marked *