How to Test TypeScript with Jest?
Last Updated :
03 Apr, 2025
Jest, a powerful JavaScript testing framework, seamlessly integrates with TypeScript, providing all the tools needed to write and run tests for your TypeScript code, ensuring quality and reliability.
It handles TypeScript compilation automatically, offers features like mocking and code coverage, and includes a user-friendly test runner for efficient testing.
Here's a breakdown of how to test TypeScript with Jest:
1. Setting Up Jest with TypeScript
These steps will get Jest working with your TypeScript project:
Step 1: Initialize and Install
Get started with Node.js and install the necessary packages
npm init -y
npm install --save-dev jest @types/jest ts-jest typescript
Step 2: Create a jest.config.js file
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
Step 3: Add a tsconfig.json file if you don't already have one
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Step 4: Once the setup is complete, you can start writing tests. Jest allows you to write test cases using its built-in functions like describe, test, it, expect, etc.
Step 5: Create a TypeScript file, say sum.ts
export const sum = (a: number, b: number): number => {
return a + b;
};
Step 6: Create a test file, sum.test.ts
import { sum } from './sum';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Note: Running the tests is straightforward using the Jest command-line interface. Jest provides detailed feedback on your tests, showing which tests passed, failed, and why.
Step 7: Run your tests using the following command
npx jest
Output:
OutputCase 1: Testing Mock Functions using Jest
Jest provides powerful mocking capabilities, allowing you to mock functions, modules, and timers. This is useful for isolating the code under test and controlling its dependencies.
Example: This example shows the testing of function.
JavaScript
// sum.ts
export const fetchData = (callback: (data: string) => void) => {
setTimeout(() => {
callback('peanut butter');
}, 1000);
};
JavaScript
// sum.test.ts
import { fetchData } from './sum';
test('fetchData calls callback with "peanut butter"', done => {
function callback(data: string) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
Output:
OutputCase 2: Testing Asynchronous Code
Testing asynchronous code can be challenging, but Jest makes it easier with support for async functions, promises, and callback-based code.
Example: This example shows the testing of Asynchronous function.
JavaScript
// sum.ts
export const fetchDataPromise = (): Promise<string> => {
return new Promise(resolve => {
setTimeout(() => {
resolve('peanut butter');
}, 1000);
});
};
JavaScript
// sum.test.ts
import { fetchDataPromise } from './sum';
test('the data is peanut butter', async () => {
const data = await fetchDataPromise();
expect(data).toBe('peanut butter');
});
Output:
Output
Similar Reads
How to use TypeScript with React?
TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
3 min read
How to redirect in React with Typescript ?
Navigating users seamlessly through a React application is a fundamental aspect of creating a smooth and intuitive user experience. In this article, we delve into the world of redirects in React, specifically addressing the use of TypeScript for enhanced type safety and developer productivity.Prereq
2 min read
How to Use MathJS with TypeScript?
Math.js library can be use with TypeScript to handle various mathematical tasks while getting the benefits of TypeScriptâs type safety and autocompletion. Integrating Math.js into your TypeScript project allows you to perform arithmetic, algebra, statistics, and more, with the added advantage of Typ
3 min read
How to use jQuery with TypeScript ?
In this article, we will learn how we can use jQuery with TypeScript and implement the features of both languages. The below approach can be used to implement jQuery in TypeScript. By installing jQuery using the npm commandThe jQuery can be installed in your current TypeScript project folder using t
2 min read
How to Setup a TypeScript Project?
In the world of modern web development, TypeScript has emerged as a powerful superset of JavaScript, offering static typing and improved tooling. Its strong typing system helps developers catch errors early during development, leading to more maintainable and scalable code. Whether you're starting a
2 min read
Node.js with TypeScript
If you're immersed in the world of Node.js development, you're likely acquainted with the hurdles of handling and expanding a substantial codebase. A viable solution to tackle this is leveraging TypeScript, a statically-typed superset of JavaScript. TypeScript enriches the language with optional typ
6 min read
How to add TypeScript in Next.js ?
In this article, we will learn how to add TypeScript in Next.js.Why should we use TypeScript in our project? The fundamental concept of TypeScript is that it is type-strict, which means that each entity, be it a variable, a function, or an object has a definite data type. It allows minimum bugs in t
5 min read
How to install TypeScript ?
TypeScript is a powerful language that enhances JavaScript by adding static type checking, enabling developers to catch errors during development rather than at runtime. As a strict superset of JavaScript, TypeScript allows you to write plain JavaScript with optional extra features. This guide will
3 min read
How to Use NextJS in Typescript?
TypeScript enhances Next.js applications by adding static type checking and improves developer experience through type safety. Integrating TypeScript into your Next.js project helps catch errors early and improves code maintainability. It offers even greater productivity and robustness to your web d
5 min read
How to Use TypeScript with Vite?
Vite is a modern build tool known for its speed and efficiency. Using TypeScript with Vite combines Vite's fast development experience with TypeScript's strong static typing, enabling early error detection and more maintainable code. This integration enhances productivity and code quality in modern
3 min read