typescript JEST -语法错误:带有uuid库的意外标记“export”

yeotifhr  于 2022-12-05  发布在  TypeScript
关注(0)|答案(2)|浏览(189)

我曾经在使用Jest时只使用JavaScript来解决类似的错误,但目前我无法使用Typescript来解决。
我所有的测试都运行良好,直到我安装了Puppeteer,它需要@types/jest-environment-puppeteer@types/puppeteer@types/expect-puppeteer
安装后, puppet 师测试运行完美,但其他测试开始失败,并出现以下错误。

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)

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

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

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

所以目前ts-jest不能编译js文件。但是我想我不能让babel选择js文件的转换。下面是我的jest配置:

{
  "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)$"]
}
fv2wmkja

fv2wmkja1#

感谢此回复: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。
因为我必须将jest配置从package.json转移到一个单独的.js文件中。
编辑:根据这个github问题,uuid库的最新版本已经解决了兼容性问题。

gj3fmq9x

gj3fmq9x2#

只需将moduleNameMapper:{"^uuid$": "uuid"}添加到我的jest.config.js中就可以解决这个问题:
暂时相关性uuid:^8.3.2中的值
第28.1.3节

棱角分明:14.0.1

相关问题