在开玩笑中获取原始实施
我试图在ESM模块中暂时模拟Node-fetch,同时仍在重新审进原始实现,以便我可以访问真实的端点值。但是,此错误“必须使用导入来加载ES模块”。我认识到对ESM的嘲笑支持仍在待处理中 - 是否有任何方法可以结合当前节点,ES6和Jest的组合?
worker.ts(依赖项):
export default async () => {
const response = await fetch("http://example2.org");
return await response.json()
}
main.test.ts:
import { jest } from "@jest/globals";
jest.mock("node-fetch", () => {
return Promise.resolve({
json: () => Promise.resolve({ myItem: "abc" }),
})
})
import doWork from './worker.js';
import mockedFetch from 'node-fetch';
const originalFetch = jest.requireActual('node-fetch') as any;
test("Ensure mock", async () => {
const result = await doWork();
expect(result.myItem).toStrictEqual("abc");
expect(mockedFetch).toBeCalledTimes(1);
const response = await originalFetch("http://www.example.org");
expect(response.status).toBe(200);
const result2 = await doWork();
expect(result2.myItem).toStrictEqual("abc");
expect(mockedFetch).toBeCalledTimes(2);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,jest 不支持
jest.jest.mock在ESM
测试模块
这是合理的,因为
导入
的语义与需要
不同。所有导入均已提升,并将在任何模块代码之前在模块负载上进行评估。因此,在您的情况下,因为您使用的是
jest.mock
我认为您的测试代码已转换。在这种情况下,如果要使用非“ commonjs”软件包,则也应该对其进行更改。您可以在开玩笑的配置中更改transformignorepatterns
[]
。这意味着来自node_modules
的所有软件包都将通过变换。如果它太激进了,您可以选择像“ transformignorepatterns”那样忽略的特定模块:[“ node_modules/(?!!(node-fetch))”]
,但不要忘记传递依赖性。 ;)如果您有错误
jest.mock (
https://github.com.com/facebook/jestbook/jest/jest/issues/issues/2567
First, Jest doesn't support
jest.mock
in ESM module for testsThis is reasonable because
import
has different semantic thanrequire
. All imports are hoisted and will be evaluated at module load before any module code.So in your case because you are using
jest.mock
I assume that your test code are transformed. In this case, if you want to use non "CommonJS" package, you should transform it too. You can changetransformIgnorePatterns
in jest config to[]
. It means that all packages fromnode_modules
will go through transform. If it's too aggressive, you can pick specific modules which ignore like this"transformIgnorePatterns": [ "node_modules/(?!(node-fetch))" ]
but don't forget about transitive dependencies. ;)If you have error
just remove jest from import and use it as global variable or import it inside the module factory function
https://github.com/facebook/jest/issues/2567
const originalFetch = jest.requireActual('node-fetch')
to