DEV Community

CarlosAndress
CarlosAndress

Posted on

How to write tests with Typescript and jest

Step 1: Set Up Your TypeScript Project

Create a new folder

mkdir test
cd test
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
  ]
Enter fullscreen mode Exit fullscreen mode

Create a jest.config.ts file to configure Jest

pnpm create jest 
Enter fullscreen mode Exit fullscreen mode
import type {Config} from 'jest';

  const config: Config = {
  collectCoverage: true,
  coverageProvider: "v8",
  preset: 'ts-jest',
  roots: [
     "<rootDir>"
   ],
  testEnvironment: "node",
  verbose: true,
  transform: {}
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
  });
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Run Your Tests

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

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

Run your tests using:

npm run test

pnpm run test
Enter fullscreen mode Exit fullscreen mode

Top comments (0)