I encountered an issue in Jest where it throws an "Unexpected token", Can anyone help me?

The error message is:

/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)

Jest encountered an unexpected token. This usually means that you are trying to import a file that 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:

  • 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:

export default BitcoinWidget;

How can I resolve this “Unexpected token” error in Jest?

Hey Heena,

Add the following configuration to the jest section of your package.json:

"transform": {
  "\\.js$": "<rootDir>/node_modules/babel-jest"
}

If you still encounter issues, please let me know.

I agree with Devan,

but here’s what I tried, and it works for me.

For those using the Create React App, it’s important to note that only certain Jest configurations can be modified directly in package.json. If you’re facing issues with Jest not processing an internal library and encountering ‘unexpected token’ errors in imports from this library, you can resolve this by updating your test script.

Change your test script in package.json to the following:

"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'"

Replace <your-package-goes-here> with the name of your package. This configuration will ensure that Jest processes the specified library correctly.

For those who have struggled with Jest configuration issues and the previous solutions did not resolve the problem, here’s a working solution: Update your jest.config.js file to include transformIgnorePatterns:

// jest.config.js


module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
    transform: {
        "^.+\\.(js|ts)$": "ts-jest",
    },
    transformIgnorePatterns: [
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.js$",
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.ts$",
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.tsx$",
    ],
}

Replace [@autofiy/autofiyable|@autofiy/property] with the packages you want Jest to transform. Separate multiple package names with a | character.