Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Test TypeScript with Jest?
Next article icon

How to Test TypeScript with Jest?

Last Updated : 03 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

How to Test TypeScript with Jest
Output

Case 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:

Testing Mock Functions using Jest
Output

Case 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:

Testing Asynchronous Code
Output

Next Article
How to Test TypeScript with Jest?

N

nikunj_sonigara
Improve
Article Tags :
  • Web Technologies
  • TypeScript

Similar Reads

    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences