【发布时间】:2021-11-21 18:45:29
【问题描述】:
我正在尝试升级我的 api 以使用 node-fetch 3.0.0。他们文档中的部分重大更改是 node-fetch 现在是一个纯 ESM 模块。
https://github.com/node-fetch/node-fetch/blob/main/docs/CHANGELOG.md
我的单元测试已经开始摆脱这种变化。我使用 jest.requireActual("node-fetch") 作为响应对象
const { Response } = jest.requireActual("node-fetch");
但是,随着新的变化,我得到:
“类型‘{}’上不存在属性‘响应’。”
我尝试更改为似乎可以修复该错误的导入语句:
import { Response } from "node-fetch"
现在,我在运行单元测试时收到以下错误:
Test suite failed to run
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:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• 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\{mypath}\api\node_modules\node-fetch\src\index.js:9
import http from 'http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
2 | import { AuthProvider, TokenCache } from "./tokenTypes";
3 | import { getUserEmail, getUserId, getUserRole } from "../common/authUtil";
> 4 | import fetch from "node-fetch";
该错误似乎发生在 node-fetch 本身内。
我尝试更改我的 package.json 中的测试脚本以匹配 Jest 文档对 ESM 模块的建议。 https://jestjs.io/docs/ecmascript-modules
package.json
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
该文档还建议更改 jest.config.js 中的 transform 属性以获取一个空对象,但是对于 typescript 和 ts-jest,我的 transform 对象如下所示:
jest.config.js
transform: { "^.+\\.ts?$": "ts-jest" }
如果我将其更改为空对象,我的所有测试都会中断。我对 CJS 与 ESM 不是很熟悉,因此我们将不胜感激。
【问题讨论】:
标签: javascript node.js typescript jestjs node-fetch