8

I am trying to run a test with Jest and I'm currently using jsx and tsx (changing from js to ts) in my react app but when I run my tests, all jsx tests are successful except those in tsx with optional blocking. I always get an error Unexpected token on my input that looks like

...
<Input 
    value={parent?.child}
...

this is my jest config

{
    "verbose": true,
    "roots": [
      "<rootDir>/app"
    ],
    "setupFiles": [
      "./config/webpack/jest/config.js"
    ],
    "moduleNameMapper": {
      "^components(.*)": "<rootDir>/app/javascript/components$1",
      "^utils(.*)": "<rootDir>/app/javascript/utils$1",
      "^types(.*)": "<rootDir>/app/javascript/types$1",
      "\\.(css|pcss|scss)$": "<rootDir>/spec/__mocks__/styleMock.js",
      "\\.(gif|ttf|eot|svg|png)$": "<rootDir>/spec/__mocks__/fileMock.js"
    },
    "snapshotSerializers": [
      "<rootDir>/node_modules/enzyme-to-json/serializer"
    ],
    "testRegex": "(/__tests__/.*|\\.(test))\\.(ts|tsx|js|jsx)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx"
    ],
    "transform": {
      "\\.[jt]sx?$": "babel-jest"
    }
}

What could be the problem how can I work with optional chaining and jest?

Henry Okonkwo
  • 363
  • 7
  • 17

2 Answers2

9

For me the issue was that in my tsconfig.json, I was using "lib": ["ES2020"], which was in conflict with my node version. Changing node version to v14 solved the issue.
Here you'll find a link with lib targets with node versions:

https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Octavian Rotari
  • 325
  • 2
  • 10
7

change tsconfig.json using "lib": ["ES2020"], "target": "ES2020", also worked for me. Tks

user3166763
  • 71
  • 1
  • 1