Optional chaining issues when running test with jest
Asked Answered
I

3

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?

Ithnan answered 28/2, 2021 at 0:0 Comment(0)
K
11

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

Klimt answered 5/4, 2021 at 7:31 Comment(0)
M
8

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

Migratory answered 2/2, 2022 at 4:31 Comment(0)
P
0

Avoid these type of values

"lib": ["dom", "dom.iterable", "esnext"], 
"target": "ES2017", 

this is work for me

"lib": ["ES2020"],
"target": "ES2020" 
Polymorphism answered 7/10, 2023 at 5:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.