Jest "unexpected token" with Antd and React

Viewed 1844

I get the following error when using Jest with Antd, React and Parcel. Jest complains about the Antd css file. Should Jest even include node_modules by default? And if not, is it possible to exclude it?

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.


{ProjectPath}/node_modules/antd/lib/style/index.css:5
.ant-modal,
^

SyntaxError: Unexpected token '.'

   8 | 
   9 | 
> 10 | export default () => {

jest.config.js

{
    "jest": {
        "setupFilesAfterEnv": [
            "<rootDir>src/setupTests.js"
        ],
        "transform": {
            "^.+\\.js$": "babel-jest",
            ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
        }
    }
}

.babelrc

{
    "presets": [
        "@babel/preset-react",
        "@babel/preset-env"
    ],
    "plugins": [
        [
            "import",
            {
                "libraryName": "antd",
                "style": "css"
            }
        ]
    ]
}

.lessrc

{
  "javascriptEnabled": true
}
2 Answers

Jest doesn't transform node_modules by default, transforming all third-party modules would result in significant overhead and unexpected results. So Antd .css files aren't transformed by jest-transform-stub and fail to import because they aren't valid JS files.

All exclusions need to be specified in transformIgnorePatterns:

"transformIgnorePatterns": [
  "node_modules/(?!(antd)/)"
]

It can potentially be narrowed down to antd/lib/style/.

You did right to use jest-transform-stub to mock import assets during test, but Jest won't apply for the node_modules though. So use the option moduleNameMapper to make it apply too:

"moduleNameMapper": {
  "^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
}
Related