Mitya
Mitya

Reputation: 34556

Jest: Failed to parse the TypeScript config file

I'm trying to install Jest for use with Babel and Typescript. I've followed the instructions shown here to the letter but I'm getting:

Error: Jest: Failed to parse the TypeScript config file C:...jest.config.js`

...when I run npm run test.

The contents of jest.config.ts is:

export default {
    //lots of commented-out stuff in here - nothing at all uncommented
}

Here's the exact steps I did:

sum.js:

function sum(a, b) {
  return a + b;
}
module.exports = sum;

sum.test.js

const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

package.json:

{
  "name": "jest-learn",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.17.5",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-typescript": "^7.16.7",
    "babel-jest": "^27.5.1",
    "jest": "^27.5.1"
  }
}

At this point, if I run yarn test, my test runs and passes just fine. The problem is when I try to introduce Babel and Typescript. Steps continue:

babel.config.js:

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

Now when I run npm run test I get the above error. What did I do wrong?

Upvotes: 8

Views: 17747

Answers (2)

koikingu
koikingu

Reputation: 11

This issue was fixed for me by just installing TS Node.

Upvotes: 1

nkmuturi
nkmuturi

Reputation: 456

This worked for me from Jest docs:

  • create and add file jest.config.ts to your source directory with content like:
    /** @type {import('jest').Config} */
        const config = {
            verbose: true,
        };
      
    module.exports = config;
  • Then, make sure to include the file in your tsconfig.json file:
    ...
    "include": ["./src/**/*.tsx", "./src/**/*.ts", "src/jest.config.ts"]
  • in your packages.json: Ensure also that you have installed jest, ts-jest, and ts-node-dev modules:
    ...
    },
      "devDependencies": {
        "@faker-js/faker": "^7.5.0",
        "@types/express": "^4.17.14",
        "@types/jest": "^29.0.3",
        "@types/uuid": "^8.3.4",
        "jest": "^29.0.3",
        "nodemon": "^2.0.20",
        "ts-jest": "^29.0.2",
        "ts-node-dev": "^2.0.0",
        "typescript": "^4.8.3"
      }

and that the jest transform configuration script looks like:

"jest": {
    "transform": {
      ".(ts|tsx)": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ]
  },

Upvotes: 2

Related Questions