【问题标题】:node + ts-jest + ESM, jest.mock doing nothing节点 + ts-jest + ESM,jest.mock 什么都不做
【发布时间】:2022-04-17 05:38:46
【问题描述】:

我在 nodejs 上使用 ts-jest 和 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.
  });
});

我的笑话配置:

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

【问题讨论】:

    标签: node.js typescript jestjs ts-jest


    【解决方案1】:

    jest.mock 适用于 CJS,但不适用于 ESM。

    有一个jest.unstable_mockModule 和一个打开的 PR 将其变成一个稳定的 API,但它处于不确定状态(开玩笑的作者失去了动力)。

    更多详情:

    问题中的一些有价值的 cmets 可能会帮助您找到部分解决方案。

    它对我不起作用。我放弃了它,完全走了一条不同的路。

    【讨论】:

    • 我切换到vitest,它开箱即用。
    【解决方案2】:

    这是一个已知问题(如 https://github.com/facebook/jest/issues/10025 中所述)。

    基本上,问题在于 Jest 无法像使用 babel (https://github.com/facebook/jest/issues/10025#issuecomment-920401080) 那样在所有其他导入之前提升模拟。使用顶级 await 和 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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 2020-12-23
      • 2018-07-14
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      相关资源
      最近更新 更多