【问题标题】:JEST - SyntaxError: Unexpected token 'export' with uuid libraryJEST - SyntaxError: Unexpected token \'export\' with uuid library
【发布时间】:2022-10-05 21:03:05
【问题描述】:

当我只使用 JavaScript 使用 Jest 时,我曾经解决过类似的错误,但目前我无法使用 Typescript 来解决。

在我安装需要@types/jest-environment-puppeteer、@types/puppeteer 和@types/expect-puppeteer 的Puppeteer 之前,我所有的测试都运行良好。

安装它们后,puppeteer 测试运行良好,但其他测试开始失败并出现以下错误。

  D:\\...\\api\\node_modules\\uuid\\dist\\esm-browser\\index.js:1    
    ({\"Object.<anonymous>\":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from \'./v1.js\';
                                                                                      ^^^^^^  

    SyntaxError: Unexpected token \'export\'

      at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)   
      at Object.require (../node_modules/@nestjs/common/decorators/core/injectable.decorator.js:4:16)

我做了什么?

allowJs: true on tsconfig.json 并在 jest configs 上设置 transformIgnorePatterns。这样 jest 就可以从node_modules/ 编译文件了 之后,此错误停止,但由于另一个奇怪的原因测试失败。 更糟糕的是,测试开始时间增加了太多。

所以我离开了allowJs,就像原来的设置一样,并更新了 jest 配置

\"transform\": {
   \"^.+\\\\.(t|j)s$\": \"ts-jest\"
}

至

\"transform\": {
   \"^.+\\\\.(t)s$\": \"ts-jest\"
}

所以目前 ts-jest 不编译 js 文件。但我认为我无法让 babel 选择 js 文件的转换。这些是我的笑话配置:

{
  \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],
  \"rootDir\": \".\",
  \"testEnvironment\": \"node\",
  \"testRegex\": \".e2e-spec.ts$\",
  \"transform\": {
    \"^.+\\\\.(t)s$\": \"ts-jest\",
    \"^.+\\\\.(js|jsx)$\": \"babel-jest\"
  },
  \"transformIgnorePatterns\": [\"<rootDir>/node_modules/.+.(js|jsx)$\"]
}

    标签: typescript jestjs babeljs puppeteer nest


    【解决方案1】:

    感谢这个回复: https://stackoverflow.com/a/54117206/15741905

    我开始在谷歌上搜索类似的修复程序,最后到了这里: https://github.com/uuidjs/uuid/issues/451

    这解决了我的问题:https://github.com/uuidjs/uuid/issues/451#issuecomment-1112328417

    // jest.config.js
    {
    //................
      moduleNameMapper: {
        // Force module uuid to resolve with the CJS entry point, because Jest does not support package.json.exports. See https://github.com/uuidjs/uuid/issues/451
        "uuid": require.resolve('uuid'),
      }
    }
    

    如果使用 jest-babel 可以解决这个问题,我仍然会很高兴。

    因为我不得不将 package.json 中的笑话配置带到单独的 .js 文件中。

    编辑: 据此github issue 兼容性问题已通过uuid 库的最新版本得到解决。

    【讨论】:

    • 我正在使用jest.config.ts 文件,而引号不断被剥离"uuid",并且修复不起作用。通过使其成为"^uuid$",这开始为我工作。截至 2022 年 8 月 23 日,最新版本的 uuid 仍然是 beta 版,上面未链接的链接表明它仅使用 beta 29.x of jest 进行了测试,所以我认为既然我刚刚从 27.x 升级,我会坚持现在用这个解决方案。谢谢。
    【解决方案2】:

    只需将 moduleNameMapper:{"^uuid$": "uuid"} 添加到我的 jest.config.js 中即可解决我的问题:

    暂时依赖uuid: ^8.3.2

    笑话: 28.1.3

    有角度的: 14.0.1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 2019-11-10
      • 2021-03-22
      • 2019-04-24
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多