DEV Community

Acid Coder
Acid Coder

Posted on • Edited on

Jest + Typescript minus TS-Jest

ts-jest is a popular package for typescript + jest.

But one issue that is bugging me recently is the uncovered lines stat is not correct, my test coverage dropped by 10+%.

After some googling, seem like folks also having the same issue, still nothing useful come up, no solution

With some troubleshooting, I found out that it was ts-jest that causing the issue

so I decided to use babel for compilation instead

install dependencies

npm i -D @babel/preset-env @babel/preset-typescript typescript jest
Enter fullscreen mode Exit fullscreen mode

setup npm script

"scripts": {
  "test": "jest",
}
Enter fullscreen mode Exit fullscreen mode

create a jest.config.js

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */

module.exports = {
    testEnvironment: 'node',
    roots: ['<rootDir>/src'],
    testMatch: ['**/__tests__/**/*.+(ts|js)', '**/?(*.)+(spec|test).+(ts|js)'],
    transform: {
        '^.+\\.(js|ts)$': 'babel-jest',
    },
    moduleDirectories: ['node_modules', 'src'],
    collectCoverage: true,
    collectCoverageFrom: ['**/*.{js,ts}', '!**/*.d.ts'],
}

Enter fullscreen mode Exit fullscreen mode

create a babel.config.js

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

Enter fullscreen mode Exit fullscreen mode

you don't need to install babel-jest, it comes with jest

finally npm test and boom, your 100% test coverage is back.

Top comments (0)