Sho*_*orn 5 typescript jestjs es6-modules node-fetch ts-jest
我正在尝试设置一个非常简单的 NPM 代码库,我可以用它来驱动 API 来进行一些测试。
\n导致错误的代码行只是import fetch from "node-fetch";,请参阅代码。
对于设置/配置,我正在关注此存储库(建议使用更好的模板将不胜感激):https://github.com/bromix/typescript-jest-example
\nnode-fetch当我尝试在代码中使用该库(在目录test.ts中的文件/test或目录.ts中的文件中/src)时,出现以下错误:
FAIL test/Api.test.ts\n \xe2\x97\x8f Test suite failed to run\n\n Jest encountered an unexpected token\n\n Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n...\n\n Details:\n\n C:\\ardc\\rats\\node_modules\\node-fetch\\src\\index.js:9\n import http from \'node:http\';\n ^^^^^^\n\n SyntaxError: Cannot use import statement outside a module\n\n > 1 | import fetch from "node-fetch";\n | ^\n 2 |\n 3 | const apiBase = "https://api.raid.org.au/v1";\n 4 |\n\n at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)\n at Object.<anonymous> (src/RaidApi.ts:1:1)\nRun Code Online (Sandbox Code Playgroud)\n我认为 node-fetch v3.x 升级为 esmodule 有一些奇怪的地方,如这里的答案所述: https: //stackoverflow.com/a/69385437/924597
\n但我尝试过加入一些不同的东西package.json,tsconfig.json但我无法让它工作。
我需要进行哪些更改才能使我的测试可以用于node-fetch发出请求调用?
该存储库的全部目的只是进行这些 HTTP 调用,因此无需考虑更改模块类型或任何需要执行的操作的兼容性问题。
\n我的解决方法是降级到此处node-fetch 2.6.7所示。但如果这个 esmodule 的东西是前进的方向,我想弄清楚如何让它发挥作用。
您可以在这里看到整个失败的项目:https://github.com/ardc-shorn/rats/tree/0cdf2cf1ff4bc9e7ef0fa6113db9b9ff9f6cc6c9
\n但是,有一个自造的问题,这是重要的配置。
\nFAIL test/Api.test.ts\n \xe2\x97\x8f Test suite failed to run\n\n Jest encountered an unexpected token\n\n Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n...\n\n Details:\n\n C:\\ardc\\rats\\node_modules\\node-fetch\\src\\index.js:9\n import http from \'node:http\';\n ^^^^^^\n\n SyntaxError: Cannot use import statement outside a module\n\n > 1 | import fetch from "node-fetch";\n | ^\n 2 |\n 3 | const apiBase = "https://api.raid.org.au/v1";\n 4 |\n\n at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)\n at Object.<anonymous> (src/RaidApi.ts:1:1)\nRun Code Online (Sandbox Code Playgroud)\r\n您的项目不是 ECMAScript 模块,因此您无法解析它们。唯一的例外是,如果它们包含 CJS 的替代版本,或者您使用的任何预 ESM 模块类型。实际上,通过快速 DDG/Google 搜索就可以很容易地弄清楚这一点。
在参考文献 2 中,我的 Pre-ESM 评论:因此,您使用了 CJS;如果 ESM 包包含转译的 CJS 版本,则只能使用它(我猜他们可以手写这两个包,但为什么呢?)。任何执行此操作的软件包都会在其软件包文档(README.md 文件)中明确声明它们支持 ESM 和 CJS。如果出于某种原因您想检查其文档以外的其他方式,您可以通过查看项目包含的任何 package.json 文件来快速判断。一个快速迹象是看到多个 package.json 文件,和/或在 package.json 中看到“exports”属性
| 归档时间: |
|
| 查看次数: |
6117 次 |
| 最近记录: |