5

The project is using ReactJS, Typescript, Webpack and Jest. To achieve module resolution (to minimize import), we made following changes:

TSConfig.js:

"compilerOptions": { "baseUrl": "src",}

Webpack.config.js

alias: {
  Common: path.resolve(__dirname, 'src/Common/'),
},

The code works fine, however Jest tests started failing with error:

Cannot find module 'Common/js/utils' from 'MyContact.ts'

This is because, Jest is not yet aware of how to resolve Common to Src/common and not to look in node_module. To fix this, following change were made:

jestConfig.js

moduleNameMapper: {"Common": "<rootDir>/src/Common"}

That seems fixed, but then I have another issue [which is why I am here :)]

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

C:\Users\ua\Project\develop\src\Common\index.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './Acc'
                                                                                         ^^^^^^

SyntaxError: Unexpected token export

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)

Here is full jest.config.js file:

module.exports = {
  verbose: false,
  roots: ["<rootDir>/src"],
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
  globals: {
    'ts-jest': {
      diagnostics: false
    }
  },
  moduleNameMapper: {
    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
      "<rootDir>/__mocks__/fileMock.js",
    "\\.(css|less|pcss)$": "<rootDir>/__mocks__/styleMock.js",
    "Common": "<rootDir>/src/Common",
  },
  snapshotSerializers: ["enzyme-to-json/serializer"],
  setupFilesAfterEnv: ["<rootDir>/setupEnzyme.ts"],
  testMatch: [ "**/__tests__/**/*.test.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)"],
  collectCoverageFrom: ["**/*.{ts,tsx}", "!**/node_modules/**", "!**/vendor/**"]
};

tsconfig.js:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "src",
    "typeRoots": [
      "./node_modules/@types",
      "./custom_typings"
    ],
    "outDir": "build",
    "module": "commonjs",
    "skipLibCheck": true,
    "moduleResolution": "node",
    "removeComments": true,
    "target": "es5",
    "sourceMap": true,
    "lib": [ "dom", "es2015", "es2017", "esnext" ],
    "noEmit": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "allowUnusedLabels": false,
    "jsx": "react",
    "allowJs": true,
    "isolatedModules": false,
    "strictNullChecks": false,
    "noEmitHelpers": false,
    "allowSyntheticDefaultImports": true
  },
  "typeRoots": [
    "./node_modules/@types",
    "./custom_typings"
  ],
  "exclude":[
    "./node_modules"
  ],
  "include": [
    "src/*",
    "custom_typings"
  ]
}

8
  • Code for some reason has a non-top-level export statement, which is illegal. If you wrote it that way, you'll need to change it. If it's the output of a tool or process, you'll need to debug that process. Commented Oct 2, 2019 at 18:14
  • which code you are talking about, jest.config.js? Also just so you know, the code is running fine, it's just jest throwing this issue. Commented Oct 2, 2019 at 18:21
  • I'm talking about the error you yourself posted: function(module,exports,require,__dirname,__filename,global,jest){export * from './Acc'. You cannot have an export statement inside a function body. Imports/exports have to be statically resolvable. There is a proposal for an import function that returns a Promise, but that export statement is flat out illegal any way you slice it. The error message points you right to it. Commented Oct 2, 2019 at 18:23
  • no, my code does not contain this function it is like: export * from './Async' Plain and simple series of export statements. Commented Oct 2, 2019 at 18:24
  • This is come from node_modules currently node.js doesn't esm support so we have to add babel-jest package Commented Oct 2, 2019 at 18:26

2 Answers 2

6

Ok, so I was able to fix module resolution by adding this line to jest.config.js

moduleDirectories: ["node_modules", "src"],

Sign up to request clarification or add additional context in comments.

Comments

1

Looks like babel by default can't parse typescript test file, so do install npm install ts-jest babel-jest --save-dev Then add below config in jest.config.js file.

  transform: {
    '^.+\\.jsx?$': require.resolve('babel-jest'),
    '^.+\\.tsx?$': 'ts-jest',
  }

8 Comments

We have this in jest.config.js. The problem is that as I am using module resolution, Jest is not able to resolve non node-module imports.
Added at the end of the question.
Code for some reason has a non-top-level export statement. No amount of transforming is going to fix that.
does it mean I have to install babel-jest? Currently I do not have it.
Yes you have to install "npm install babel-jest --save-dev"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.