【问题标题】:Jest setup for typescript with module resolution带有模块分辨率的打字稿的开玩笑设置
【发布时间】:2020-02-01 00:37:15
【问题描述】:

该项目正在使用 ReactJS、Typescript、Webpack 和 Jest。 为了实现模块解析(以最小化导入),我们进行了以下更改:

TSConfig.js:

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

Webpack.config.js

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

代码运行良好,但是 Jest 测试开始失败并出现错误:

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

这是因为,Jest 还不知道如何将 Common 解析为 Src/common 并且不查看 node_module。为了解决这个问题,进行了以下更改:

jestConfig.js

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

这似乎已解决,但我还有另一个问题 [这就是我在这里的原因:)]

Jest 遇到了意外的令牌

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)

这是完整的 jest.config.js 文件:

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"
  ]
}

【问题讨论】:

  • 代码由于某种原因有一个非顶级的导出语句,这是非法的。如果你是这样写的,你需要改变它。如果它是工具或流程的输出,则需要调试该流程。
  • 你说的是哪个代码,jest.config.js?另外,您知道,代码运行良好,只是开玩笑抛出这个问题。
  • 我说的是您自己发布的错误:function(module,exports,require,__dirname,__filename,global,jest){export * from './Acc'。函数体内不能有导出语句。导入/导出必须是静态可解析的。有一个关于返回 Promise 的import 函数的提议,但是无论您以何种方式分割它,该导出语句都是非法的。错误消息将您指向它。
  • 不,我的代码不包含这个函数是这样的:export * from './Async'简单明了的一系列导出语句。
  • 这是来自 node_modules 目前 node.js 不支持 esm 所以我们必须添加 babel-jest 包

标签: typescript webpack jestjs


【解决方案1】:

好的,所以我可以通过将此行添加到 jest.config.js 来修复模块分辨率

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

【讨论】:

    【解决方案2】:

    貌似 babel 默认无法解析 typescript 测试文件,所以安装npm install ts-jest babel-jest --save-dev 然后在 jest.config.js 文件中添加下面的配置。

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

    【讨论】:

    • 我们在 jest.config.js 中有这个。问题是,当我使用模块解析时,Jest 无法解析非节点模块导入。
    • 添加在问题的末尾。
    • 代码由于某种原因有一个非顶级的导出语句。再多的转变也无法解决这个问题。
    • 这是否意味着我必须安装 babel-jest?目前我没有。
    • 是的,你必须安装“npm install babel-jest --save-dev”
    猜你喜欢
    • 2016-04-18
    • 2021-12-09
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2021-01-09
    • 2017-10-02
    • 2020-07-09
    相关资源
    最近更新 更多