How to use TypeScript with Jest

2022/12/61 min read
bookmark this


This blog shows how to get start use TypeScript to write code and also write in Jest.

Install Packages

If you have not use Jest, can reference this to get start with Jest with JavaScript, Get Start with Jest.

At here, we'll start install necessary NPM packages for use TypeScript at Jest and the code.

npm install --save-dev @babel/core @babel/preset-env @babel/preset-typescript @jest/globals @types/jest babel-jest ts-jest ts-node typescript

Create babel.config.js

module.exports = {
    presets: [
      ['@babel/preset-env', {targets: {node: 'current'}}],

Create jest.config.ts

export default {
    clearMocks: true,
    collectCoverage: true,
    coverageDirectory: "coverage"

Change the Code sample.js to TypeScript sample.ts

Change the Jest sample.test.js to TypeScript sample.test.ts

import {exponent, subtraction, sum} from '../src/sample';
import {describe, expect, test} from '@jest/globals';

describe('calculator', () => {
    test('test sum', () => {
        expect(sum(1, 2)).toBe(3);

    test('test subtraction', () => {
        expect(subtraction(10, 2)).toBe(8);

    test('test exponent', () => {
        expect(exponent(5, 2)).toBe(25);

Run npm run test

Now, if run npm run test and if everything works, should see test all passed and 100% coverage.