I have a trouble with Jest on my Typescript React project.
Node: 16.10.0 Jest: 26.6.3 Babel-jest: 26.6.3
When I run command jest <file-name
to execute a test on a file, I get the error message with stacktrace like this:
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".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/<username>/<my_project>/test/jest.setup.ts:11
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
It seems like the babel-jest
transformer cannot load the typescript file with esm6 module.
I realize this happens globally to all projects in my machine, other teammates don't.
Especially, this issue does not occurs when I run with sudo
permission.
These are some actions I tried:
- Removing all
node_modules
and reinstalled. - Reinstalled Node
- Change owner of some suspected folders and files. Like global node_module from root -> current user.
- Add
type: module
to package.json.