Using Jest With TypeScript

Using Jest With TypeScript

Introduction

Jest, a popular JavaScript testing framework, has gained immense popularity due to its simplicity, flexibility, and extensive features.

It offers a clean and concise syntax for writing unit tests, making it a preferred choice for developers worldwide. TypeScript, on the other hand, is a superset of JavaScript that adds static typing, enhancing code reliability and maintainability.

Combining Jest and TypeScript provides a powerful testing environment that ensures code correctness and enhances development efficiency. This guide will equip you with the knowledge to integrate Jest and TypeScript into your projects seamlessly.

How to install and use Jest

Step 1: Setting up the Development Environment

Before diving into Jest and TypeScript testing, ensure you have the necessary development tools installed.

  1. Node.js and npm: These are the foundation of JavaScript development, providing the environment for running Node-based applications and managing packages. Download and install the latest version of Node.js from https://nodejs.org/en/download.
  2. TypeScript: TypeScript is available as an npm package. To install it, open a terminal window and run the following command:
npm install -g typescript

  1. Jest: Install Jest using the npm package manager:
npm install -D jest

Step 2: Configuring the Project for TypeScript

Once you have the development tools in place, configure your project to support TypeScript.

  1. Create a tsconfig.json file: This file provides configuration settings for the TypeScript compiler. Create a tsconfig.json file at the root of your project directory.
  2. Define TypeScript Compiler Options: Specify the compiler options in the tsconfig.json file. Here’s an example of a basic configuration:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  }
}

Step 3: Setting up Jest for TypeScript

Jest has a built-in TypeScript support system, making it easy to integrate with TypeScript projects.

  1. Install ts-jest: ts-jest is a Jest preprocessor that enables running TypeScript tests in Jest. Install it using npm:
npm install -D jest @types/jest ts-jest

  1. Create a jest.config.js file: This file provides configuration settings for Jest, specifically for TypeScript support. Create a jest.config.js file at the root of your project directory.
  2. Enable TypeScript Support in Jest: In the jest.config.js file, enable TypeScript support using the ts-jest preset:
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node'
};

Step 4: Writing and Running Unit Tests

Now that your project is configured for Jest and TypeScript, you can start writing and running unit tests.

  1. Create Test Files: Create test files for the modules or components you want to test. Use the .spec.ts file extension for test files.
  2. Import the Testing Framework and Code: Import the necessary modules, including Jest and the code you want to test. For example, to test a function in the myModule class:
import '@jest/globals';
import { myModule } from './myModule';

  1. Write Unit Tests: Define test cases using Jest’s assertion methods. Each test case should describe a specific behaviour of the code you want to test.
  2. Run the Test Runner: Execute the tests using the Jest test runner. Run the following command in the terminal:
npx jest

Jest will compile the TypeScript tests and run the test suite. If any tests fail, Jest will report the errors and the failing test cases.

Example Unit Test Case

Here’s an example of a unit test case for a function that adds two numbers:

import '@jest/globals';
import { add } from './myModule';

test('add function should add two numbers', () => {
  expect(add(2, 3)).toBe(5);
});

This test case asserts that the add function returns the expected value of 5 when given the input values of 2 and 3.

Conclusion

Jest, with its TypeScript support, empowers you to write comprehensive and reliable tests for your TypeScript applications.

By leveraging Jest’s powerful assertion methods and organising tests into reusable suites, you can gain confidence in the correctness and stability of your code, ensuring a smoother development experience.

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.