使用 JEST 和 ESM 的快速测试给出错误“TypeError:无法分配给对象 '[object Module]' 的只读属性 'sum'”

Fei*_*291 7 javascript node.js express jestjs es6-modules

我尝试使用 jest 来模拟导入的函数,但出现此错误,TypeError: Assignment to constant variable.或者TypeError: Cannot assign to read only property 'sum' of object '[object Module]',我希望获得在本测试中模拟的返回值

尝试1

import { jest } from '@jest/globals'
import * as util from "./util.js"

it("TypeError: Cannot assign to read only property 'sum' of object '[object Module]'", () => {
  jest.spyOn(util, "sum").mockImplementation(() => { return 2 })
  
  expect(sum(1, 2)).toBe(2);
})

Run Code Online (Sandbox Code Playgroud)

尝试2

import { jest } from '@jest/globals'
import { sum } from './util.js'

it("TypeError: Cannot assign to read only property 'sum' of object '[object Module]'", () => {
  jest.mock("./util.js", () => ({
    __esModule: true,
    sum: jest.fn().mockReturnValue(2),
  }));
  
  expect(sum(1, 2)).toBe(2);
})
Run Code Online (Sandbox Code Playgroud)

尝试3

import { jest } from '@jest/globals'
import { sum } from "./util.js"

it("TypeError: Assignment to constant variable.", () => {
  sum = jest.fn(() => { return 2 })
  expect(sum(1, 2)).toBe(2);
})
Run Code Online (Sandbox Code Playgroud)

我正在按照笑话文档https://jestjs.io/docs/ecmascript-modules来设置我的配置

包.json

{
  "type": "module",
  "scripts": {
    "test": "NODE_OPTIONS=--experimental-vm-modules jest"
  },
}
Run Code Online (Sandbox Code Playgroud)

笑话配置.js

module.exports = async () => {
  return {
    verbose: true,
    transform: {}
  };
};
Run Code Online (Sandbox Code Playgroud)

我创建了这个存储库用于复制https://github.com/fei1990a/jest-esm/tree/main

感谢您的任何帮助

thr*_*thr 4

这是我想出的解决方法。

import { jest } from "@jest/globals";

beforeAll(() => {
  jest.unstable_mockModule("./util.js", () => ({
    sum: jest.fn(() => { return 2 }),
  }));
});

afterAll(() => {
  jest.clearAllMocks();
});

test("should sum value be 2", async () => {
  const { sum } = await import("./util.js");
  expect(sum(1, 2)).toBe(2);
});
Run Code Online (Sandbox Code Playgroud)

参考: https: //github.com/facebook/jest/issues/10025