ts-jest: Jest encountered an unexpected token

Detail:

I have updated a third party library axios version to 1.6.7 . When I ran tests I started to get the following error ` 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:

D:\gitRepos\apimatic-js-runtime\node_modules\axios\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import axios from './lib/axios.js';
                                                                                         ^^^^^^

SyntaxError: Cannot use import statement outside a module

> 1 | import { AxiosHeaders, AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosResponseHeaders, RawAxiosResponseHeaders } from 'axios';
    | ^
  2 | import axios from 'axios';
  3 | import isNode from 'detect-node';
  4 | import FormData from 'form-data';

  at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1350:14)
  at Object.<anonymous> (src/httpClient.ts:1:1)`

package.json

  "devDependencies": {
    "@babel/cli": "^7.21.5",
    "@babel/core": "^7.22.1",
    "@babel/preset-env": "^7.18.2",
    "babel-jest": "^26.6.3",
    "@size-limit/preset-small-lib": "^7.0.8",
    "@types/detect-node": "^2.0.0",
    "@types/lodash.flatmap": "^4.5.6",
    "abort-controller": "^3.0.0",
    "babel-plugin-annotate-pure-calls": "^0.4.0",
    "jest": "^26.6.3",
    "jsdom": "^19.0.0",
    "jsdom-global": "^3.0.2",
    "lerna-alias": "3.0.3-0",
    "rollup": "^2.79.0",
    "rollup-plugin-typescript2": "^0.31.0",
    "size-limit": "^7.0.8",
    "ts-jest": "^29.1.2",
    "typescript": "^4.1.2"
  }

jest.config.js `const { jest: lernaAliases } = require(‘lerna-alias’);

module.exports = { preset: ‘ts-jest’, moduleNameMapper: lernaAliases(), transform: { ‘^.+\.tsx?$’: ‘ts-jest’, // Add TypeScript transformation ‘^.+\.jsx?$’: ‘babel-jest’, // Add Babel transformation for ES6 modules }, coverageReporters: [[‘lcov’, { projectRoot: ‘…/…/’ }]] }; `

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 11
  • Comments: 16

Commits related to this issue

Most upvoted comments

@thenoseman you can use this workaround

transform: {
    '^.+\\.(ts|js)$': ['ts-jest', {
      isolatedModules: true,
    }]
},

there is my-method to solve this which I wan’t to use third-esm-modules such as chalk

tsconfig.json need has module: "ESNext" and target: "ES2020" option ( ES may could ),


  {
    "compilerOptions": {

     // update this
      "target": "ES2020",
      "module": "ESNext",
      "moduleResolution": "node",
     // update end

      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,
      "strict": true,
      "skipLibCheck": true,
      "outDir": "dist"
    },
    "include": ["src"]
  }

then, you should config your jest.config.ts with


  import type {Config} from 'jest';

  export default async (): Promise<Config> => {
      return {

         // must has
          extensionsToTreatAsEsm: ['.ts'],
        // must has
          transform: {
              "^.+\.tsx?$": ["ts-jest",{
                  useESM: true, 
                  isolatedModules: true  
              }],
          },

      } as Config;
  };

end, your package.json like

"scripts": {
    "test": "NODE_OPTIONS=--experimental-vm-modules jest"
  },

must has --experimental-vm-modules node-option

The suggested fix does not work for me either. The error message points to an import statement in octokit, of which I’m using version 4.1.0.

I cannot thank you enough, that drove me nuts for two days! Thanks a lot!