我使用ts-jest和nodejs上的ESM导入。
问题是我的jest.mock不起作用,也不是在嘲弄。
import { jest } from "@jest/globals";
jest.mock("./helpers"); // I tried before or after import
import { fn } from "./helpers";
describe("SimpleTest", () => {
it("should work", () => {
console.log(fn); // => defined
console.log(fn.mockReturnValue); // => /!\ UNDEFINED, fn is not a jest mock.
});
});我的jest配置:
export default {
preset: "ts-jest/presets/default-esm",
extensionsToTreatAsEsm: [".ts"],
globals: {
"ts-jest": {
useESM: true,
},
},
}我使用的命令:
node --experimental-vm-modules --experimental-specifier-resolution=node $(yarn bin jest)
我使用节点v16.13.2和ts-jest 27.1.3。
发布于 2022-02-15 09:15:19
jest.mock为CJS工作,但不为ESM工作。
有一个jest.unstable_mockModule和一个打开的PR来将它转化为一个稳定的API,但是它处于一个边缘(Jest作者失去了动力)。
欲知更多详情:
在这个问题上的一些有价值的评论可能会帮助你找到一个部分的解决方案。
这对我没用。我放弃了,走了一条完全不同的路。
发布于 2022-04-16 21:38:46
这是一个已知的问题(正如https://github.com/facebook/jest/issues/10025中提到的)。
基本上,问题是Jest不能像使用babel (https://github.com/facebook/jest/issues/10025#issuecomment-920401080)那样在所有其他导入之前提升模拟。使用顶级的等待和jest.unstable_mockModule一起为我工作。
只需注意使用jest.unstable_mockModule的示例
import { jest } from "@jest/globals";
const mockFn = jest.fn();
jest.unstable_mockModule("./helpers", () => ({
fn: mockFn
}));
const { fn } = await import("./helpers"); // Needs to be after the mock is declared.https://stackoverflow.com/questions/70999696
复制相似问题