我正在尝试升级我的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")来获得Response对象。
const { Response } = jest.requireActual("node-fetch");
然而,使用新的更改后,我得到了以下错误信息:
"在类型“{}”上不存在属性“Response”。"
我尝试了更改为import语句,这似乎修复了该错误:
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的转换对象如下所示:
jest.config.js
transform: { "^.+\\.ts?$": "ts-jest" }
如果我将其更改为空对象,则所有测试都会失败。我对CJS与ESM并不十分熟悉,因此希望能得到帮助。
4 |从"node-fetch"导入获取;
同样适用于 - avenmia