2

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',
  },
}
3
  • Do you get the error if you export the class directly instead of at the bottom of the file like that? i.e. export class MyProvider{ etc... Otherwise I'd say change export { MyProvider } to export default MyProvider and import in your test without the brackets Commented May 12, 2020 at 14:52
  • yeah same, i did both of your suggestions Commented May 12, 2020 at 15:02
  • It could be because you're not importing react in the test, on a side note your file isn't actually a react component, you can make it a ts file instead of tsx. Otherwise "import * as React from 'react'" in your test file Commented May 12, 2020 at 15:08

1 Answer 1

4

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",
  ]
Sign up to request clarification or add additional context in comments.

3 Comments

this worked. thanks! follow up tho, i thought you did not need to add a babel preset once you have tsconfig.js set and jest.config.js to transform tsx to js?
Tsconfig transpile your code in the build step. Right now your are not building your application. Babel transpile your code for Jest. @gdubs
@babel/preset-typescript is missing in your answer regarding installing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.