Skip to main content

Jest for TypeScript

Jest is one of the most popular testing frameworks for JavaScript and TypeScript projects. This guide will walk you through configuring Jest for an existing TypeScript project, ensuring your tests run smoothly with TypeScript’s type-checking and features.


Prerequisites

Ensure the following dependencies are installed in your project:

Jest: Install Jest in your project and ts-jest, a TypeScript preprocessor for Jest:

npm install jest --save-dev
npm install ts-jest @types/jest --save-dev

Configuration Steps

  1. Add Jest Configuration

Create a jest.config.js file in the root of your project with the following content:

module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).ts?(x)'],
collectCoverageFrom: [
'src/**/*.{ts,tsx}', // Include source files
'!src/**/*.d.ts', // Exclude declaration files
],
coveragePathIgnorePatterns: [
'/node_modules/' // Exclude node modules
],
coverageReporters: ['text', 'lcov'],
};

  1. Verify TypeScript Configuration

Ensure your tsconfig.json includes appropriate options for Jest. Here’s an example:

{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "**/*.test.ts"]
}

  1. Add Test Scripts

Update your package.json to include test scripts:

"scripts": {
"test": "jest",
"test:watch": "jest --watch",
}

  1. Write a Test

Create a test file in your project, for example, src/sample.test.ts:

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

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

  1. Run Tests

Run your tests using the following script:

npm test

With this setup, your TypeScript project is ready to leverage Jest for robust and efficient unit testing. Happy testing!