jest with typescript throws an error when importing a file

Viewed 3082

I'm having issues with jest on typescript.

//myprovider.tsx

class MyProvider{
   constructor(){}
   giveMeFive(): int{  return 5;  }
}

export { MyProvider }



// myprovider.test.js

import { MyProvider } from './myprovider';

test('give me five!', () => {
  const myprovider = new MyProvider();
  /// assert
})

I get the following error

Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

import { MyProvider } from './myprovider';
       ^

I'm not sure what I'm missing, I have this on my package

//package.json

  "jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": ["ts", "tsx", "js"]
  },



// .babelrc

{
    "presets": [
        "@babel/preset-typescript"
    ]
} 



//jest.config.js

module.exports = {
  preset: 'ts-jest',
  transform: {
    '^.+\\.tsx?$': 'babel-jest',
  },
}
1 Answers

Make sure to install these packages:

babel-jest @babel/core @babel/preset-env

Your babel config should look like this:

  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          node: "current",
        },
      },
    ],
    "@babel/preset-typescript",
  ]
Related