gpt4 book ai didi

javascript - 在 Jest 模拟期间获得原始实现

转载 作者:行者123 更新时间:2023-12-05 03:24:00 25 4
gpt4 key购买 nike

我正在尝试在 ESM 模块中临时模拟 Node 获取,同时仍在重新训练原始实现,以便我可以访问真实端点的值。但是,此错误与“必须使用导入加载 ES 模块”。我知道对 ESM 的 jest 支持仍然悬而未决 - 有什么方法可以在当前的 Node、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);
});

最佳答案

首先,开 Jest doesn't support jest.mock in ESM测试模块

Please note that we currently don't support jest.mock in a clean wayin ESM, but that is something we intend to add proper support for inthe future. Follow this issue for updates.

这是合理的,因为 importrequire 具有不同的语义。所有导入都会被提升,并将在模块加载时进行评估在任何模块代码之前

所以在您的情况下,因为您使用的是 jest.mock 我假设您的测试代码已转换。在这种情况下,如果你想使用非“CommonJS”包,你也应该转换它。您可以将 jest 配置中的 transformIgnorePatterns 更改为 []。这意味着来自 node_modules 的所有包都将经过转换。如果它过于激进,您可以选择像这样忽略的特定模块 "transformIgnorePatterns": [ "node_modules/(?!(node-fetch))"] 但不要忘记传递依赖项。 ;)

  • 添加/更改 jest 配置
  "transformIgnorePatterns": []
  • jest.mock 接受应该返回导出代码的模块工厂。在你的情况下,你应该这样写。
jest.mock("node-fetch", () => {
return {
__esModule: true,
default: jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ myItem: "abc" }),
})
),
};
});

如果有错误

The module factory of jest.mock() is not allowed to reference any out-of-scope variables

只需从 import 中删除 jest 并将其用作全局变量或将其导入到模块工厂函数中 https://github.com/facebook/jest/issues/2567

  • const originalFetch = jest.requireActual('node-fetch') 更改为
const originalFetch = jest.requireActual('node-fetch').default;

关于javascript - 在 Jest 模拟期间获得原始实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72383506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com