Step 1: Set Up Your TypeScript Project
Create a new folder
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 -y
Install TypeScript and Jest as development dependencies:
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
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
return a + b;
}
import the file we created in the test location into a new file named operation.test.ts or operation.spec.ts
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:
“test”: “jest”
}
Run your tests using:
pnpm run test